Move use of EffectiveStmtCtx.caerbannog()
[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.StatementDefinition;
26 import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceEffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.UnknownStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.UnrecognizedStatement;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Parent;
38 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
39 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
40 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
41 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
42 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
43
44 public final class StmtContextUtils {
45     private StmtContextUtils() {
46         // Hidden on purpose
47     }
48
49     @SuppressWarnings("unchecked")
50     public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
51             final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
52         for (final StmtContext<?, ?, ?> ctx : contexts) {
53             if (ctx.producesDeclared(declaredType)) {
54                 return (A) ctx.getStatementArgument();
55             }
56         }
57         return null;
58     }
59
60     @SuppressWarnings("unchecked")
61     public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
62             final Class<D> declaredType) {
63         return ctx.producesDeclared(declaredType) ? (A) ctx.getStatementArgument() : null;
64     }
65
66     public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
67             final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
68         return firstAttributeOf(ctx.allSubstatements(), declaredType);
69     }
70
71     @SuppressWarnings("unchecked")
72     public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstDeclaredSubstatement(
73             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
74         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
75             if (subStmtContext.producesDeclared(declaredType)) {
76                 return (StmtContext<A, ?, ?>) subStmtContext;
77             }
78         }
79         return null;
80     }
81
82     @SafeVarargs
83     @SuppressWarnings({ "rawtypes", "unchecked" })
84     public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
85             int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
86         if (startIndex >= types.length) {
87             return null;
88         }
89
90         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
91             if (subStmtContext.producesDeclared((Class) types[startIndex])) {
92                 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
93                         ++startIndex, types);
94             }
95         }
96         return null;
97     }
98
99     @SuppressWarnings("unchecked")
100     public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
101             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
102         final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
103         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
104             if (subStmtContext.producesDeclared(declaredType)) {
105                 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
106             }
107         }
108         return listBuilder.build();
109     }
110
111     @SuppressWarnings("unchecked")
112     public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
113             final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
114         final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
115         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
116             if (subStmtContext.producesDeclared(type)) {
117                 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
118             }
119         }
120         return listBuilder.build();
121     }
122
123     public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
124             final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
125         final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
126         listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
127         listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
128         return listBuilder.build();
129     }
130
131     @SuppressWarnings("unchecked")
132     public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
133             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
134         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
135             if (subStmtContext.producesDeclared(declaredType)) {
136                 return (StmtContext<A, ?, ?>) subStmtContext;
137             }
138         }
139         return null;
140     }
141
142     /**
143      * Searches for the first substatement of the specified type in the specified statement context.
144      * First, it tries to find the substatement in the effective substatements of the statement context.
145      * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
146      * the method returns null.
147      *
148      * @param stmtContext statement context to search in
149      * @param declaredType substatement type to search for
150      * @param <A> statement argument type
151      * @param <D> declared statement type
152      * @return statement context that was searched for or null if was not found
153      * @deprecated Use {@link StmtContext#findSubstatementArgument(Class)} instead.
154      */
155     @Deprecated(forRemoval = true)
156     public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
157             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
158         final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
159         return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
160                 declaredType);
161     }
162
163     public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
164             final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType, int sublevel) {
165         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
166             if (sublevel == 1 && subStmtContext.producesDeclared(declaredType)) {
167                 return subStmtContext;
168             }
169             if (sublevel > 1) {
170                 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
171                         declaredType, --sublevel);
172                 if (result != null) {
173                     return result;
174                 }
175             }
176         }
177
178         return null;
179     }
180
181     public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
182             final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType) {
183         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
184             if (subStmtContext.producesDeclared(declaredType)) {
185                 return subStmtContext;
186             }
187
188             final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
189             if (result != null) {
190                 return result;
191             }
192         }
193
194         return null;
195     }
196
197     public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
198         StmtContext<?, ?, ?> current = stmtCtx;
199
200         while (true) {
201             final StmtContext<?, ?, ?> parent = current.coerceParentContext();
202             if (parent.getParentContext() == null) {
203                 return false;
204             }
205             if (isUnknownStatement(parent)) {
206                 return true;
207             }
208             current = parent;
209         }
210     }
211
212     /**
213      * Returns true if supplied statement context represents unknown statement,
214      * otherwise returns false.
215      *
216      * @param stmtCtx
217      *            statement context to be checked
218      * @return true if supplied statement context represents unknown statement,
219      *         otherwise false
220      * @throws NullPointerException
221      *             if supplied statement context is null
222      */
223     public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
224         return UnknownStatement.class
225                 .isAssignableFrom(stmtCtx.getPublicDefinition().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.getPublicDefinition())) {
249                 containsIfFeature = true;
250                 @SuppressWarnings("unchecked")
251                 final Predicate<Set<QName>> argument = (Predicate<Set<QName>>) stmt.coerceStatementArgument();
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.getPublicDefinition() == 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.getPublicDefinition() == 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.getPublicDefinition() instanceof YangStmtMapping)) {
301             return false;
302         }
303         switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
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.getPublicDefinition().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.parent();
348         while (current != null) {
349             if (ancestorTypes.contains(current.publicDefinition())) {
350                 return true;
351             }
352             current = current.parent();
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         requireNonNull(ancestorChildType);
371
372         StmtContext<?, ?, ?> current = stmt.caerbannog().getParentContext();
373         StmtContext<?, ?, ?> parent = current.getParentContext();
374         while (parent != null) {
375             if (ancestorType.equals(current.getPublicDefinition())
376                     && !current.hasSubstatement(ancestorChildType.getEffectiveRepresentationClass())) {
377                 return false;
378             }
379
380             current = parent;
381             parent = current.getParentContext();
382         }
383
384         return true;
385     }
386
387     /**
388      * Checks whether the parent of EffectiveStmtCtx is of specified type.
389      *
390      * @param stmt EffectiveStmtCtx to be checked
391      * @param parentType type of parent to check
392      * @return true if the parent of StmtContext is of specified type, otherwise false
393      */
394     public static boolean hasParentOfType(final EffectiveStmtCtx.Current<?, ?> stmt,
395             final StatementDefinition parentType) {
396         return hasParentOfType(stmt.caerbannog(), parentType);
397     }
398
399     /**
400      * Checks whether the parent of StmtContext is of specified type.
401      *
402      * @param ctx StmtContext to be checked
403      * @param parentType type of parent to check
404      * @return true if the parent of StmtContext is of specified type, otherwise false
405      */
406     public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
407         requireNonNull(parentType);
408         final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
409         return parentContext != null && parentType.equals(parentContext.getPublicDefinition());
410     }
411
412     /**
413      * Validates the specified statement context with regards to if-feature and when statement on list keys.
414      * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
415      * statement defined in a keyed list (a uses statement may add leaves into the list).
416      *
417      * <p>
418      * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
419      *
420      * @param ctx statement context to be validated
421      */
422     public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
423         if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
424             return;
425         }
426
427         final StmtContext<?, ?, ?> listStmtCtx = ctx.coerceParentContext();
428         final StmtContext<Set<QName>, ?, ?> keyStmtCtx = findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
429
430         if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
431             if (isListKey(ctx, keyStmtCtx)) {
432                 disallowIfFeatureAndWhenOnListKeys(ctx);
433             }
434         } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
435             findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
436                 if (isListKey(leafStmtCtx, keyStmtCtx)) {
437                     disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
438                 }
439             });
440         }
441     }
442
443     private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
444         return YangVersion.VERSION_1_1.equals(ctx.getRootVersion()) && hasParentOfType(ctx, YangStmtMapping.LIST)
445                 && findFirstDeclaredSubstatement(ctx.coerceParentContext(), KeyStatement.class) != null;
446     }
447
448     private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
449             final StmtContext<Set<QName>, ?, ?> keyStmtCtx) {
450         return keyStmtCtx.coerceStatementArgument().contains(leafStmtCtx.getStatementArgument());
451     }
452
453     private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
454         leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
455             final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
456             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
457                     || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
458                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
459                     statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
460         });
461     }
462
463     public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
464         if (Strings.isNullOrEmpty(value)) {
465             return ctx.getPublicDefinition().getStatementName();
466         }
467
468         String prefix;
469         QNameModule qnameModule = null;
470         String localName = null;
471
472         final String[] namesParts = value.split(":");
473         switch (namesParts.length) {
474             case 1:
475                 localName = namesParts[0];
476                 qnameModule = getRootModuleQName(ctx);
477                 break;
478             default:
479                 prefix = namesParts[0];
480                 localName = namesParts[1];
481                 qnameModule = getModuleQNameByPrefix(ctx, prefix);
482                 // in case of unknown statement argument, we're not going to parse it
483                 if (qnameModule == null && isUnknownStatement(ctx)) {
484                     localName = value;
485                     qnameModule = getRootModuleQName(ctx);
486                 }
487                 if (qnameModule == null && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
488                     ctx = ctx.getOriginalCtx().orElse(null);
489                     qnameModule = getModuleQNameByPrefix(ctx, prefix);
490                 }
491         }
492
493         return internedQName(ctx,
494             InferenceException.throwIfNull(qnameModule, ctx.getStatementSourceReference(),
495             "Cannot resolve QNameModule for '%s'", value), localName);
496     }
497
498     /**
499      * Parse a YANG identifier string in context of a statement.
500      *
501      * @param ctx Statement context
502      * @param str String to be parsed
503      * @return An interned QName
504      * @throws NullPointerException if any of the arguments are null
505      * @throws SourceException if the string is not a valid YANG identifier
506      */
507     public static QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
508         SourceException.throwIf(str.isEmpty(), ctx.getStatementSourceReference(),
509                 "Identifier may not be an empty string");
510         return internedQName(ctx, str);
511     }
512
513     public static QName parseNodeIdentifier(StmtContext<?, ?, ?> ctx, final String prefix,
514             final String localName) {
515         final QNameModule module = getModuleQNameByPrefix(ctx, prefix);
516         if (module != null) {
517             return internedQName(ctx, module, localName);
518         }
519
520         if (ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
521             final Optional<? extends StmtContext<?, ?, ?>> optOrigCtx = ctx.getOriginalCtx();
522             if (optOrigCtx.isPresent()) {
523                 ctx = optOrigCtx.get();
524                 final QNameModule origModule = getModuleQNameByPrefix(ctx, prefix);
525                 if (origModule != null) {
526                     return internedQName(ctx, origModule, localName);
527                 }
528             }
529         }
530
531         throw new InferenceException(ctx.getStatementSourceReference(), "Cannot resolve QNameModule for '%s'", prefix);
532     }
533
534     /**
535      * Parse a YANG node identifier string in context of a statement.
536      *
537      * @param ctx Statement context
538      * @param str String to be parsed
539      * @return An interned QName
540      * @throws NullPointerException if any of the arguments are null
541      * @throws SourceException if the string is not a valid YANG node identifier
542      */
543     public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
544         SourceException.throwIf(str.isEmpty(), ctx.getStatementSourceReference(),
545                 "Node identifier may not be an empty string");
546
547         final int colon = str.indexOf(':');
548         if (colon == -1) {
549             return internedQName(ctx, str);
550         }
551
552         final String prefix = str.substring(0, colon);
553         SourceException.throwIf(prefix.isEmpty(), ctx.getStatementSourceReference(),
554             "String '%s' has an empty prefix", str);
555         final String localName = str.substring(colon + 1);
556         SourceException.throwIf(localName.isEmpty(), ctx.getStatementSourceReference(),
557             "String '%s' has an empty identifier", str);
558
559         return parseNodeIdentifier(ctx, prefix, localName);
560     }
561
562     private static QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
563         return internedQName(ctx, getRootModuleQName(ctx), localName);
564     }
565
566     private static QName internedQName(final StmtContext<?, ?, ?> ctx, final QNameModule module,
567             final String localName) {
568         final QName template;
569         try {
570             template = QName.create(module, localName);
571         } catch (IllegalArgumentException e) {
572             throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid identifier '%s'", localName);
573         }
574         return template.intern();
575     }
576
577     public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
578         if (ctx == null) {
579             return null;
580         }
581
582         final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
583         final QNameModule qnameModule;
584
585         if (rootCtx.producesDeclared(ModuleStatement.class)) {
586             qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
587         } else if (rootCtx.producesDeclared(SubmoduleStatement.class)) {
588             final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
589                 BelongsToStatement.class);
590             qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
591         } else {
592             qnameModule = null;
593         }
594
595         checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
596         return qnameModule;
597     }
598
599     public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
600         final StmtContext<?, ?, ?> root = ctx.getRoot();
601         final StmtContext<?, ?, ?> importedModule = root.getFromNamespace(ImportPrefixToModuleCtx.class, prefix);
602         final QNameModule qnameModule = ctx.getFromNamespace(ModuleCtxToModuleQName.class, importedModule);
603         if (qnameModule != null) {
604             return qnameModule;
605         }
606
607         if (root.producesDeclared(SubmoduleStatement.class)) {
608             final String moduleName = root.getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
609             return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
610         }
611
612         return null;
613     }
614
615     public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
616         Revision revision = null;
617         for (final StmtContext<?, ?, ?> subStmt : subStmts) {
618             if (subStmt.producesDeclared(RevisionStatement.class)) {
619                 if (revision == null && subStmt.getStatementArgument() != null) {
620                     revision = (Revision) subStmt.getStatementArgument();
621                 } else {
622                     final Revision subArg = (Revision) subStmt.getStatementArgument();
623                     if (subArg != null && subArg.compareTo(revision) > 0) {
624                         revision = subArg;
625                     }
626                 }
627             }
628         }
629         return Optional.ofNullable(revision);
630     }
631 }