2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.spi.meta;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.CharMatcher;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableList;
16 import java.util.Collection;
17 import java.util.Optional;
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.Revision;
23 import org.opendaylight.yangtools.yang.common.YangVersion;
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.ImportPrefixToModuleCtx;
43 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
44 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
47 public final class StmtContextUtils {
48 private static final CharMatcher IDENTIFIER_START =
49 CharMatcher.inRange('A', 'Z').or(CharMatcher.inRange('a', 'z').or(CharMatcher.is('_'))).precomputed();
50 private static final CharMatcher NOT_IDENTIFIER_PART =
51 IDENTIFIER_START.or(CharMatcher.inRange('0', '9')).or(CharMatcher.anyOf("-.")).negate().precomputed();
53 private StmtContextUtils() {
54 throw new UnsupportedOperationException("Utility class");
57 @SuppressWarnings("unchecked")
58 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
59 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
60 for (final StmtContext<?, ?, ?> ctx : contexts) {
61 if (producesDeclared(ctx, declaredType)) {
62 return (A) ctx.getStatementArgument();
68 @SuppressWarnings("unchecked")
69 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
70 final Class<D> declaredType) {
71 return producesDeclared(ctx, declaredType) ? (A) ctx.getStatementArgument() : null;
74 public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
75 final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
76 return firstAttributeOf(ctx.allSubstatements(), declaredType);
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;
91 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
92 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
93 if (startIndex >= types.length) {
97 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
98 if (producesDeclared(subStmtContext, types[startIndex])) {
99 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
100 ++startIndex, types);
106 @SuppressWarnings("unchecked")
107 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
108 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
109 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
110 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
111 if (producesDeclared(subStmtContext, declaredType)) {
112 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
115 return listBuilder.build();
118 @SuppressWarnings("unchecked")
119 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
120 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
121 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
122 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
123 if (producesDeclared(subStmtContext, type)) {
124 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
127 return listBuilder.build();
130 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
131 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
132 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
133 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
134 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
135 return listBuilder.build();
138 @SuppressWarnings("unchecked")
139 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
140 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
141 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
142 if (producesDeclared(subStmtContext, declaredType)) {
143 return (StmtContext<A, ?, ?>) subStmtContext;
150 * Searches for the first substatement of the specified type in the specified statement context.
151 * First, it tries to find the substatement in the effective substatements of the statement context.
152 * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
153 * the method returns null.
155 * @param stmtContext statement context to search in
156 * @param declaredType substatement type to search for
157 * @param <A> statement argument type
158 * @param <D> declared statement type
159 * @return statement context that was searched for or null if was not found
161 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
162 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
163 final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
164 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
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;
175 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
176 declaredType, --sublevel);
177 if (result != null) {
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;
193 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
194 if (result != null) {
202 public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx,
203 final Class<? extends DeclaredStatement<?>> type) {
204 return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
207 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
208 StmtContext<?, ?, ?> current = stmtCtx;
209 while (current.coerceParentContext().getParentContext() != null) {
210 current = current.getParentContext();
211 if (isUnknownStatement(current)) {
220 * Returns true if supplied statement context represents unknown statement,
221 * otherwise returns false.
224 * statement context to be checked
225 * @return true if supplied statement context represents unknown statement,
227 * @throws NullPointerException
228 * if supplied statement context is null
230 public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
231 return UnknownStatement.class
232 .isAssignableFrom(stmtCtx.getPublicDefinition().getDeclaredRepresentationClass());
236 * Returns true if supplied statement context represents unrecognized
237 * statement, otherwise returns false.
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
246 public static boolean isUnrecognizedStatement(final StmtContext<?, ?, ?> stmtCtx) {
247 return UnrecognizedStatement.class
248 .isAssignableFrom(stmtCtx.getPublicDefinition().getDeclaredRepresentationClass());
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 @SuppressWarnings("unchecked")
259 final Predicate<Set<QName>> argument = (Predicate<Set<QName>>) stmt.coerceStatementArgument();
260 if (argument.test(supportedFeatures)) {
269 return !containsIfFeature || isSupported;
273 * Checks whether statement context is a presence container or not.
277 * @return true if it is a presence container
279 public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
280 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
284 * Checks whether statement context is a non-presence container or not.
288 * @return true if it is a non-presence container
290 public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
291 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
294 private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
295 return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
299 * Checks whether statement context is a mandatory leaf, choice, anyxml,
300 * list or leaf-list according to RFC6020 or not.
304 * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
305 * according to RFC6020.
307 public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
308 if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
311 switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
315 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
318 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
319 return minElements != null && minElements > 0;
326 * Checks whether a statement context is a statement of supplied statement
327 * definition and whether it is not mandatory leaf, choice, anyxml, list or
328 * leaf-list according to RFC6020.
333 * statement definition
334 * @return true if supplied statement context is a statement of supplied
335 * statement definition and if it is not mandatory leaf, choice,
336 * anyxml, list or leaf-list according to RFC6020
338 public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
339 final StatementDefinition stmtDef) {
340 return stmtCtx.getPublicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
344 * Checks whether at least one ancestor of a StatementContext matches one from a collection of statement
348 * StatementContext to be checked
349 * @param ancestorTypes
350 * collection of statement definitions
351 * @return true if at least one ancestor of a StatementContext matches one
352 * from collection of statement definitions, otherwise false.
354 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
355 final Collection<StatementDefinition> ancestorTypes) {
356 requireNonNull(ancestorTypes);
357 StmtContext<?, ?, ?> current = ctx.getParentContext();
358 while (current != null) {
359 if (ancestorTypes.contains(current.getPublicDefinition())) {
362 current = current.getParentContext();
368 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type.
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 * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
375 public static <A, D extends DeclaredStatement<A>> boolean hasAncestorOfTypeWithChildOfType(
376 final StmtContext<?, ?, ?> ctx, final StatementDefinition ancestorType,
377 final StatementDefinition ancestorChildType) {
379 requireNonNull(ancestorType);
380 requireNonNull(ancestorChildType);
382 StmtContext<?, ?, ?> current = ctx.coerceParentContext();
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) {
394 parent = current.getParentContext();
401 * Checks whether the parent of StmtContext is of specified type.
404 * StmtContext to be checked
406 * type of parent to check
407 * @return true if the parent of StmtContext is of specified type, otherwise false
409 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
410 requireNonNull(parentType);
411 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
412 return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
416 * Validates the specified statement context with regards to if-feature and when statement on list keys.
417 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
418 * statement defined in a keyed list (a uses statement may add leaves into the list).
421 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
423 * @param ctx statement context to be validated
425 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
426 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
430 final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
431 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
432 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
434 if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
435 if (isListKey(ctx, keyStmtCtx)) {
436 disallowIfFeatureAndWhenOnListKeys(ctx);
438 } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
439 StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
440 if (isListKey(leafStmtCtx, keyStmtCtx)) {
441 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
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.coerceParentContext(),
451 KeyStatement.class) != null;
454 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
455 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
456 for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.coerceStatementArgument()) {
457 if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
465 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
466 leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
467 final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
468 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
469 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
470 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
471 statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
475 public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
476 if (Strings.isNullOrEmpty(value)) {
477 return ctx.getPublicDefinition().getStatementName();
481 QNameModule qnameModule = null;
482 String localName = null;
484 final String[] namesParts = value.split(":");
485 switch (namesParts.length) {
487 localName = namesParts[0];
488 qnameModule = StmtContextUtils.getRootModuleQName(ctx);
491 prefix = namesParts[0];
492 localName = namesParts[1];
493 qnameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
494 // in case of unknown statement argument, we're not going to parse it
495 if (qnameModule == null && isUnknownStatement(ctx)) {
497 qnameModule = StmtContextUtils.getRootModuleQName(ctx);
499 if (qnameModule == null && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
500 ctx = ctx.getOriginalCtx().orElse(null);
501 qnameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
505 return internedQName(ctx,
506 InferenceException.throwIfNull(qnameModule, ctx.getStatementSourceReference(),
507 "Cannot resolve QNameModule for '%s'", value), localName);
511 * Parse a YANG identifier string in context of a statement.
513 * @param ctx Statement context
514 * @param str String to be parsed
515 * @return An interned QName
516 * @throws NullPointerException if any of the arguments are null
517 * @throws SourceException if the string is not a valid YANG identifier
519 public static QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
520 SourceException.throwIf(str.isEmpty(), ctx.getStatementSourceReference(),
521 "Identifier may not be an empty string");
522 checkIdentifierString(ctx, str);
523 return internedQName(ctx, str);
527 * Parse a YANG node identifier string in context of a statement.
529 * @param ctx Statement context
530 * @param str String to be parsed
531 * @return An interned QName
532 * @throws NullPointerException if any of the arguments are null
533 * @throws SourceException if the string is not a valid YANG node identifier
535 public static QName parseNodeIdentifier(StmtContext<?, ?, ?> ctx, final String str) {
536 SourceException.throwIf(str.isEmpty(), ctx.getStatementSourceReference(),
537 "Node identifier may not be an empty string");
539 final int colon = str.indexOf(':');
541 checkIdentifierString(ctx, str);
542 return internedQName(ctx, str);
545 final String prefix = str.substring(0, colon);
546 SourceException.throwIf(prefix.isEmpty(), ctx.getStatementSourceReference(),
547 "String '%s' has an empty prefix", str);
548 final String localName = str.substring(colon + 1);
549 SourceException.throwIf(localName.isEmpty(), ctx.getStatementSourceReference(),
550 "String '%s' has an empty identifier", str);
551 checkIdentifierString(ctx, localName);
553 final QNameModule module = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
554 if (module != null) {
555 return internedQName(ctx, module, localName);
558 if (ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
559 final Optional<StmtContext<?, ?, ?>> optOrigCtx = ctx.getOriginalCtx();
560 if (optOrigCtx.isPresent()) {
561 ctx = optOrigCtx.get();
562 final QNameModule origModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
563 if (origModule != null) {
564 return internedQName(ctx, origModule, localName);
569 throw new InferenceException(ctx.getStatementSourceReference(), "Cannot resolve QNameModule for '%s'", str);
572 private static void checkIdentifierString(final StmtContext<?, ?, ?> ctx, final String str) {
573 SourceException.throwIf(!IDENTIFIER_START.matches(str.charAt(0)) || NOT_IDENTIFIER_PART.indexIn(str, 1) != -1,
574 ctx.getStatementSourceReference(), "String '%s' is not a valid identifier", str);
577 private static QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
578 return internedQName(ctx, StmtContextUtils.getRootModuleQName(ctx), localName);
581 private static QName internedQName(final StmtContext<?, ?, ?> ctx, final QNameModule module,
582 final String localName) {
583 return ctx.getFromNamespace(QNameCacheNamespace.class, QName.create(module, localName));
586 public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
591 final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
592 final QNameModule qnameModule;
594 if (producesDeclared(rootCtx, ModuleStatement.class)) {
595 qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
596 } else if (producesDeclared(rootCtx, SubmoduleStatement.class)) {
597 final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
598 BelongsToStatement.class);
599 qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
604 checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
608 public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
609 final StmtContext<?, ?, ?> importedModule = ctx.getRoot().getFromNamespace(ImportPrefixToModuleCtx.class,
611 final QNameModule qnameModule = ctx.getFromNamespace(ModuleCtxToModuleQName.class, importedModule);
612 if (qnameModule != null) {
616 if (producesDeclared(ctx.getRoot(), SubmoduleStatement.class)) {
617 final String moduleName = ctx.getRoot().getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
618 return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
624 public static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
625 final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
626 if (qNameModule != null) {
627 // creates SourceIdentifier for a module
628 return RevisionSourceIdentifier.create((String) root.getStatementArgument(), qNameModule.getRevision());
631 // creates SourceIdentifier for a submodule
632 final Optional<Revision> revision = getLatestRevision(root.declaredSubstatements());
633 return RevisionSourceIdentifier.create((String) root.getStatementArgument(), revision);
636 public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
637 Revision revision = null;
638 for (final StmtContext<?, ?, ?> subStmt : subStmts) {
639 if (subStmt.getPublicDefinition().getDeclaredRepresentationClass().isAssignableFrom(
640 RevisionStatement.class)) {
641 if (revision == null && subStmt.getStatementArgument() != null) {
642 revision = (Revision) subStmt.getStatementArgument();
644 final Revision subArg = (Revision) subStmt.getStatementArgument();
645 if (subArg != null && subArg.compareTo(revision) > 0) {
651 return Optional.ofNullable(revision);