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