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