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