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