984c9e3eaba285ff026946486321eeba45d20ec4
[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     @SuppressWarnings("unchecked")
89     public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
90             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
91         final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
92         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
93             if (producesDeclared(subStmtContext, declaredType)) {
94                 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
95             }
96         }
97         return listBuilder.build();
98     }
99
100     @SuppressWarnings("unchecked")
101     public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
102             final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
103         final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
104         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
105             if (producesDeclared(subStmtContext, type)) {
106                 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
107             }
108         }
109         return listBuilder.build();
110     }
111
112     public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
113             final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
114         final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
115         listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
116         listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
117         return listBuilder.build();
118     }
119
120     @SuppressWarnings("unchecked")
121     public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
122             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
123         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
124             if (producesDeclared(subStmtContext, declaredType)) {
125                 return (StmtContext<A, ?, ?>) subStmtContext;
126             }
127         }
128         return null;
129     }
130
131     /**
132      * Searches for the first substatement of the specified type in the specified statement context.
133      * First, it tries to find the substatement in the effective substatements of the statement context.
134      * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
135      * the method returns null.
136      *
137      * @param stmtContext statement context to search in
138      * @param declaredType substatement type to search for
139      * @param <A> statement argument type
140      * @param <D> declared statement type
141      * @return statement context that was searched for or null if was not found
142      */
143     public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
144             final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
145         final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
146         return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
147                 declaredType);
148     }
149
150     @SafeVarargs
151     public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
152             int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
153         if (startIndex >= types.length) {
154             return null;
155         }
156
157         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
158             if (producesDeclared(subStmtContext, types[startIndex])) {
159                 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
160                         ++startIndex, types);
161             }
162         }
163         return null;
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
341      * from collection of statement definitions.
342      *
343      * @param ctx
344      *            StatementContext to be checked
345      * @param ancestorTypes
346      *            collection of statement definitions
347      *
348      * @return true if at least one ancestor of a StatementContext matches one
349      *         from collection of statement definitions, otherwise false.
350      */
351     public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
352             final Collection<StatementDefinition> ancestorTypes) {
353         Preconditions.checkNotNull(ctx);
354         Preconditions.checkNotNull(ancestorTypes);
355         StmtContext<?, ?, ?> current = ctx.getParentContext();
356         while (current != null) {
357             if (ancestorTypes.contains(current.getPublicDefinition())) {
358                 return true;
359             }
360             current = current.getParentContext();
361         }
362         return false;
363     }
364
365     /**
366      * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
367      *
368      * @param ctx StmtContext to be checked
369      * @param ancestorType type of ancestor to search for
370      * @param ancestorChildType type of child to search for in the specified ancestor type
371      *
372      * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
373      */
374     public static <A, D extends DeclaredStatement<A>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
375             final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
376         Preconditions.checkNotNull(ctx);
377         Preconditions.checkNotNull(ancestorType);
378         Preconditions.checkNotNull(ancestorChildType);
379
380         StmtContext<?, ?, ?> current = ctx.getParentContext();
381         StmtContext<?, ?, ?> parent = current.getParentContext();
382         while (parent != null) {
383             if (ancestorType.equals(current.getPublicDefinition())) {
384                 @SuppressWarnings("unchecked")
385                 final Class<D> ancestorChildTypeClass = (Class<D>) ancestorChildType.getDeclaredRepresentationClass();
386                 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
387                     return false;
388                 }
389             }
390
391             current = parent;
392             parent = current.getParentContext();
393         }
394
395         return true;
396     }
397
398     /**
399      * Checks whether the parent of StmtContext is of specified type
400      *
401      * @param ctx
402      *            StmtContext to be checked
403      * @param parentType
404      *            type of parent to check
405      *
406      * @return true if the parent of StmtContext is of specified type, otherwise
407      *         false
408      */
409     public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
410         Preconditions.checkNotNull(ctx);
411         Preconditions.checkNotNull(parentType);
412         final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
413         return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
414     }
415
416     /**
417      * Validates the specified statement context with regards to if-feature and when statement on list keys.
418      * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
419      * statement defined in a keyed list (a uses statement may add leaves into the list).
420      *
421      * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
422      *
423      * @param ctx statement context to be validated
424      */
425     public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
426         Preconditions.checkNotNull(ctx);
427
428         if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
429             return;
430         }
431
432         final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
433         final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
434                 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
435
436         if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
437             if (isListKey(ctx, keyStmtCtx)) {
438                 disallowIfFeatureAndWhenOnListKeys(ctx);
439             }
440         } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
441             StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
442                 if (isListKey(leafStmtCtx, keyStmtCtx)) {
443                     disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
444                 }
445             });
446         }
447     }
448
449     private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
450         return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
451                 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
452                 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
453     }
454
455     private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
456             final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
457         for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
458             if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
459                 return true;
460             }
461         }
462
463         return false;
464     }
465
466     private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
467         leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
468             final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
469             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
470                     || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
471                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
472                     statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
473         });
474     }
475
476     public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
477         if (Strings.isNullOrEmpty(value)) {
478             return ctx.getPublicDefinition().getStatementName();
479         }
480
481         String prefix;
482         QNameModule qNameModule = null;
483         String localName = null;
484
485         final String[] namesParts = value.split(":");
486         switch (namesParts.length) {
487         case 1:
488             localName = namesParts[0];
489             qNameModule = StmtContextUtils.getRootModuleQName(ctx);
490             break;
491         default:
492             prefix = namesParts[0];
493             localName = namesParts[1];
494             qNameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
495             // in case of unknown statement argument, we're not going to parse it
496             if (qNameModule == null && isUnknownStatement(ctx)) {
497                 localName = value;
498                 qNameModule = StmtContextUtils.getRootModuleQName(ctx);
499             }
500             if (qNameModule == null
501                     && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
502                 ctx = ctx.getOriginalCtx().orElse(null);
503                 qNameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
504             }
505             break;
506         }
507
508         qNameModule = InferenceException.throwIfNull(qNameModule, ctx.getStatementSourceReference(),
509             "Cannot resolve QNameModule for '%s'", value);
510
511         final QNameModule resultQNameModule;
512         if (qNameModule.getRevision() == null) {
513             resultQNameModule = QNameModule.create(qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV)
514                 .intern();
515         } else {
516             resultQNameModule = qNameModule;
517         }
518
519         return ctx.getFromNamespace(QNameCacheNamespace.class, QName.create(resultQNameModule, localName));
520     }
521
522     public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
523         if (ctx == null) {
524             return null;
525         }
526
527         final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
528         final QNameModule qNameModule;
529
530         if (producesDeclared(rootCtx, ModuleStatement.class)) {
531             qNameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
532         } else if (producesDeclared(rootCtx, SubmoduleStatement.class)) {
533             final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
534                 BelongsToStatement.class);
535             qNameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
536         } else {
537             qNameModule = null;
538         }
539
540         Preconditions.checkArgument(qNameModule != null, "Failed to look up root QNameModule for %s", ctx);
541         if (qNameModule.getRevision() != null) {
542             return qNameModule;
543         }
544
545         return QNameModule.create(qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV).intern();
546     }
547
548     public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
549         final ModuleIdentifier modId = ctx.getRoot().getFromNamespace(ImpPrefixToModuleIdentifier.class, prefix);
550         final QNameModule qNameModule = ctx.getFromNamespace(ModuleIdentifierToModuleQName.class, modId);
551
552         if (qNameModule == null && producesDeclared(ctx.getRoot(), SubmoduleStatement.class)) {
553             final String moduleName = ctx.getRoot().getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
554             return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
555         }
556         return qNameModule;
557     }
558
559     public static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
560         final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
561         if (qNameModule != null) {
562             // creates SourceIdentifier for a module
563             return RevisionSourceIdentifier.create((String) root.getStatementArgument(),
564                 qNameModule.getFormattedRevision());
565         }
566
567         // creates SourceIdentifier for a submodule
568         final Date revision = Optional.ofNullable(getLatestRevision(root.declaredSubstatements()))
569                 .orElse(SimpleDateFormatUtil.DEFAULT_DATE_REV);
570         final String formattedRevision = SimpleDateFormatUtil.getRevisionFormat().format(revision);
571         return RevisionSourceIdentifier.create((String) root.getStatementArgument(), formattedRevision);
572     }
573
574     public static Date getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
575         Date revision = null;
576         for (final StmtContext<?, ?, ?> subStmt : subStmts) {
577             if (subStmt.getPublicDefinition().getDeclaredRepresentationClass().isAssignableFrom(RevisionStatement
578                     .class)) {
579                 if (revision == null && subStmt.getStatementArgument() != null) {
580                     revision = (Date) subStmt.getStatementArgument();
581                 } else if (subStmt.getStatementArgument() != null && ((Date) subStmt.getStatementArgument()).compareTo
582                         (revision) > 0) {
583                     revision = (Date) subStmt.getStatementArgument();
584                 }
585             }
586         }
587         return revision;
588     }
589 }