Move list/key checks to onStatementAdded()
[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.base.VerifyException;
15 import com.google.common.collect.ImmutableList;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.List;
19 import java.util.Optional;
20 import java.util.Set;
21 import java.util.function.Predicate;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.common.QNameModule;
24 import org.opendaylight.yangtools.yang.common.Revision;
25 import org.opendaylight.yangtools.yang.common.YangVersion;
26 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
29 import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.KeyEffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceEffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
39 import org.opendaylight.yangtools.yang.model.api.stmt.UnknownStatement;
40 import org.opendaylight.yangtools.yang.model.api.stmt.UnrecognizedStatement;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
49 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
50
51 public final class StmtContextUtils {
52     private StmtContextUtils() {
53         // Hidden on purpose
54     }
55
56     @SuppressWarnings("unchecked")
57     public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
58             final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
59         for (final StmtContext<?, ?, ?> ctx : contexts) {
60             if (ctx.producesDeclared(declaredType)) {
61                 return (A) ctx.argument();
62             }
63         }
64         return null;
65     }
66
67     @SuppressWarnings("unchecked")
68     public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
69             final Class<D> declaredType) {
70         return ctx.producesDeclared(declaredType) ? (A) ctx.argument() : null;
71     }
72
73     public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
74             final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
75         return firstAttributeOf(ctx.allSubstatements(), declaredType);
76     }
77
78     @SuppressWarnings("unchecked")
79     public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstDeclaredSubstatement(
80             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
81         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
82             if (subStmtContext.producesDeclared(declaredType)) {
83                 return (StmtContext<A, ?, ?>) subStmtContext;
84             }
85         }
86         return null;
87     }
88
89     @SafeVarargs
90     @SuppressWarnings({ "rawtypes", "unchecked" })
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 (subStmtContext.producesDeclared((Class) 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 (subStmtContext.producesDeclared(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 (subStmtContext.producesDeclared(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 (subStmtContext.producesDeclared(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      * @deprecated Use {@link BoundStmtCtx#findSubstatementArgument(Class)} instead.
161      */
162     @Deprecated(forRemoval = true)
163     public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
164             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
165         final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
166         return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
167                 declaredType);
168     }
169
170     public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
171             final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType, int sublevel) {
172         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
173             if (sublevel == 1 && subStmtContext.producesDeclared(declaredType)) {
174                 return subStmtContext;
175             }
176             if (sublevel > 1) {
177                 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
178                         declaredType, --sublevel);
179                 if (result != null) {
180                     return result;
181                 }
182             }
183         }
184
185         return null;
186     }
187
188     public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
189             final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType) {
190         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
191             if (subStmtContext.producesDeclared(declaredType)) {
192                 return subStmtContext;
193             }
194
195             final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
196             if (result != null) {
197                 return result;
198             }
199         }
200
201         return null;
202     }
203
204     public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
205         StmtContext<?, ?, ?> current = stmtCtx;
206
207         while (true) {
208             final StmtContext<?, ?, ?> parent = current.coerceParentContext();
209             if (parent.getParentContext() == null) {
210                 return false;
211             }
212             if (isUnknownStatement(parent)) {
213                 return true;
214             }
215             current = parent;
216         }
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.isAssignableFrom(stmtCtx.publicDefinition().getDeclaredRepresentationClass());
232     }
233
234     /**
235      * Returns true if supplied statement context represents unrecognized
236      * statement, otherwise returns false.
237      *
238      * @param stmtCtx
239      *            statement context to be checked
240      * @return true if supplied statement context represents unrecognized
241      *         statement, otherwise false
242      * @throws NullPointerException
243      *             if supplied statement context is null
244      */
245     public static boolean isUnrecognizedStatement(final StmtContext<?, ?, ?> stmtCtx) {
246         return stmtCtx.producesDeclared(UnrecognizedStatement.class);
247     }
248
249     public static boolean checkFeatureSupport(final StmtContext<?, ?, ?> stmtContext,
250             final Set<QName> supportedFeatures) {
251         boolean isSupported = false;
252         boolean containsIfFeature = false;
253         for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
254             if (YangStmtMapping.IF_FEATURE.equals(stmt.publicDefinition())) {
255                 containsIfFeature = true;
256                 @SuppressWarnings("unchecked")
257                 final Predicate<Set<QName>> argument = (Predicate<Set<QName>>) stmt.getArgument();
258                 if (argument.test(supportedFeatures)) {
259                     isSupported = true;
260                 } else {
261                     isSupported = false;
262                     break;
263                 }
264             }
265         }
266
267         return !containsIfFeature || isSupported;
268     }
269
270     /**
271      * Checks whether statement context is a presence container or not.
272      *
273      * @param stmtCtx
274      *            statement context
275      * @return true if it is a presence container
276      */
277     public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
278         return stmtCtx.publicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
279     }
280
281     /**
282      * Checks whether statement context is a non-presence container or not.
283      *
284      * @param stmtCtx
285      *            statement context
286      * @return true if it is a non-presence container
287      */
288     public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
289         return stmtCtx.publicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
290     }
291
292     private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
293         return stmtCtx.hasSubstatement(PresenceEffectiveStatement.class);
294     }
295
296     /**
297      * Checks whether statement context is a mandatory leaf, choice, anyxml,
298      * list or leaf-list according to RFC6020 or not.
299      *
300      * @param stmtCtx
301      *            statement context
302      * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
303      *         according to RFC6020.
304      */
305     public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
306         if (!(stmtCtx.publicDefinition() instanceof YangStmtMapping)) {
307             return false;
308         }
309         switch ((YangStmtMapping) stmtCtx.publicDefinition()) {
310             case LEAF:
311             case CHOICE:
312             case ANYXML:
313                 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
314             case LIST:
315             case LEAF_LIST:
316                 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
317                 return minElements != null && minElements > 0;
318             default:
319                 return false;
320         }
321     }
322
323     /**
324      * Checks whether a statement context is a statement of supplied statement
325      * definition and whether it is not mandatory leaf, choice, anyxml, list or
326      * leaf-list according to RFC6020.
327      *
328      * @param stmtCtx
329      *            statement context
330      * @param stmtDef
331      *            statement definition
332      * @return true if supplied statement context is a statement of supplied
333      *         statement definition and if it is not mandatory leaf, choice,
334      *         anyxml, list or leaf-list according to RFC6020
335      */
336     public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
337             final StatementDefinition stmtDef) {
338         return stmtCtx.publicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
339     }
340
341     /**
342      * Checks whether at least one ancestor of a StatementContext matches one from a collection of statement
343      * definitions.
344      *
345      * @param stmt Statement context to be checked
346      * @param ancestorTypes collection of statement definitions
347      * @return true if at least one ancestor of a StatementContext matches one
348      *         from collection of statement definitions, otherwise false.
349      */
350     public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> stmt,
351             final Collection<StatementDefinition> ancestorTypes) {
352         requireNonNull(ancestorTypes);
353         StmtContext<?, ?, ?> current = stmt.getParentContext();
354         while (current != null) {
355             if (ancestorTypes.contains(current.publicDefinition())) {
356                 return true;
357             }
358             current = current.getParentContext();
359         }
360         return false;
361     }
362
363     /**
364      * Check whether all of StmtContext's {@code list} ancestors have a {@code key}.
365      *
366      * @param stmt EffectiveStmtCtx to be checked
367      * @param name Human-friendly statement name
368      * @throws SourceException if there is any keyless list ancestor
369      */
370     public static void validateNoKeylessListAncestorOf(final Mutable<?, ?, ?> stmt, final String name) {
371         requireNonNull(stmt);
372
373         // We do not expect this to by typically populated
374         final List<Mutable<?, ?, ?>> incomplete = new ArrayList<>(0);
375
376         Mutable<?, ?, ?> current = stmt.coerceParentContext();
377         Mutable<?, ?, ?> parent = current.getParentContext();
378         while (parent != null) {
379             if (YangStmtMapping.LIST == current.publicDefinition()
380                     && !current.hasSubstatement(KeyEffectiveStatement.class)) {
381                 if (ModelProcessingPhase.FULL_DECLARATION.isCompletedBy(current.getCompletedPhase())) {
382                     throw new SourceException(stmt, "%s %s is defined within a list that has no key statement", name,
383                         stmt.argument());
384                 }
385
386                 // Ancestor has not completed full declaration yet missing 'key' statement may materialize later
387                 incomplete.add(current);
388             }
389
390             current = parent;
391             parent = current.getParentContext();
392         }
393
394         // Deal with whatever incomplete ancestors we encountered
395         for (Mutable<?, ?, ?> ancestor : incomplete) {
396             // This check must complete during the ancestor's FULL_DECLARATION phase, i.e. the ancestor must not reach
397             // EFFECTIVE_MODEL until it is done.
398             final ModelActionBuilder action = ancestor.newInferenceAction(ModelProcessingPhase.FULL_DECLARATION);
399             action.apply(new InferenceAction() {
400                 @Override
401                 public void apply(final InferenceContext ctx) {
402                     if (!ancestor.hasSubstatement(KeyEffectiveStatement.class)) {
403                         throw new SourceException(stmt, "%s %s is defined within a list that has no key statement",
404                             name, stmt.argument());
405                     }
406                 }
407
408                 @Override
409                 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
410                     throw new VerifyException("Should never happen");
411                 }
412             });
413         }
414     }
415
416     /**
417      * Checks whether the parent of StmtContext is of specified type.
418      *
419      * @param ctx StmtContext to be checked
420      * @param parentType type of parent to check
421      * @return true if the parent of StmtContext is of specified type, otherwise false
422      */
423     public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
424         requireNonNull(parentType);
425         final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
426         return parentContext != null && parentType.equals(parentContext.publicDefinition());
427     }
428
429     /**
430      * Validates the specified statement context with regards to if-feature and when statement on list keys.
431      * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
432      * statement defined in a keyed list (a uses statement may add leaves into the list).
433      *
434      * <p>
435      * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
436      *
437      * @param ctx statement context to be validated
438      */
439     public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
440         if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
441             return;
442         }
443
444         final StmtContext<?, ?, ?> listStmtCtx = ctx.coerceParentContext();
445         final StmtContext<Set<QName>, ?, ?> keyStmtCtx = findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
446
447         if (YangStmtMapping.LEAF.equals(ctx.publicDefinition())) {
448             if (isListKey(ctx, keyStmtCtx)) {
449                 disallowIfFeatureAndWhenOnListKeys(ctx);
450             }
451         } else if (YangStmtMapping.USES.equals(ctx.publicDefinition())) {
452             findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
453                 if (isListKey(leafStmtCtx, keyStmtCtx)) {
454                     disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
455                 }
456             });
457         }
458     }
459
460     private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
461         return YangVersion.VERSION_1_1.equals(ctx.yangVersion()) && hasParentOfType(ctx, YangStmtMapping.LIST)
462                 && findFirstDeclaredSubstatement(ctx.coerceParentContext(), KeyStatement.class) != null;
463     }
464
465     private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
466             final StmtContext<Set<QName>, ?, ?> keyStmtCtx) {
467         return keyStmtCtx.getArgument().contains(leafStmtCtx.argument());
468     }
469
470     private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
471         leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
472             final StatementDefinition statementDef = leafSubstmtCtx.publicDefinition();
473             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
474                     || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx,
475                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
476                     statementDef.getStatementName(), leafStmtCtx.argument());
477         });
478     }
479
480     public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
481         if (Strings.isNullOrEmpty(value)) {
482             return ctx.publicDefinition().getStatementName();
483         }
484
485         String prefix;
486         QNameModule qnameModule = null;
487         String localName = null;
488
489         final String[] namesParts = value.split(":");
490         switch (namesParts.length) {
491             case 1:
492                 localName = namesParts[0];
493                 qnameModule = getRootModuleQName(ctx);
494                 break;
495             default:
496                 prefix = namesParts[0];
497                 localName = namesParts[1];
498                 qnameModule = getModuleQNameByPrefix(ctx, prefix);
499                 // in case of unknown statement argument, we're not going to parse it
500                 if (qnameModule == null && isUnknownStatement(ctx)) {
501                     localName = value;
502                     qnameModule = getRootModuleQName(ctx);
503                 }
504                 if (qnameModule == null && ctx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
505                     ctx = ctx.getOriginalCtx().orElse(null);
506                     qnameModule = getModuleQNameByPrefix(ctx, prefix);
507                 }
508         }
509
510         return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx,
511             "Cannot resolve QNameModule for '%s'", value), localName);
512     }
513
514     /**
515      * Parse a YANG identifier string in context of a statement.
516      *
517      * @param ctx Statement context
518      * @param str String to be parsed
519      * @return An interned QName
520      * @throws NullPointerException if any of the arguments are null
521      * @throws SourceException if the string is not a valid YANG identifier
522      */
523     public static QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
524         SourceException.throwIf(str.isEmpty(), ctx, "Identifier may not be an empty string");
525         return internedQName(ctx, str);
526     }
527
528     public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String prefix,
529             final String localName) {
530         return internedQName(ctx,
531             InferenceException.throwIfNull(getModuleQNameByPrefix(ctx, prefix), ctx,
532                 "Cannot resolve QNameModule for '%s'", prefix),
533             localName);
534     }
535
536     /**
537      * Parse a YANG node identifier string in context of a statement.
538      *
539      * @param ctx Statement context
540      * @param str String to be parsed
541      * @return An interned QName
542      * @throws NullPointerException if any of the arguments are null
543      * @throws SourceException if the string is not a valid YANG node identifier
544      */
545     public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
546         SourceException.throwIf(str.isEmpty(), ctx, "Node identifier may not be an empty string");
547
548         final int colon = str.indexOf(':');
549         if (colon == -1) {
550             return internedQName(ctx, str);
551         }
552
553         final String prefix = str.substring(0, colon);
554         SourceException.throwIf(prefix.isEmpty(), ctx, "String '%s' has an empty prefix", str);
555         final String localName = str.substring(colon + 1);
556         SourceException.throwIf(localName.isEmpty(), ctx, "String '%s' has an empty identifier", str);
557
558         return parseNodeIdentifier(ctx, prefix, localName);
559     }
560
561     private static QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
562         return internedQName(ctx, getRootModuleQName(ctx), localName);
563     }
564
565     private static QName internedQName(final CommonStmtCtx ctx, final QNameModule module,
566             final String localName) {
567         final QName template;
568         try {
569             template = QName.create(module, localName);
570         } catch (IllegalArgumentException e) {
571             throw new SourceException(ctx, e, "Invalid identifier '%s'", localName);
572         }
573         return template.intern();
574     }
575
576     public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
577         if (ctx == null) {
578             return null;
579         }
580
581         final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
582         final QNameModule qnameModule;
583
584         if (rootCtx.producesDeclared(ModuleStatement.class)) {
585             qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
586         } else if (rootCtx.producesDeclared(SubmoduleStatement.class)) {
587             final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
588                 BelongsToStatement.class);
589             qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
590         } else {
591             qnameModule = null;
592         }
593
594         checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
595         return qnameModule;
596     }
597
598     public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
599         final StmtContext<?, ?, ?> root = ctx.getRoot();
600         final StmtContext<?, ?, ?> importedModule = root.getFromNamespace(ImportPrefixToModuleCtx.class, prefix);
601         final QNameModule qnameModule = ctx.getFromNamespace(ModuleCtxToModuleQName.class, importedModule);
602         if (qnameModule != null) {
603             return qnameModule;
604         }
605
606         if (root.producesDeclared(SubmoduleStatement.class)) {
607             final String moduleName = root.getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
608             return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
609         }
610
611         return null;
612     }
613
614     public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
615         Revision revision = null;
616         for (final StmtContext<?, ?, ?> subStmt : subStmts) {
617             if (subStmt.producesDeclared(RevisionStatement.class)) {
618                 if (revision == null && subStmt.argument() != null) {
619                     revision = (Revision) subStmt.argument();
620                 } else {
621                     final Revision subArg = (Revision) subStmt.argument();
622                     if (subArg != null && subArg.compareTo(revision) > 0) {
623                         revision = subArg;
624                     }
625                 }
626             }
627         }
628         return Optional.ofNullable(revision);
629     }
630 }