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