Make ParserNamespace an identifier
[yangtools.git] / parser / yang-parser-spi / src / main / java / org / opendaylight / yangtools / yang / parser / spi / meta / StmtContextUtils.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.parser.spi.meta;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Strings;
13 import com.google.common.base.VerifyException;
14 import com.google.common.collect.ImmutableList;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.List;
18 import java.util.Optional;
19 import java.util.Set;
20 import java.util.function.Predicate;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.common.QNameModule;
24 import org.opendaylight.yangtools.yang.common.Revision;
25 import org.opendaylight.yangtools.yang.common.YangVersion;
26 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
29 import org.opendaylight.yangtools.yang.model.api.stmt.KeyEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceEffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.UnknownStatement;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
43 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
44 import org.opendaylight.yangtools.yang.parser.spi.source.SourceParserNamespaces;
45
46 public final class StmtContextUtils {
47     private StmtContextUtils() {
48         // Hidden on purpose
49     }
50
51     @SuppressWarnings("unchecked")
52     public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
53             final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
54         for (final StmtContext<?, ?, ?> ctx : contexts) {
55             if (ctx.producesDeclared(declaredType)) {
56                 return (A) ctx.argument();
57             }
58         }
59         return null;
60     }
61
62     @SuppressWarnings("unchecked")
63     public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
64             final Class<D> declaredType) {
65         return ctx.producesDeclared(declaredType) ? (A) ctx.argument() : null;
66     }
67
68     public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
69             final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
70         return firstAttributeOf(ctx.allSubstatements(), declaredType);
71     }
72
73     @SuppressWarnings("unchecked")
74     public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstDeclaredSubstatement(
75             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
76         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
77             if (subStmtContext.producesDeclared(declaredType)) {
78                 return (StmtContext<A, ?, ?>) subStmtContext;
79             }
80         }
81         return null;
82     }
83
84     @SafeVarargs
85     @SuppressWarnings({ "rawtypes", "unchecked" })
86     public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
87             int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
88         if (startIndex >= types.length) {
89             return null;
90         }
91
92         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
93             if (subStmtContext.producesDeclared((Class) types[startIndex])) {
94                 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
95                         ++startIndex, types);
96             }
97         }
98         return null;
99     }
100
101     @SuppressWarnings("unchecked")
102     public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
103             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
104         final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
105         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
106             if (subStmtContext.producesDeclared(declaredType)) {
107                 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
108             }
109         }
110         return listBuilder.build();
111     }
112
113     @SuppressWarnings("unchecked")
114     public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
115             final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
116         final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
117         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
118             if (subStmtContext.producesDeclared(type)) {
119                 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
120             }
121         }
122         return listBuilder.build();
123     }
124
125     public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
126             final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
127         final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
128         listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
129         listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
130         return listBuilder.build();
131     }
132
133     @SuppressWarnings("unchecked")
134     public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
135             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
136         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
137             if (subStmtContext.producesDeclared(declaredType)) {
138                 return (StmtContext<A, ?, ?>) subStmtContext;
139             }
140         }
141         return null;
142     }
143
144     public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
145             final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType, int sublevel) {
146         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
147             if (sublevel == 1 && subStmtContext.producesDeclared(declaredType)) {
148                 return subStmtContext;
149             }
150             if (sublevel > 1) {
151                 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
152                         declaredType, --sublevel);
153                 if (result != null) {
154                     return result;
155                 }
156             }
157         }
158
159         return null;
160     }
161
162     public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
163             final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType) {
164         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
165             if (subStmtContext.producesDeclared(declaredType)) {
166                 return subStmtContext;
167             }
168
169             final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
170             if (result != null) {
171                 return result;
172             }
173         }
174
175         return null;
176     }
177
178     // FIXME: 8.0.0: This method goes back as far as YANGTOOLS-365, when we were build EffectiveStatements for
179     //               unsupported YANG extensions. We are not doing that anymore, do we still need this method? Also, it
180     //               is only used in augment support to disable mechanics on unknown nodes.
181     //
182     //               It would seem we can move this method to AbstractAugmentStatementSupport at the very least, but
183     //               also: augments are defined to operate on schema tree nodes, hence even if we have an
184     //               UnknownStatement, but its EffectiveStatement projection supports SchemaTreeAwareEffectiveStatement
185     //               we should operate normally -- the StatementSupport exposing such semantics is responsible for
186     //               arranging the backend details.
187     public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
188         StmtContext<?, ?, ?> current = stmtCtx;
189
190         while (true) {
191             final StmtContext<?, ?, ?> parent = current.coerceParentContext();
192             if (parent.getParentContext() == null) {
193                 return false;
194             }
195             if (isUnknownStatement(parent)) {
196                 return true;
197             }
198             current = parent;
199         }
200     }
201
202     /**
203      * Returns true if supplied statement context represents unknown statement,
204      * otherwise returns false.
205      *
206      * @param stmtCtx
207      *            statement context to be checked
208      * @return true if supplied statement context represents unknown statement,
209      *         otherwise false
210      * @throws NullPointerException
211      *             if supplied statement context is null
212      */
213     public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
214         return UnknownStatement.class.isAssignableFrom(stmtCtx.publicDefinition().getDeclaredRepresentationClass());
215     }
216
217     public static boolean checkFeatureSupport(final StmtContext<?, ?, ?> stmtContext,
218             final Set<QName> supportedFeatures) {
219         boolean isSupported = false;
220         boolean containsIfFeature = false;
221         for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
222             if (YangStmtMapping.IF_FEATURE.equals(stmt.publicDefinition())) {
223                 containsIfFeature = true;
224                 @SuppressWarnings("unchecked")
225                 final Predicate<Set<QName>> argument = (Predicate<Set<QName>>) stmt.getArgument();
226                 if (argument.test(supportedFeatures)) {
227                     isSupported = true;
228                 } else {
229                     isSupported = false;
230                     break;
231                 }
232             }
233         }
234
235         return !containsIfFeature || isSupported;
236     }
237
238     /**
239      * Checks whether statement context is a presence container or not.
240      *
241      * @param stmtCtx
242      *            statement context
243      * @return true if it is a presence container
244      */
245     public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
246         return stmtCtx.publicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
247     }
248
249     /**
250      * Checks whether statement context is a non-presence container or not.
251      *
252      * @param stmtCtx
253      *            statement context
254      * @return true if it is a non-presence container
255      */
256     public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
257         return stmtCtx.publicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
258     }
259
260     private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
261         return stmtCtx.hasSubstatement(PresenceEffectiveStatement.class);
262     }
263
264     /**
265      * Checks whether statement context is a mandatory leaf, choice, anyxml,
266      * list or leaf-list according to RFC6020 or not.
267      *
268      * @param stmtCtx
269      *            statement context
270      * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
271      *         according to RFC6020.
272      */
273     public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
274         if (!(stmtCtx.publicDefinition() instanceof YangStmtMapping)) {
275             return false;
276         }
277         switch ((YangStmtMapping) stmtCtx.publicDefinition()) {
278             case LEAF:
279             case CHOICE:
280             case ANYXML:
281                 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
282             case LIST:
283             case LEAF_LIST:
284                 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
285                 return minElements != null && minElements > 0;
286             default:
287                 return false;
288         }
289     }
290
291     /**
292      * Checks whether a statement context is a statement of supplied statement
293      * definition and whether it is not mandatory leaf, choice, anyxml, list or
294      * leaf-list according to RFC6020.
295      *
296      * @param stmtCtx
297      *            statement context
298      * @param stmtDef
299      *            statement definition
300      * @return true if supplied statement context is a statement of supplied
301      *         statement definition and if it is not mandatory leaf, choice,
302      *         anyxml, list or leaf-list according to RFC6020
303      */
304     public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
305             final StatementDefinition stmtDef) {
306         return stmtCtx.publicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
307     }
308
309     /**
310      * Checks whether at least one ancestor of a StatementContext matches one from a collection of statement
311      * definitions.
312      *
313      * @param stmt Statement context to be checked
314      * @param ancestorTypes collection of statement definitions
315      * @return true if at least one ancestor of a StatementContext matches one
316      *         from collection of statement definitions, otherwise false.
317      */
318     public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> stmt,
319             final Collection<StatementDefinition> ancestorTypes) {
320         requireNonNull(ancestorTypes);
321         StmtContext<?, ?, ?> current = stmt.getParentContext();
322         while (current != null) {
323             if (ancestorTypes.contains(current.publicDefinition())) {
324                 return true;
325             }
326             current = current.getParentContext();
327         }
328         return false;
329     }
330
331     /**
332      * Check whether all of StmtContext's {@code list} ancestors have a {@code key}.
333      *
334      * @param stmt EffectiveStmtCtx to be checked
335      * @param name Human-friendly statement name
336      * @throws SourceException if there is any keyless list ancestor
337      */
338     public static void validateNoKeylessListAncestorOf(final Mutable<?, ?, ?> stmt, final String name) {
339         requireNonNull(stmt);
340
341         // We do not expect this to by typically populated
342         final List<Mutable<?, ?, ?>> incomplete = new ArrayList<>(0);
343
344         Mutable<?, ?, ?> current = stmt.coerceParentContext();
345         Mutable<?, ?, ?> parent = current.getParentContext();
346         while (parent != null) {
347             if (YangStmtMapping.LIST == current.publicDefinition()
348                     && !current.hasSubstatement(KeyEffectiveStatement.class)) {
349                 if (ModelProcessingPhase.FULL_DECLARATION.isCompletedBy(current.getCompletedPhase())) {
350                     throw new SourceException(stmt, "%s %s is defined within a list that has no key statement", name,
351                         stmt.argument());
352                 }
353
354                 // Ancestor has not completed full declaration yet missing 'key' statement may materialize later
355                 incomplete.add(current);
356             }
357
358             current = parent;
359             parent = current.getParentContext();
360         }
361
362         // Deal with whatever incomplete ancestors we encountered
363         for (Mutable<?, ?, ?> ancestor : incomplete) {
364             // This check must complete during the ancestor's FULL_DECLARATION phase, i.e. the ancestor must not reach
365             // EFFECTIVE_MODEL until it is done.
366             final ModelActionBuilder action = ancestor.newInferenceAction(ModelProcessingPhase.FULL_DECLARATION);
367             action.apply(new InferenceAction() {
368                 @Override
369                 public void apply(final InferenceContext ctx) {
370                     if (!ancestor.hasSubstatement(KeyEffectiveStatement.class)) {
371                         throw new SourceException(stmt, "%s %s is defined within a list that has no key statement",
372                             name, stmt.argument());
373                     }
374                 }
375
376                 @Override
377                 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
378                     throw new VerifyException("Should never happen");
379                 }
380             });
381         }
382     }
383
384     /**
385      * Checks whether the parent of StmtContext is of specified type.
386      *
387      * @param ctx StmtContext to be checked
388      * @param parentType type of parent to check
389      * @return true if the parent of StmtContext is of specified type, otherwise false
390      */
391     public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
392         requireNonNull(parentType);
393         final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
394         return parentContext != null && parentType.equals(parentContext.publicDefinition());
395     }
396
397     /**
398      * Validates the specified statement context with regards to if-feature and when statement on list keys.
399      * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
400      * statement defined in a keyed list (a uses statement may add leaves into the list).
401      *
402      * <p>
403      * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
404      *
405      * @param ctx statement context to be validated
406      */
407     public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
408         if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
409             return;
410         }
411
412         final StmtContext<?, ?, ?> listStmtCtx = ctx.coerceParentContext();
413         final StmtContext<Set<QName>, ?, ?> keyStmtCtx = findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
414
415         if (YangStmtMapping.LEAF.equals(ctx.publicDefinition())) {
416             if (isListKey(ctx, keyStmtCtx)) {
417                 disallowIfFeatureAndWhenOnListKeys(ctx);
418             }
419         } else if (YangStmtMapping.USES.equals(ctx.publicDefinition())) {
420             findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
421                 if (isListKey(leafStmtCtx, keyStmtCtx)) {
422                     disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
423                 }
424             });
425         }
426     }
427
428     private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
429         return YangVersion.VERSION_1_1.equals(ctx.yangVersion()) && hasParentOfType(ctx, YangStmtMapping.LIST)
430                 && findFirstDeclaredSubstatement(ctx.coerceParentContext(), KeyStatement.class) != null;
431     }
432
433     private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
434             final StmtContext<Set<QName>, ?, ?> keyStmtCtx) {
435         return keyStmtCtx.getArgument().contains(leafStmtCtx.argument());
436     }
437
438     private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
439         leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
440             final StatementDefinition statementDef = leafSubstmtCtx.publicDefinition();
441             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
442                     || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx,
443                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
444                     statementDef.getStatementName(), leafStmtCtx.argument());
445         });
446     }
447
448     public static @NonNull QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
449         if (Strings.isNullOrEmpty(value)) {
450             return ctx.publicDefinition().getStatementName();
451         }
452
453         String prefix;
454         QNameModule qnameModule = null;
455         String localName = null;
456
457         final String[] namesParts = value.split(":");
458         switch (namesParts.length) {
459             case 1:
460                 localName = namesParts[0];
461                 qnameModule = getRootModuleQName(ctx);
462                 break;
463             default:
464                 prefix = namesParts[0];
465                 localName = namesParts[1];
466                 qnameModule = getModuleQNameByPrefix(ctx, prefix);
467                 // in case of unknown statement argument, we're not going to parse it
468                 if (qnameModule == null && isUnknownStatement(ctx)) {
469                     localName = value;
470                     qnameModule = getRootModuleQName(ctx);
471                 }
472                 if (qnameModule == null && ctx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
473                     ctx = ctx.getOriginalCtx().orElse(null);
474                     qnameModule = getModuleQNameByPrefix(ctx, prefix);
475                 }
476         }
477
478         return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx,
479             "Cannot resolve QNameModule for '%s'", value), localName);
480     }
481
482     /**
483      * Parse a YANG identifier string in context of a statement.
484      *
485      * @param ctx Statement context
486      * @param str String to be parsed
487      * @return An interned QName
488      * @throws NullPointerException if any of the arguments are null
489      * @throws SourceException if the string is not a valid YANG identifier
490      */
491     public static @NonNull QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
492         SourceException.throwIf(str.isEmpty(), ctx, "Identifier may not be an empty string");
493         return internedQName(ctx, str);
494     }
495
496     public static @NonNull QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String prefix,
497             final String localName) {
498         return internedQName(ctx,
499             InferenceException.throwIfNull(getModuleQNameByPrefix(ctx, prefix), ctx,
500                 "Cannot resolve QNameModule for '%s'", prefix),
501             localName);
502     }
503
504     /**
505      * Parse a YANG node identifier string in context of a statement.
506      *
507      * @param ctx Statement context
508      * @param str String to be parsed
509      * @return An interned QName
510      * @throws NullPointerException if any of the arguments are null
511      * @throws SourceException if the string is not a valid YANG node identifier
512      */
513     public static @NonNull QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
514         SourceException.throwIf(str.isEmpty(), ctx, "Node identifier may not be an empty string");
515
516         final int colon = str.indexOf(':');
517         if (colon == -1) {
518             return internedQName(ctx, str);
519         }
520
521         final String prefix = str.substring(0, colon);
522         SourceException.throwIf(prefix.isEmpty(), ctx, "String '%s' has an empty prefix", str);
523         final String localName = str.substring(colon + 1);
524         SourceException.throwIf(localName.isEmpty(), ctx, "String '%s' has an empty identifier", str);
525
526         return parseNodeIdentifier(ctx, prefix, localName);
527     }
528
529     private static @NonNull QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
530         return internedQName(ctx, getRootModuleQName(ctx), localName);
531     }
532
533     private static @NonNull QName internedQName(final CommonStmtCtx ctx, final QNameModule module,
534             final String localName) {
535         final QName template;
536         try {
537             template = QName.create(module, localName);
538         } catch (IllegalArgumentException e) {
539             throw new SourceException(ctx, e, "Invalid identifier '%s'", localName);
540         }
541         return template.intern();
542     }
543
544     public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
545         return ctx == null ? null : getModuleQName(ctx.getRoot());
546     }
547
548     public static @NonNull QNameModule getModuleQName(final @NonNull RootStmtContext<?, ?, ?> ctx) {
549         if (ctx.producesDeclared(ModuleStatement.class)) {
550             return lookupModuleQName(ctx, ctx);
551         } else if (ctx.producesDeclared(SubmoduleStatement.class)) {
552             final var belongsTo = ctx.getAllFromNamespace(SourceParserNamespaces.BELONGSTO_PREFIX_TO_MODULECTX);
553             if (belongsTo == null || belongsTo.isEmpty()) {
554                 throw new IllegalArgumentException(ctx + " does not have belongs-to linkage resolved");
555             }
556             return lookupModuleQName(ctx, belongsTo.values().iterator().next());
557         } else {
558             throw new IllegalArgumentException("Unsupported root " + ctx);
559         }
560     }
561
562     private static @NonNull QNameModule lookupModuleQName(final NamespaceStmtCtx storage,
563             final StmtContext<?, ?, ?> module) {
564         final var ret = storage.getFromNamespace(SourceParserNamespaces.MODULECTX_TO_QNAME, module);
565         if (ret == null) {
566             throw new IllegalArgumentException("Failed to look up QNameModule for " + module + " in " + storage);
567         }
568         return ret;
569     }
570
571     public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
572         final StmtContext<?, ?, ?> root = ctx.getRoot();
573         final StmtContext<?, ?, ?> importedModule = root.getFromNamespace(
574             SourceParserNamespaces.IMPORT_PREFIX_TO_MODULECTX, prefix);
575         final QNameModule qnameModule = ctx.getFromNamespace(SourceParserNamespaces.MODULECTX_TO_QNAME, importedModule);
576         if (qnameModule != null) {
577             return qnameModule;
578         }
579
580         if (root.producesDeclared(SubmoduleStatement.class)) {
581             return ctx.getFromNamespace(SourceParserNamespaces.MODULE_NAME_TO_QNAME,
582                 root.getFromNamespace(SourceParserNamespaces.BELONGSTO_PREFIX_TO_MODULE_NAME, prefix));
583         }
584
585         return null;
586     }
587
588     public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
589         Revision revision = null;
590         for (final StmtContext<?, ?, ?> subStmt : subStmts) {
591             if (subStmt.producesDeclared(RevisionStatement.class)) {
592                 if (revision == null && subStmt.argument() != null) {
593                     revision = (Revision) subStmt.argument();
594                 } else {
595                     final Revision subArg = (Revision) subStmt.argument();
596                     if (subArg != null && subArg.compareTo(revision) > 0) {
597                         revision = subArg;
598                     }
599                 }
600             }
601         }
602         return Optional.ofNullable(revision);
603     }
604 }