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