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 node according to RFC6020
312 * @return true if it is a mandatory node according to RFC6020
314 public static boolean isMandatoryNode(final StatementContextBase<?, ?, ?> stmtCtx) {
315 return isMandatoryListOrLeafList(stmtCtx) || isMandatoryLeafChoiceOrAnyXML(stmtCtx);
318 private static boolean isMandatoryLeafChoiceOrAnyXML(final StatementContextBase<?, ?, ?> stmtCtx) {
319 if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
322 switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
326 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
332 private static boolean isMandatoryListOrLeafList(final StatementContextBase<?, ?, ?> stmtCtx) {
333 if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
336 switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
339 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
340 return minElements != null && minElements > 0;
347 * Checks whether at least one ancestor of a StatementContext matches one
348 * from collection of statement definitions.
351 * StatementContext to be checked
352 * @param ancestorTypes
353 * collection of statement definitions
355 * @return true if at least one ancestor of a StatementContext matches one
356 * from collection of statement definitions, otherwise false.
358 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
359 final Collection<StatementDefinition> ancestorTypes) {
360 Preconditions.checkNotNull(ctx);
361 Preconditions.checkNotNull(ancestorTypes);
362 StmtContext<?, ?, ?> current = ctx.getParentContext();
363 while (current != null) {
364 if (ancestorTypes.contains(current.getPublicDefinition())) {
367 current = current.getParentContext();
373 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
375 * @param ctx StmtContext to be checked
376 * @param ancestorType type of ancestor to search for
377 * @param ancestorChildType type of child to search for in the specified ancestor type
379 * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
381 public static <AT, DT extends DeclaredStatement<AT>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
382 final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
383 Preconditions.checkNotNull(ctx);
384 Preconditions.checkNotNull(ancestorType);
385 Preconditions.checkNotNull(ancestorChildType);
386 StmtContext<?, ?, ?> current = ctx.getParentContext();
387 while (!(current instanceof RootStatementContext)) {
388 if (ancestorType.equals(current.getPublicDefinition())) {
389 @SuppressWarnings("unchecked")
390 final Class<DT> ancestorChildTypeClass = (Class<DT>) ancestorChildType.getDeclaredRepresentationClass();
391 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
395 current = current.getParentContext();
402 * Checks whether the parent of StmtContext is of specified type
405 * StmtContext to be checked
407 * type of parent to check
409 * @return true if the parent of StmtContext is of specified type, otherwise
412 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
413 Preconditions.checkNotNull(ctx);
414 Preconditions.checkNotNull(parentType);
415 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
416 return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
420 * Validates the specified statement context with regards to if-feature and when statement on list keys.
421 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
422 * statement defined in a keyed list (a uses statement may add leaves into the list).
424 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
426 * @param ctx statement context to be validated
428 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
429 Preconditions.checkNotNull(ctx);
431 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
435 final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
436 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
437 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
439 if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
440 if (isListKey(ctx, keyStmtCtx)) {
441 disallowIfFeatureAndWhenOnListKeys(ctx);
443 } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
444 StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
445 if (isListKey(leafStmtCtx, keyStmtCtx)) {
446 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
452 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
453 return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
454 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
455 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
458 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
459 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
460 for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
461 if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
469 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
470 Iterables.concat(leafStmtCtx.declaredSubstatements(), leafStmtCtx.effectiveSubstatements()).forEach(
472 final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
473 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
474 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
475 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
476 statementDef.getStatementName(), leafStmtCtx.getStatementArgument());