Deprecate StmtContextUtils.producesDeclared() for removal
[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.PresenceStatement;
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.model.repo.api.RevisionSourceIdentifier;
38 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
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.getStatementArgument();
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.getStatementArgument() : 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     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 (producesDeclared(subStmtContext, 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      */
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 findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
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                 @SuppressWarnings("unchecked")
383                 final Class<D> ancestorChildTypeClass = (Class<D>) ancestorChildType.getDeclaredRepresentationClass();
384                 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
385                     return false;
386                 }
387             }
388
389             current = parent;
390             parent = current.getParentContext();
391         }
392
393         return true;
394     }
395
396     /**
397      * Checks whether the parent of StmtContext is of specified type.
398      *
399      * @param ctx
400      *            StmtContext to be checked
401      * @param parentType
402      *            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.getPublicDefinition());
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.getPublicDefinition())) {
430             if (isListKey(ctx, keyStmtCtx)) {
431                 disallowIfFeatureAndWhenOnListKeys(ctx);
432             }
433         } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
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.getRootVersion()) && 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.coerceStatementArgument().contains(leafStmtCtx.getStatementArgument());
450     }
451
452     private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
453         leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
454             final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
455             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
456                     || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
457                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
458                     statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
459         });
460     }
461
462     public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
463         if (Strings.isNullOrEmpty(value)) {
464             return ctx.getPublicDefinition().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.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
487                     ctx = ctx.getOriginalCtx().orElse(null);
488                     qnameModule = getModuleQNameByPrefix(ctx, prefix);
489                 }
490         }
491
492         return internedQName(ctx,
493             InferenceException.throwIfNull(qnameModule, ctx.getStatementSourceReference(),
494             "Cannot resolve QNameModule for '%s'", value), localName);
495     }
496
497     /**
498      * Parse a YANG identifier string in context of a statement.
499      *
500      * @param ctx Statement context
501      * @param str String to be parsed
502      * @return An interned QName
503      * @throws NullPointerException if any of the arguments are null
504      * @throws SourceException if the string is not a valid YANG identifier
505      */
506     public static QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
507         SourceException.throwIf(str.isEmpty(), ctx.getStatementSourceReference(),
508                 "Identifier may not be an empty string");
509         return internedQName(ctx, str);
510     }
511
512     public static QName parseNodeIdentifier(StmtContext<?, ?, ?> ctx, final String prefix,
513             final String localName) {
514         final QNameModule module = getModuleQNameByPrefix(ctx, prefix);
515         if (module != null) {
516             return internedQName(ctx, module, localName);
517         }
518
519         if (ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
520             final Optional<? extends StmtContext<?, ?, ?>> optOrigCtx = ctx.getOriginalCtx();
521             if (optOrigCtx.isPresent()) {
522                 ctx = optOrigCtx.get();
523                 final QNameModule origModule = getModuleQNameByPrefix(ctx, prefix);
524                 if (origModule != null) {
525                     return internedQName(ctx, origModule, localName);
526                 }
527             }
528         }
529
530         throw new InferenceException(ctx.getStatementSourceReference(), "Cannot resolve QNameModule for '%s'", prefix);
531     }
532
533     /**
534      * Parse a YANG node identifier string in context of a statement.
535      *
536      * @param ctx Statement context
537      * @param str String to be parsed
538      * @return An interned QName
539      * @throws NullPointerException if any of the arguments are null
540      * @throws SourceException if the string is not a valid YANG node identifier
541      */
542     public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
543         SourceException.throwIf(str.isEmpty(), ctx.getStatementSourceReference(),
544                 "Node identifier may not be an empty string");
545
546         final int colon = str.indexOf(':');
547         if (colon == -1) {
548             return internedQName(ctx, str);
549         }
550
551         final String prefix = str.substring(0, colon);
552         SourceException.throwIf(prefix.isEmpty(), ctx.getStatementSourceReference(),
553             "String '%s' has an empty prefix", str);
554         final String localName = str.substring(colon + 1);
555         SourceException.throwIf(localName.isEmpty(), ctx.getStatementSourceReference(),
556             "String '%s' has an empty identifier", str);
557
558         return parseNodeIdentifier(ctx, prefix, localName);
559     }
560
561     private static QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
562         return internedQName(ctx, getRootModuleQName(ctx), localName);
563     }
564
565     private static QName internedQName(final StmtContext<?, ?, ?> ctx, final QNameModule module,
566             final String localName) {
567         final QName template;
568         try {
569             template = QName.create(module, localName);
570         } catch (IllegalArgumentException e) {
571             throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid identifier '%s'", localName);
572         }
573         return template.intern();
574     }
575
576     public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
577         if (ctx == null) {
578             return null;
579         }
580
581         final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
582         final QNameModule qnameModule;
583
584         if (rootCtx.producesDeclared(ModuleStatement.class)) {
585             qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
586         } else if (rootCtx.producesDeclared(SubmoduleStatement.class)) {
587             final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
588                 BelongsToStatement.class);
589             qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
590         } else {
591             qnameModule = null;
592         }
593
594         checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
595         return qnameModule;
596     }
597
598     public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
599         final StmtContext<?, ?, ?> importedModule = ctx.getRoot().getFromNamespace(ImportPrefixToModuleCtx.class,
600             prefix);
601         final QNameModule qnameModule = ctx.getFromNamespace(ModuleCtxToModuleQName.class, importedModule);
602         if (qnameModule != null) {
603             return qnameModule;
604         }
605
606         final StmtContext<?, ?, ?> root = ctx.getRoot();
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 SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
616         final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
617         if (qNameModule != null) {
618             // creates SourceIdentifier for a module
619             return RevisionSourceIdentifier.create((String) root.getStatementArgument(), qNameModule.getRevision());
620         }
621
622         // creates SourceIdentifier for a submodule
623         final Optional<Revision> revision = getLatestRevision(root.declaredSubstatements());
624         return RevisionSourceIdentifier.create((String) root.getStatementArgument(), revision);
625     }
626
627     public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
628         Revision revision = null;
629         for (final StmtContext<?, ?, ?> subStmt : subStmts) {
630             if (subStmt.producesDeclared(RevisionStatement.class)) {
631                 if (revision == null && subStmt.getStatementArgument() != null) {
632                     revision = (Revision) subStmt.getStatementArgument();
633                 } else {
634                     final Revision subArg = (Revision) subStmt.getStatementArgument();
635                     if (subArg != null && subArg.compareTo(revision) > 0) {
636                         revision = subArg;
637                     }
638                 }
639             }
640         }
641         return Optional.ofNullable(revision);
642     }
643 }