Enable findbugs in more artifacts
[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.getParentContext().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.getStatementArgument();
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.getParentContext();
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.getParentContext(), KeyStatement.class) != null;
451     }
452
453     private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
454             final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
455         for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
456             if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
457                 return true;
458             }
459         }
460
461         return false;
462     }
463
464     private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
465         leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
466             final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
467             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
468                     || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
469                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
470                     statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
471         });
472     }
473
474     public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
475         if (Strings.isNullOrEmpty(value)) {
476             return ctx.getPublicDefinition().getStatementName();
477         }
478
479         String prefix;
480         QNameModule qnameModule = null;
481         String localName = null;
482
483         final String[] namesParts = value.split(":");
484         switch (namesParts.length) {
485             case 1:
486                 localName = namesParts[0];
487                 qnameModule = StmtContextUtils.getRootModuleQName(ctx);
488                 break;
489             default:
490                 prefix = namesParts[0];
491                 localName = namesParts[1];
492                 qnameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
493                 // in case of unknown statement argument, we're not going to parse it
494                 if (qnameModule == null && isUnknownStatement(ctx)) {
495                     localName = value;
496                     qnameModule = StmtContextUtils.getRootModuleQName(ctx);
497                 }
498                 if (qnameModule == null && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
499                     ctx = ctx.getOriginalCtx().orElse(null);
500                     qnameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
501                 }
502         }
503
504         return internedQName(ctx,
505             InferenceException.throwIfNull(qnameModule, ctx.getStatementSourceReference(),
506             "Cannot resolve QNameModule for '%s'", value), localName);
507     }
508
509     /**
510      * Parse a YANG identifier string in context of a statement.
511      *
512      * @param ctx Statement context
513      * @param str String to be parsed
514      * @return An interned QName
515      * @throws NullPointerException if any of the arguments are null
516      * @throws SourceException if the string is not a valid YANG identifier
517      */
518     public static QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
519         SourceException.throwIf(str.isEmpty(), ctx.getStatementSourceReference(),
520                 "Identifier may not be an empty string");
521         checkIdentifierString(ctx, str);
522         return internedQName(ctx, str);
523     }
524
525     /**
526      * Parse a YANG node identifier string in context of a statement.
527      *
528      * @param ctx Statement context
529      * @param str String to be parsed
530      * @return An interned QName
531      * @throws NullPointerException if any of the arguments are null
532      * @throws SourceException if the string is not a valid YANG node identifier
533      */
534     public static QName parseNodeIdentifier(StmtContext<?, ?, ?> ctx, final String str) {
535         SourceException.throwIf(str.isEmpty(), ctx.getStatementSourceReference(),
536                 "Node identifier may not be an empty string");
537
538         final int colon = str.indexOf(':');
539         if (colon == -1) {
540             checkIdentifierString(ctx, str);
541             return internedQName(ctx, str);
542         }
543
544         final String prefix = str.substring(0, colon);
545         SourceException.throwIf(prefix.isEmpty(), ctx.getStatementSourceReference(),
546             "String '%s' has an empty prefix", str);
547         final String localName = str.substring(colon + 1);
548         SourceException.throwIf(localName.isEmpty(), ctx.getStatementSourceReference(),
549             "String '%s' has an empty identifier", str);
550         checkIdentifierString(ctx, localName);
551
552         final QNameModule module = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
553         if (module != null) {
554             return internedQName(ctx, module, localName);
555         }
556
557         if (ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
558             final Optional<StmtContext<?, ?, ?>> optOrigCtx = ctx.getOriginalCtx();
559             if (optOrigCtx.isPresent()) {
560                 ctx = optOrigCtx.get();
561                 final QNameModule origModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
562                 if (origModule != null) {
563                     return internedQName(ctx, origModule, localName);
564                 }
565             }
566         }
567
568         throw new InferenceException(ctx.getStatementSourceReference(), "Cannot resolve QNameModule for '%s'", str);
569     }
570
571     private static void checkIdentifierString(final StmtContext<?, ?, ?> ctx, final String str) {
572         SourceException.throwIf(!IDENTIFIER_START.matches(str.charAt(0)) || NOT_IDENTIFIER_PART.indexIn(str, 1) != -1,
573             ctx.getStatementSourceReference(), "String '%s' is not a valid identifier", str);
574     }
575
576     private static QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
577         return internedQName(ctx, StmtContextUtils.getRootModuleQName(ctx), localName);
578     }
579
580     private static QName internedQName(final StmtContext<?, ?, ?> ctx, final QNameModule module,
581             final String localName) {
582         return ctx.getFromNamespace(QNameCacheNamespace.class, QName.create(module, localName));
583     }
584
585     public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
586         if (ctx == null) {
587             return null;
588         }
589
590         final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
591         final QNameModule qnameModule;
592
593         if (producesDeclared(rootCtx, ModuleStatement.class)) {
594             qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
595         } else if (producesDeclared(rootCtx, SubmoduleStatement.class)) {
596             final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
597                 BelongsToStatement.class);
598             qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
599         } else {
600             qnameModule = null;
601         }
602
603         checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
604         return qnameModule;
605     }
606
607     public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
608         final StmtContext<?, ?, ?> importedModule = ctx.getRoot().getFromNamespace(ImportPrefixToModuleCtx.class,
609             prefix);
610         final QNameModule qnameModule = ctx.getFromNamespace(ModuleCtxToModuleQName.class, importedModule);
611         if (qnameModule != null) {
612             return qnameModule;
613         }
614
615         if (producesDeclared(ctx.getRoot(), SubmoduleStatement.class)) {
616             final String moduleName = ctx.getRoot().getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
617             return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
618         }
619
620         return null;
621     }
622
623     public static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
624         final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
625         if (qNameModule != null) {
626             // creates SourceIdentifier for a module
627             return RevisionSourceIdentifier.create((String) root.getStatementArgument(), qNameModule.getRevision());
628         }
629
630         // creates SourceIdentifier for a submodule
631         final Optional<Revision> revision = getLatestRevision(root.declaredSubstatements());
632         return RevisionSourceIdentifier.create((String) root.getStatementArgument(), revision);
633     }
634
635     public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
636         Revision revision = null;
637         for (final StmtContext<?, ?, ?> subStmt : subStmts) {
638             if (subStmt.getPublicDefinition().getDeclaredRepresentationClass().isAssignableFrom(
639                     RevisionStatement.class)) {
640                 if (revision == null && subStmt.getStatementArgument() != null) {
641                     revision = (Revision) subStmt.getStatementArgument();
642                 } else if (subStmt.getStatementArgument() != null
643                         && ((Revision) subStmt.getStatementArgument()).compareTo(revision) > 0) {
644                     revision = (Revision) subStmt.getStatementArgument();
645                 }
646             }
647         }
648         return Optional.ofNullable(revision);
649     }
650 }