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.Strings;
14 import com.google.common.collect.ImmutableList;
15 import java.util.Collection;
16 import java.util.Optional;
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.Revision;
22 import org.opendaylight.yangtools.yang.common.YangVersion;
23 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
24 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
26 import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
35 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.UnknownStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.UnrecognizedStatement;
38 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
39 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
40 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
41 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
42 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
43 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
44 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
46 public final class StmtContextUtils {
47 private StmtContextUtils() {
48 throw new UnsupportedOperationException("Utility class");
51 @SuppressWarnings("unchecked")
52 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
53 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
54 for (final StmtContext<?, ?, ?> ctx : contexts) {
55 if (producesDeclared(ctx, declaredType)) {
56 return (A) ctx.getStatementArgument();
62 @SuppressWarnings("unchecked")
63 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
64 final Class<D> declaredType) {
65 return producesDeclared(ctx, declaredType) ? (A) ctx.getStatementArgument() : null;
68 public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
69 final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
70 return firstAttributeOf(ctx.allSubstatements(), declaredType);
73 @SuppressWarnings("unchecked")
74 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstDeclaredSubstatement(
75 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
76 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
77 if (producesDeclared(subStmtContext, declaredType)) {
78 return (StmtContext<A, ?, ?>) subStmtContext;
85 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
86 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
87 if (startIndex >= types.length) {
91 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
92 if (producesDeclared(subStmtContext, types[startIndex])) {
93 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
100 @SuppressWarnings("unchecked")
101 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
102 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
103 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
104 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
105 if (producesDeclared(subStmtContext, declaredType)) {
106 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
109 return listBuilder.build();
112 @SuppressWarnings("unchecked")
113 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
114 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
115 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
116 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
117 if (producesDeclared(subStmtContext, type)) {
118 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
121 return listBuilder.build();
124 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
125 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
126 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
127 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
128 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
129 return listBuilder.build();
132 @SuppressWarnings("unchecked")
133 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
134 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
135 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
136 if (producesDeclared(subStmtContext, declaredType)) {
137 return (StmtContext<A, ?, ?>) subStmtContext;
144 * Searches for the first substatement of the specified type in the specified statement context.
145 * First, it tries to find the substatement in the effective substatements of the statement context.
146 * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
147 * the method returns null.
149 * @param stmtContext statement context to search in
150 * @param declaredType substatement type to search for
151 * @param <A> statement argument type
152 * @param <D> declared statement type
153 * @return statement context that was searched for or null if was not found
155 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
156 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
157 final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
158 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
162 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
163 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType, int sublevel) {
164 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
165 if (sublevel == 1 && producesDeclared(subStmtContext, declaredType)) {
166 return subStmtContext;
169 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
170 declaredType, --sublevel);
171 if (result != null) {
180 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
181 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
182 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
183 if (producesDeclared(subStmtContext, declaredType)) {
184 return subStmtContext;
187 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
188 if (result != null) {
196 public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx,
197 final Class<? extends DeclaredStatement<?>> type) {
198 return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
201 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
202 StmtContext<?, ?, ?> current = stmtCtx;
203 while (current.getParentContext().getParentContext() != null) {
204 current = current.getParentContext();
205 if (isUnknownStatement(current)) {
214 * Returns true if supplied statement context represents unknown statement,
215 * otherwise returns false.
218 * statement context to be checked
219 * @return true if supplied statement context represents unknown statement,
221 * @throws NullPointerException
222 * if supplied statement context is null
224 public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
225 return UnknownStatement.class
226 .isAssignableFrom(stmtCtx.getPublicDefinition().getDeclaredRepresentationClass());
230 * Returns true if supplied statement context represents unrecognized
231 * statement, otherwise returns false.
234 * statement context to be checked
235 * @return true if supplied statement context represents unrecognized
236 * statement, otherwise false
237 * @throws NullPointerException
238 * if supplied statement context is null
240 public static boolean isUnrecognizedStatement(final StmtContext<?, ?, ?> stmtCtx) {
241 return UnrecognizedStatement.class
242 .isAssignableFrom(stmtCtx.getPublicDefinition().getDeclaredRepresentationClass());
245 public static boolean checkFeatureSupport(final StmtContext<?, ?, ?> stmtContext,
246 final Set<QName> supportedFeatures) {
247 boolean isSupported = false;
248 boolean containsIfFeature = false;
249 for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
250 if (YangStmtMapping.IF_FEATURE.equals(stmt.getPublicDefinition())) {
251 containsIfFeature = true;
252 if (((Predicate<Set<QName>>) stmt.getStatementArgument()).test(supportedFeatures)) {
261 return !containsIfFeature || isSupported;
265 * Checks whether statement context is a presence container or not.
269 * @return true if it is a presence container
271 public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
272 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
276 * Checks whether statement context is a non-presence container or not.
280 * @return true if it is a non-presence container
282 public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
283 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
286 private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
287 return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
291 * Checks whether statement context is a mandatory leaf, choice, anyxml,
292 * list or leaf-list according to RFC6020 or not.
296 * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
297 * according to RFC6020.
299 public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
300 if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
303 switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
307 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
310 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
311 return minElements != null && minElements > 0;
318 * Checks whether a statement context is a statement of supplied statement
319 * definition and whether it is not mandatory leaf, choice, anyxml, list or
320 * leaf-list according to RFC6020.
325 * statement definition
326 * @return true if supplied statement context is a statement of supplied
327 * statement definition and if it is not mandatory leaf, choice,
328 * anyxml, list or leaf-list according to RFC6020
330 public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
331 final StatementDefinition stmtDef) {
332 return stmtCtx.getPublicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
336 * Checks whether at least one ancestor of a StatementContext matches one from a collection of statement
340 * StatementContext to be checked
341 * @param ancestorTypes
342 * collection of statement definitions
343 * @return true if at least one ancestor of a StatementContext matches one
344 * from collection of statement definitions, otherwise false.
346 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
347 final Collection<StatementDefinition> ancestorTypes) {
348 requireNonNull(ancestorTypes);
349 StmtContext<?, ?, ?> current = ctx.getParentContext();
350 while (current != null) {
351 if (ancestorTypes.contains(current.getPublicDefinition())) {
354 current = current.getParentContext();
360 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type.
362 * @param ctx StmtContext to be checked
363 * @param ancestorType type of ancestor to search for
364 * @param ancestorChildType type of child to search for in the specified ancestor type
365 * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
367 public static <A, D extends DeclaredStatement<A>> boolean hasAncestorOfTypeWithChildOfType(
368 final StmtContext<?, ?, ?> ctx, final StatementDefinition ancestorType,
369 final StatementDefinition ancestorChildType) {
371 requireNonNull(ancestorType);
372 requireNonNull(ancestorChildType);
374 StmtContext<?, ?, ?> current = ctx.getParentContext();
375 StmtContext<?, ?, ?> parent = current.getParentContext();
376 while (parent != null) {
377 if (ancestorType.equals(current.getPublicDefinition())) {
378 @SuppressWarnings("unchecked")
379 final Class<D> ancestorChildTypeClass = (Class<D>) ancestorChildType.getDeclaredRepresentationClass();
380 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
386 parent = current.getParentContext();
393 * Checks whether the parent of StmtContext is of specified type.
396 * StmtContext to be checked
398 * type of parent to check
399 * @return true if the parent of StmtContext is of specified type, otherwise false
401 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
402 requireNonNull(parentType);
403 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
404 return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
408 * Validates the specified statement context with regards to if-feature and when statement on list keys.
409 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
410 * statement defined in a keyed list (a uses statement may add leaves into the list).
413 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
415 * @param ctx statement context to be validated
417 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
418 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
422 final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
423 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
424 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
426 if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
427 if (isListKey(ctx, keyStmtCtx)) {
428 disallowIfFeatureAndWhenOnListKeys(ctx);
430 } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
431 StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
432 if (isListKey(leafStmtCtx, keyStmtCtx)) {
433 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
439 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
440 return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
441 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
442 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
445 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
446 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
447 for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
448 if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
456 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
457 leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
458 final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
459 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
460 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
461 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
462 statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
466 public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
467 if (Strings.isNullOrEmpty(value)) {
468 return ctx.getPublicDefinition().getStatementName();
472 QNameModule qnameModule = null;
473 String localName = null;
475 final String[] namesParts = value.split(":");
476 switch (namesParts.length) {
478 localName = namesParts[0];
479 qnameModule = StmtContextUtils.getRootModuleQName(ctx);
482 prefix = namesParts[0];
483 localName = namesParts[1];
484 qnameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
485 // in case of unknown statement argument, we're not going to parse it
486 if (qnameModule == null && isUnknownStatement(ctx)) {
488 qnameModule = StmtContextUtils.getRootModuleQName(ctx);
490 if (qnameModule == null && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
491 ctx = ctx.getOriginalCtx().orElse(null);
492 qnameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
497 qnameModule = InferenceException.throwIfNull(qnameModule, ctx.getStatementSourceReference(),
498 "Cannot resolve QNameModule for '%s'", value);
499 return ctx.getFromNamespace(QNameCacheNamespace.class, QName.create(qnameModule, localName));
502 public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
507 final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
508 final QNameModule qnameModule;
510 if (producesDeclared(rootCtx, ModuleStatement.class)) {
511 qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
512 } else if (producesDeclared(rootCtx, SubmoduleStatement.class)) {
513 final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
514 BelongsToStatement.class);
515 qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
520 checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
524 public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
525 final StmtContext<?, ?, ?> importedModule = ctx.getRoot().getFromNamespace(ImportPrefixToModuleCtx.class,
527 final QNameModule qnameModule = ctx.getFromNamespace(ModuleCtxToModuleQName.class, importedModule);
528 if (qnameModule != null) {
532 if (producesDeclared(ctx.getRoot(), SubmoduleStatement.class)) {
533 final String moduleName = ctx.getRoot().getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
534 return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
540 public static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
541 final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
542 if (qNameModule != null) {
543 // creates SourceIdentifier for a module
544 return RevisionSourceIdentifier.create((String) root.getStatementArgument(), qNameModule.getRevision());
547 // creates SourceIdentifier for a submodule
548 final Optional<Revision> revision = getLatestRevision(root.declaredSubstatements());
549 return RevisionSourceIdentifier.create((String) root.getStatementArgument(), revision);
552 public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
553 Revision revision = null;
554 for (final StmtContext<?, ?, ?> subStmt : subStmts) {
555 if (subStmt.getPublicDefinition().getDeclaredRepresentationClass().isAssignableFrom(
556 RevisionStatement.class)) {
557 if (revision == null && subStmt.getStatementArgument() != null) {
558 revision = (Revision) subStmt.getStatementArgument();
559 } else if (subStmt.getStatementArgument() != null
560 && ((Revision) subStmt.getStatementArgument()).compareTo(revision) > 0) {
561 revision = (Revision) subStmt.getStatementArgument();
565 return Optional.ofNullable(revision);