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.rfc6020.UnknownStatementImpl;
35 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangDataStatementImpl;
37 public final class StmtContextUtils {
38 public static final Splitter LIST_KEY_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
40 private StmtContextUtils() {
41 throw new UnsupportedOperationException("Utility class");
44 @SuppressWarnings("unchecked")
45 public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(
46 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<DT> declaredType) {
47 for (final StmtContext<?, ?, ?> ctx : contexts) {
48 if (producesDeclared(ctx, declaredType)) {
49 return (AT) ctx.getStatementArgument();
55 @SuppressWarnings("unchecked")
56 public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(final StmtContext<?, ?, ?> ctx,
57 final Class<DT> declaredType) {
58 return producesDeclared(ctx, declaredType) ? (AT) ctx.getStatementArgument() : null;
61 public static <AT, DT extends DeclaredStatement<AT>> AT firstSubstatementAttributeOf(
62 final StmtContext<?, ?, ?> ctx, final Class<DT> declaredType) {
63 final AT firstAttribute = firstAttributeOf(ctx.effectiveSubstatements(), declaredType);
64 return firstAttribute != null ? firstAttribute : firstAttributeOf(ctx.declaredSubstatements(), declaredType);
67 @SuppressWarnings("unchecked")
68 public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstDeclaredSubstatement(
69 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
70 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
71 if (producesDeclared(subStmtContext, declaredType)) {
72 return (StmtContext<AT, ?, ?>) subStmtContext;
78 @SuppressWarnings("unchecked")
79 public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllDeclaredSubstatements(
80 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
81 final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
82 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
83 if (producesDeclared(subStmtContext, declaredType)) {
84 listBuilder.add((StmtContext<AT, DT, ?>) subStmtContext);
87 return listBuilder.build();
90 @SuppressWarnings("unchecked")
91 public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllEffectiveSubstatements(
92 final StmtContext<?, ?, ?> stmtContext, final Class<DT> type) {
93 final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
94 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
95 if (producesDeclared(subStmtContext, type)) {
96 listBuilder.add((StmtContext<AT, DT, ?>) subStmtContext);
99 return listBuilder.build();
102 public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllSubstatements(
103 final StmtContext<?, ?, ?> stmtContext, final Class<DT> type) {
104 final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
105 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
106 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
107 return listBuilder.build();
110 @SuppressWarnings("unchecked")
111 public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstEffectiveSubstatement(
112 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
113 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
114 if (producesDeclared(subStmtContext, declaredType)) {
115 return (StmtContext<AT, ?, ?>) subStmtContext;
122 * Searches for the first substatement of the specified type in the specified statement context.
123 * First, it tries to find the substatement in the effective substatements of the statement context.
124 * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
125 * the method returns null.
127 * @param stmtContext statement context to search in
128 * @param declaredType substatement type to search for
129 * @param <AT> statement argument type
130 * @param <DT> declared statement type
131 * @return statement context that was searched for or null if was not found
133 public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstSubstatement(
134 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
135 final StmtContext<AT, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
136 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
141 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
142 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
143 if (startIndex >= types.length) {
147 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
148 if (producesDeclared(subStmtContext, types[startIndex])) {
149 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
150 ++startIndex, types);
156 public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
157 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType, int sublevel) {
158 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
159 if (sublevel == 1 && producesDeclared(subStmtContext, declaredType)) {
160 return subStmtContext;
163 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
164 declaredType, --sublevel);
165 if (result != null) {
174 public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
175 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
176 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
177 if (producesDeclared(subStmtContext, declaredType)) {
178 return subStmtContext;
181 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
182 if (result != null) {
190 public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx,
191 final Class<? extends DeclaredStatement<?>> type) {
192 return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
195 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
196 StmtContext<?, ?, ?> current = stmtCtx;
197 while (!current.getParentContext().isRootContext()) {
198 current = current.getParentContext();
199 if (producesDeclared(current, UnknownStatementImpl.class)) {
208 * Checks if the statement context has a 'yang-data' extension node as its parent.
210 * @param stmtCtx statement context to be checked
211 * @return true if the parent node is a 'yang-data' node, otherwise false
213 public static boolean hasYangDataExtensionParent(final StmtContext<?, ?, ?> stmtCtx) {
214 return producesDeclared(stmtCtx.getParentContext(), YangDataStatementImpl.class);
217 public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
218 return producesDeclared(stmtCtx, UnknownStatementImpl.class);
221 public static Collection<SchemaNodeIdentifier> replaceModuleQNameForKey(
222 final StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?> keyStmtCtx,
223 final QNameModule newQNameModule) {
225 final Builder<SchemaNodeIdentifier> builder = ImmutableSet.builder();
226 boolean replaced = false;
227 for (final SchemaNodeIdentifier arg : keyStmtCtx.getStatementArgument()) {
228 final QName qname = arg.getLastComponent();
229 if (!newQNameModule.equals(qname)) {
230 final QName newQname = keyStmtCtx.getFromNamespace(QNameCacheNamespace.class,
231 QName.create(newQNameModule, qname.getLocalName()));
232 builder.add(SchemaNodeIdentifier.create(false, newQname));
239 // This makes sure we reuse the collection when a grouping is
240 // instantiated in the same module
241 return replaced ? builder.build() : keyStmtCtx.getStatementArgument();
244 public static boolean areFeaturesSupported(final StmtContext.Mutable<?, ?, ?> stmtContext) {
245 switch (stmtContext.getSupportedByFeatures()) {
254 final Set<QName> supportedFeatures = stmtContext.getFromNamespace(SupportedFeaturesNamespace.class,
255 SupportedFeatures.SUPPORTED_FEATURES);
257 * If set of supported features has not been provided, all features are
258 * supported by default.
260 if (supportedFeatures == null) {
261 stmtContext.setSupportedByFeatures(true);
265 final boolean result = checkFeatureSupport(stmtContext, supportedFeatures);
266 stmtContext.setSupportedByFeatures(result);
270 private static boolean checkFeatureSupport(final StmtContext.Mutable<?, ?, ?> stmtContext,
271 final Set<QName> supportedFeatures) {
272 boolean isSupported = false;
273 boolean containsIfFeature = false;
274 for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
275 if (YangStmtMapping.IF_FEATURE.equals(stmt.getPublicDefinition())) {
276 if (stmtContext.isInYangDataExtensionBody()) {
280 containsIfFeature = true;
281 if (((Predicate<Set<QName>>) stmt.getStatementArgument()).test(supportedFeatures)) {
290 return !containsIfFeature || isSupported;
294 * Checks whether statement context is a presence container or not.
298 * @return true if it is a presence container
300 public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
301 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
305 * Checks whether statement context is a non-presence container or not.
309 * @return true if it is a non-presence container
311 public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
312 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
315 private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
316 return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
320 * Checks whether statement context is a mandatory leaf, choice, anyxml,
321 * list or leaf-list according to RFC6020 or not.
325 * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
326 * according to RFC6020.
328 public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
329 if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
332 switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
336 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
339 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
340 return minElements != null && minElements > 0;
347 * Checks whether a statement context is a statement of supplied statement
348 * definition and whether it is not mandatory leaf, choice, anyxml, list or
349 * leaf-list according to RFC6020.
354 * statement definition
355 * @return true if supplied statement context is a statement of supplied
356 * statement definition and if it is not mandatory leaf, choice,
357 * anyxml, list or leaf-list according to RFC6020
359 public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
360 final StatementDefinition stmtDef) {
361 return stmtCtx.getPublicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
365 * Checks whether at least one ancestor of a StatementContext matches one
366 * from collection of statement definitions.
369 * StatementContext to be checked
370 * @param ancestorTypes
371 * collection of statement definitions
373 * @return true if at least one ancestor of a StatementContext matches one
374 * from collection of statement definitions, otherwise false.
376 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
377 final Collection<StatementDefinition> ancestorTypes) {
378 Preconditions.checkNotNull(ctx);
379 Preconditions.checkNotNull(ancestorTypes);
380 StmtContext<?, ?, ?> current = ctx.getParentContext();
381 while (current != null) {
382 if (ancestorTypes.contains(current.getPublicDefinition())) {
385 current = current.getParentContext();
391 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
393 * @param ctx StmtContext to be checked
394 * @param ancestorType type of ancestor to search for
395 * @param ancestorChildType type of child to search for in the specified ancestor type
397 * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
399 public static <AT, DT extends DeclaredStatement<AT>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
400 final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
401 Preconditions.checkNotNull(ctx);
402 Preconditions.checkNotNull(ancestorType);
403 Preconditions.checkNotNull(ancestorChildType);
405 StmtContext<?, ?, ?> current = ctx.getParentContext();
406 StmtContext<?, ?, ?> parent = current.getParentContext();
407 while (parent != null) {
408 if (ancestorType.equals(current.getPublicDefinition())) {
409 @SuppressWarnings("unchecked")
410 final Class<DT> ancestorChildTypeClass = (Class<DT>) ancestorChildType.getDeclaredRepresentationClass();
411 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
417 parent = current.getParentContext();
424 * Checks whether the parent of StmtContext is of specified type
427 * StmtContext to be checked
429 * type of parent to check
431 * @return true if the parent of StmtContext is of specified type, otherwise
434 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
435 Preconditions.checkNotNull(ctx);
436 Preconditions.checkNotNull(parentType);
437 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
438 return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
442 * Validates the specified statement context with regards to if-feature and when statement on list keys.
443 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
444 * statement defined in a keyed list (a uses statement may add leaves into the list).
446 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
448 * @param ctx statement context to be validated
450 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
451 Preconditions.checkNotNull(ctx);
453 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
457 final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
458 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
459 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
461 if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
462 if (isListKey(ctx, keyStmtCtx)) {
463 disallowIfFeatureAndWhenOnListKeys(ctx);
465 } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
466 StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
467 if (isListKey(leafStmtCtx, keyStmtCtx)) {
468 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
474 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
475 return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
476 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
477 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
480 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
481 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
482 for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
483 if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
491 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
492 Iterables.concat(leafStmtCtx.declaredSubstatements(), leafStmtCtx.effectiveSubstatements()).forEach(
494 final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
495 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
496 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
497 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
498 statementDef.getStatementName(), leafStmtCtx.getStatementArgument());