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