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