cf56271d356e9c85aab14b92c3d693f030cd6925
[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         throw new UnsupportedOperationException("Utility class");
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.getParentContext().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                 if (((Predicate<Set<QName>>) stmt.getStatementArgument()).test(supportedFeatures)) {
253                     isSupported = true;
254                 } else {
255                     isSupported = false;
256                     break;
257                 }
258             }
259         }
260
261         return !containsIfFeature || isSupported;
262     }
263
264     /**
265      * Checks whether statement context is a presence container or not.
266      *
267      * @param stmtCtx
268      *            statement context
269      * @return true if it is a presence container
270      */
271     public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
272         return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
273     }
274
275     /**
276      * Checks whether statement context is a non-presence container or not.
277      *
278      * @param stmtCtx
279      *            statement context
280      * @return true if it is a non-presence container
281      */
282     public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
283         return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
284     }
285
286     private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
287         return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
288     }
289
290     /**
291      * Checks whether statement context is a mandatory leaf, choice, anyxml,
292      * list or leaf-list according to RFC6020 or not.
293      *
294      * @param stmtCtx
295      *            statement context
296      * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
297      *         according to RFC6020.
298      */
299     public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
300         if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
301             return false;
302         }
303         switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
304             case LEAF:
305             case CHOICE:
306             case ANYXML:
307                 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
308             case LIST:
309             case LEAF_LIST:
310                 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
311                 return minElements != null && minElements > 0;
312             default:
313                 return false;
314         }
315     }
316
317     /**
318      * Checks whether a statement context is a statement of supplied statement
319      * definition and whether it is not mandatory leaf, choice, anyxml, list or
320      * leaf-list according to RFC6020.
321      *
322      * @param stmtCtx
323      *            statement context
324      * @param stmtDef
325      *            statement definition
326      * @return true if supplied statement context is a statement of supplied
327      *         statement definition and if it is not mandatory leaf, choice,
328      *         anyxml, list or leaf-list according to RFC6020
329      */
330     public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
331             final StatementDefinition stmtDef) {
332         return stmtCtx.getPublicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
333     }
334
335     /**
336      * Checks whether at least one ancestor of a StatementContext matches one from a collection of statement
337      * definitions.
338      *
339      * @param ctx
340      *            StatementContext to be checked
341      * @param ancestorTypes
342      *            collection of statement definitions
343      * @return true if at least one ancestor of a StatementContext matches one
344      *         from collection of statement definitions, otherwise false.
345      */
346     public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
347             final Collection<StatementDefinition> ancestorTypes) {
348         requireNonNull(ancestorTypes);
349         StmtContext<?, ?, ?> current = ctx.getParentContext();
350         while (current != null) {
351             if (ancestorTypes.contains(current.getPublicDefinition())) {
352                 return true;
353             }
354             current = current.getParentContext();
355         }
356         return false;
357     }
358
359     /**
360      * Checks whether all of StmtContext's ancestors of specified type have a child of specified type.
361      *
362      * @param ctx StmtContext to be checked
363      * @param ancestorType type of ancestor to search for
364      * @param ancestorChildType type of child to search for in the specified ancestor type
365      * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
366      */
367     public static <A, D extends DeclaredStatement<A>> boolean hasAncestorOfTypeWithChildOfType(
368             final StmtContext<?, ?, ?> ctx, final StatementDefinition ancestorType,
369             final StatementDefinition ancestorChildType) {
370         requireNonNull(ctx);
371         requireNonNull(ancestorType);
372         requireNonNull(ancestorChildType);
373
374         StmtContext<?, ?, ?> current = ctx.getParentContext();
375         StmtContext<?, ?, ?> parent = current.getParentContext();
376         while (parent != null) {
377             if (ancestorType.equals(current.getPublicDefinition())) {
378                 @SuppressWarnings("unchecked")
379                 final Class<D> ancestorChildTypeClass = (Class<D>) ancestorChildType.getDeclaredRepresentationClass();
380                 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
381                     return false;
382                 }
383             }
384
385             current = parent;
386             parent = current.getParentContext();
387         }
388
389         return true;
390     }
391
392     /**
393      * Checks whether the parent of StmtContext is of specified type.
394      *
395      * @param ctx
396      *            StmtContext to be checked
397      * @param parentType
398      *            type of parent to check
399      * @return true if the parent of StmtContext is of specified type, otherwise false
400      */
401     public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
402         requireNonNull(parentType);
403         final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
404         return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
405     }
406
407     /**
408      * Validates the specified statement context with regards to if-feature and when statement on list keys.
409      * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
410      * statement defined in a keyed list (a uses statement may add leaves into the list).
411      *
412      * <p>
413      * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
414      *
415      * @param ctx statement context to be validated
416      */
417     public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
418         if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
419             return;
420         }
421
422         final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
423         final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
424                 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
425
426         if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
427             if (isListKey(ctx, keyStmtCtx)) {
428                 disallowIfFeatureAndWhenOnListKeys(ctx);
429             }
430         } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
431             StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
432                 if (isListKey(leafStmtCtx, keyStmtCtx)) {
433                     disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
434                 }
435             });
436         }
437     }
438
439     private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
440         return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
441                 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
442                 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
443     }
444
445     private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
446             final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
447         for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
448             if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
449                 return true;
450             }
451         }
452
453         return false;
454     }
455
456     private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
457         leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
458             final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
459             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
460                     || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
461                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
462                     statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
463         });
464     }
465
466     public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
467         if (Strings.isNullOrEmpty(value)) {
468             return ctx.getPublicDefinition().getStatementName();
469         }
470
471         String prefix;
472         QNameModule qnameModule = null;
473         String localName = null;
474
475         final String[] namesParts = value.split(":");
476         switch (namesParts.length) {
477             case 1:
478                 localName = namesParts[0];
479                 qnameModule = StmtContextUtils.getRootModuleQName(ctx);
480                 break;
481             default:
482                 prefix = namesParts[0];
483                 localName = namesParts[1];
484                 qnameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
485                 // in case of unknown statement argument, we're not going to parse it
486                 if (qnameModule == null && isUnknownStatement(ctx)) {
487                     localName = value;
488                     qnameModule = StmtContextUtils.getRootModuleQName(ctx);
489                 }
490                 if (qnameModule == null && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
491                     ctx = ctx.getOriginalCtx().orElse(null);
492                     qnameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
493                 }
494                 break;
495         }
496
497         qnameModule = InferenceException.throwIfNull(qnameModule, ctx.getStatementSourceReference(),
498             "Cannot resolve QNameModule for '%s'", value);
499         return ctx.getFromNamespace(QNameCacheNamespace.class, QName.create(qnameModule, localName));
500     }
501
502     public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
503         if (ctx == null) {
504             return null;
505         }
506
507         final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
508         final QNameModule qnameModule;
509
510         if (producesDeclared(rootCtx, ModuleStatement.class)) {
511             qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
512         } else if (producesDeclared(rootCtx, SubmoduleStatement.class)) {
513             final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
514                 BelongsToStatement.class);
515             qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
516         } else {
517             qnameModule = null;
518         }
519
520         checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
521         return qnameModule;
522     }
523
524     public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
525         final StmtContext<?, ?, ?> importedModule = ctx.getRoot().getFromNamespace(ImportPrefixToModuleCtx.class,
526             prefix);
527         final QNameModule qnameModule = ctx.getFromNamespace(ModuleCtxToModuleQName.class, importedModule);
528         if (qnameModule != null) {
529             return qnameModule;
530         }
531
532         if (producesDeclared(ctx.getRoot(), SubmoduleStatement.class)) {
533             final String moduleName = ctx.getRoot().getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
534             return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
535         }
536
537         return null;
538     }
539
540     public static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
541         final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
542         if (qNameModule != null) {
543             // creates SourceIdentifier for a module
544             return RevisionSourceIdentifier.create((String) root.getStatementArgument(), qNameModule.getRevision());
545         }
546
547         // creates SourceIdentifier for a submodule
548         final Optional<Revision> revision = getLatestRevision(root.declaredSubstatements());
549         return RevisionSourceIdentifier.create((String) root.getStatementArgument(), revision);
550     }
551
552     public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
553         Revision revision = null;
554         for (final StmtContext<?, ?, ?> subStmt : subStmts) {
555             if (subStmt.getPublicDefinition().getDeclaredRepresentationClass().isAssignableFrom(
556                     RevisionStatement.class)) {
557                 if (revision == null && subStmt.getStatementArgument() != null) {
558                     revision = (Revision) subStmt.getStatementArgument();
559                 } else if (subStmt.getStatementArgument() != null
560                         && ((Revision) subStmt.getStatementArgument()).compareTo(revision) > 0) {
561                     revision = (Revision) subStmt.getStatementArgument();
562                 }
563             }
564         }
565         return Optional.ofNullable(revision);
566     }
567 }