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 com.google.common.base.Preconditions;
11 import com.google.common.base.Splitter;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.collect.ImmutableSet.Builder;
15 import com.google.common.collect.Iterables;
16 import java.util.Collection;
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.YangVersion;
22 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
23 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
24 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
25 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
31 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
32 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
33 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
34 import org.opendaylight.yangtools.yang.parser.stmt.reactor.RootStatementContext;
35 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
36 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
38 public final class StmtContextUtils {
39 public static final Splitter LIST_KEY_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
41 private StmtContextUtils() {
42 throw new UnsupportedOperationException("Utility class");
45 @SuppressWarnings("unchecked")
46 public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(
47 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<DT> declaredType) {
48 for (final StmtContext<?, ?, ?> ctx : contexts) {
49 if (producesDeclared(ctx, declaredType)) {
50 return (AT) ctx.getStatementArgument();
56 @SuppressWarnings("unchecked")
57 public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(final StmtContext<?, ?, ?> ctx,
58 final Class<DT> declaredType) {
59 return producesDeclared(ctx, declaredType) ? (AT) ctx.getStatementArgument() : null;
62 public static <AT, DT extends DeclaredStatement<AT>> AT firstSubstatementAttributeOf(
63 final StmtContext<?, ?, ?> ctx, final Class<DT> declaredType) {
64 final AT firstAttribute = firstAttributeOf(ctx.effectiveSubstatements(), declaredType);
65 return firstAttribute != null ? firstAttribute : firstAttributeOf(ctx.declaredSubstatements(), declaredType);
68 @SuppressWarnings("unchecked")
69 public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstDeclaredSubstatement(
70 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
71 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
72 if (producesDeclared(subStmtContext, declaredType)) {
73 return (StmtContext<AT, ?, ?>) subStmtContext;
79 @SuppressWarnings("unchecked")
80 public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllDeclaredSubstatements(
81 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
82 final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
83 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
84 if (producesDeclared(subStmtContext, declaredType)) {
85 listBuilder.add((StmtContext<AT, DT, ?>) subStmtContext);
88 return listBuilder.build();
91 @SuppressWarnings("unchecked")
92 public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllEffectiveSubstatements(
93 final StmtContext<?, ?, ?> stmtContext, final Class<DT> type) {
94 final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
95 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
96 if (producesDeclared(subStmtContext, type)) {
97 listBuilder.add((StmtContext<AT, DT, ?>) subStmtContext);
100 return listBuilder.build();
103 public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllSubstatements(
104 final StmtContext<?, ?, ?> stmtContext, final Class<DT> type) {
105 final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
106 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
107 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
108 return listBuilder.build();
111 @SuppressWarnings("unchecked")
112 public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstEffectiveSubstatement(
113 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
114 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
115 if (producesDeclared(subStmtContext, declaredType)) {
116 return (StmtContext<AT, ?, ?>) subStmtContext;
123 * Searches for the first substatement of the specified type in the specified statement context.
124 * First, it tries to find the substatement in the effective substatements of the statement context.
125 * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
126 * the method returns null.
128 * @param stmtContext statement context to search in
129 * @param declaredType substatement type to search for
130 * @param <AT> statement argument type
131 * @param <DT> declared statement type
132 * @return statement context that was searched for or null if was not found
134 public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstSubstatement(
135 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
136 final StmtContext<AT, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
137 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
142 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
143 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
144 if (startIndex >= types.length) {
148 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
149 if (producesDeclared(subStmtContext, types[startIndex])) {
150 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
151 ++startIndex, types);
157 public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
158 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType, int sublevel) {
159 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
160 if (sublevel == 1 && producesDeclared(subStmtContext, declaredType)) {
161 return subStmtContext;
164 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
165 declaredType, --sublevel);
166 if (result != null) {
175 public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
176 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
177 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
178 if (producesDeclared(subStmtContext, declaredType)) {
179 return subStmtContext;
182 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
183 if (result != null) {
191 public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx,
192 final Class<? extends DeclaredStatement<?>> type) {
193 return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
196 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
197 StmtContext<?, ?, ?> current = stmtCtx;
198 while (!current.getParentContext().isRootContext()) {
199 current = current.getParentContext();
200 if (producesDeclared(current, UnknownStatementImpl.class)) {
208 public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
209 return producesDeclared(stmtCtx, UnknownStatementImpl.class);
212 public static Collection<SchemaNodeIdentifier> replaceModuleQNameForKey(
213 final StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?> keyStmtCtx,
214 final QNameModule newQNameModule) {
216 final Builder<SchemaNodeIdentifier> builder = ImmutableSet.builder();
217 boolean replaced = false;
218 for (final SchemaNodeIdentifier arg : keyStmtCtx.getStatementArgument()) {
219 final QName qname = arg.getLastComponent();
220 if (!newQNameModule.equals(qname)) {
221 final QName newQname = keyStmtCtx.getFromNamespace(QNameCacheNamespace.class,
222 QName.create(newQNameModule, qname.getLocalName()));
223 builder.add(SchemaNodeIdentifier.create(false, newQname));
230 // This makes sure we reuse the collection when a grouping is
231 // instantiated in the same module
232 return replaced ? builder.build() : keyStmtCtx.getStatementArgument();
235 public static boolean areFeaturesSupported(final StmtContext.Mutable<?, ?, ?> stmtContext) {
236 switch (stmtContext.getSupportedByFeatures()) {
245 final Set<QName> supportedFeatures = stmtContext.getFromNamespace(SupportedFeaturesNamespace.class,
246 SupportedFeatures.SUPPORTED_FEATURES);
248 * If set of supported features has not been provided, all features are
249 * supported by default.
251 if (supportedFeatures == null) {
252 stmtContext.setSupportedByFeatures(true);
256 final boolean result = checkFeatureSupport(stmtContext, supportedFeatures);
257 stmtContext.setSupportedByFeatures(result);
261 private static boolean checkFeatureSupport(final StmtContext.Mutable<?, ?, ?> stmtContext,
262 final Set<QName> supportedFeatures) {
263 boolean isSupported = false;
264 boolean containsIfFeature = false;
265 for (final StatementContextBase<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
266 if (YangStmtMapping.IF_FEATURE.equals(stmt.getPublicDefinition())) {
267 containsIfFeature = true;
268 if (((Predicate<Set<QName>>) stmt.getStatementArgument()).test(supportedFeatures)) {
277 return !containsIfFeature || isSupported;
281 * Checks whether statement context is a presence container or not.
285 * @return true if it is a presence container
287 public static boolean isPresenceContainer(final StatementContextBase<?, ?, ?> stmtCtx) {
288 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
292 * Checks whether statement context is a non-presence container or not.
296 * @return true if it is a non-presence container
298 public static boolean isNonPresenceContainer(final StatementContextBase<?, ?, ?> stmtCtx) {
299 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
302 private static boolean containsPresenceSubStmt(final StatementContextBase<?, ?, ?> stmtCtx) {
303 return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
307 * Checks whether statement context is a mandatory leaf, choice, anyxml,
308 * list or leaf-list according to RFC6020 or not.
312 * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
313 * according to RFC6020.
315 public static boolean isMandatoryNode(final StatementContextBase<?, ?, ?> stmtCtx) {
316 if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
319 switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
323 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
326 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
327 return minElements != null && minElements > 0;
334 * Checks whether a statement context is a statement of supplied statement
335 * definition and whether it is not mandatory leaf, choice, anyxml, list or
336 * leaf-list according to RFC6020.
341 * statement definition
342 * @return true if supplied statement context is a statement of supplied
343 * statement definition and if it is not mandatory leaf, choice,
344 * anyxml, list or leaf-list according to RFC6020
346 public static boolean isNotMandatoryNodeOfType(final StatementContextBase<?, ?, ?> stmtCtx,
347 final StatementDefinition stmtDef) {
348 return stmtCtx.getPublicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
352 * Checks whether at least one ancestor of a StatementContext matches one
353 * from collection of statement definitions.
356 * StatementContext to be checked
357 * @param ancestorTypes
358 * collection of statement definitions
360 * @return true if at least one ancestor of a StatementContext matches one
361 * from collection of statement definitions, otherwise false.
363 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
364 final Collection<StatementDefinition> ancestorTypes) {
365 Preconditions.checkNotNull(ctx);
366 Preconditions.checkNotNull(ancestorTypes);
367 StmtContext<?, ?, ?> current = ctx.getParentContext();
368 while (current != null) {
369 if (ancestorTypes.contains(current.getPublicDefinition())) {
372 current = current.getParentContext();
378 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
380 * @param ctx StmtContext to be checked
381 * @param ancestorType type of ancestor to search for
382 * @param ancestorChildType type of child to search for in the specified ancestor type
384 * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
386 public static <AT, DT extends DeclaredStatement<AT>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
387 final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
388 Preconditions.checkNotNull(ctx);
389 Preconditions.checkNotNull(ancestorType);
390 Preconditions.checkNotNull(ancestorChildType);
391 StmtContext<?, ?, ?> current = ctx.getParentContext();
392 while (!(current instanceof RootStatementContext)) {
393 if (ancestorType.equals(current.getPublicDefinition())) {
394 @SuppressWarnings("unchecked")
395 final Class<DT> ancestorChildTypeClass = (Class<DT>) ancestorChildType.getDeclaredRepresentationClass();
396 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
400 current = current.getParentContext();
407 * Checks whether the parent of StmtContext is of specified type
410 * StmtContext to be checked
412 * type of parent to check
414 * @return true if the parent of StmtContext is of specified type, otherwise
417 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
418 Preconditions.checkNotNull(ctx);
419 Preconditions.checkNotNull(parentType);
420 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
421 return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
425 * Validates the specified statement context with regards to if-feature and when statement on list keys.
426 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
427 * statement defined in a keyed list (a uses statement may add leaves into the list).
429 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
431 * @param ctx statement context to be validated
433 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
434 Preconditions.checkNotNull(ctx);
436 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
440 final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
441 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
442 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
444 if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
445 if (isListKey(ctx, keyStmtCtx)) {
446 disallowIfFeatureAndWhenOnListKeys(ctx);
448 } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
449 StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
450 if (isListKey(leafStmtCtx, keyStmtCtx)) {
451 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
457 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
458 return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
459 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
460 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
463 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
464 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
465 for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
466 if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
474 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
475 Iterables.concat(leafStmtCtx.declaredSubstatements(), leafStmtCtx.effectiveSubstatements()).forEach(
477 final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
478 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
479 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
480 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
481 statementDef.getStatementName(), leafStmtCtx.getStatementArgument());