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