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.stmt.rfc6020.UnknownStatementImpl;
33 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangDataStatementImpl;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
37 public final class StmtContextUtils {
38 private static final Logger LOG = LoggerFactory.getLogger(StmtContextUtils.class);
40 public static final Splitter LIST_KEY_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
42 private StmtContextUtils() {
43 throw new UnsupportedOperationException("Utility class");
46 @SuppressWarnings("unchecked")
47 public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(
48 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<DT> declaredType) {
49 for (final StmtContext<?, ?, ?> ctx : contexts) {
50 if (producesDeclared(ctx, declaredType)) {
51 return (AT) ctx.getStatementArgument();
57 @SuppressWarnings("unchecked")
58 public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(final StmtContext<?, ?, ?> ctx,
59 final Class<DT> declaredType) {
60 return producesDeclared(ctx, declaredType) ? (AT) ctx.getStatementArgument() : null;
63 public static <AT, DT extends DeclaredStatement<AT>> AT firstSubstatementAttributeOf(
64 final StmtContext<?, ?, ?> ctx, final Class<DT> declaredType) {
65 final AT firstAttribute = firstAttributeOf(ctx.effectiveSubstatements(), declaredType);
66 return firstAttribute != null ? firstAttribute : firstAttributeOf(ctx.declaredSubstatements(), declaredType);
69 @SuppressWarnings("unchecked")
70 public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstDeclaredSubstatement(
71 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
72 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
73 if (producesDeclared(subStmtContext, declaredType)) {
74 return (StmtContext<AT, ?, ?>) subStmtContext;
80 @SuppressWarnings("unchecked")
81 public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllDeclaredSubstatements(
82 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
83 final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
84 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
85 if (producesDeclared(subStmtContext, declaredType)) {
86 listBuilder.add((StmtContext<AT, DT, ?>) subStmtContext);
89 return listBuilder.build();
92 @SuppressWarnings("unchecked")
93 public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllEffectiveSubstatements(
94 final StmtContext<?, ?, ?> stmtContext, final Class<DT> type) {
95 final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
96 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
97 if (producesDeclared(subStmtContext, type)) {
98 listBuilder.add((StmtContext<AT, DT, ?>) subStmtContext);
101 return listBuilder.build();
104 public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllSubstatements(
105 final StmtContext<?, ?, ?> stmtContext, final Class<DT> type) {
106 final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
107 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
108 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
109 return listBuilder.build();
112 @SuppressWarnings("unchecked")
113 public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstEffectiveSubstatement(
114 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
115 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
116 if (producesDeclared(subStmtContext, declaredType)) {
117 return (StmtContext<AT, ?, ?>) subStmtContext;
124 * Searches for the first substatement of the specified type in the specified statement context.
125 * First, it tries to find the substatement in the effective substatements of the statement context.
126 * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
127 * the method returns null.
129 * @param stmtContext statement context to search in
130 * @param declaredType substatement type to search for
131 * @param <AT> statement argument type
132 * @param <DT> declared statement type
133 * @return statement context that was searched for or null if was not found
135 public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstSubstatement(
136 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
137 final StmtContext<AT, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
138 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
143 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
144 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
145 if (startIndex >= types.length) {
149 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
150 if (producesDeclared(subStmtContext, types[startIndex])) {
151 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
152 ++startIndex, types);
158 public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
159 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType, int sublevel) {
160 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
161 if (sublevel == 1 && producesDeclared(subStmtContext, declaredType)) {
162 return subStmtContext;
165 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
166 declaredType, --sublevel);
167 if (result != null) {
176 public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
177 final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
178 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
179 if (producesDeclared(subStmtContext, declaredType)) {
180 return subStmtContext;
183 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
184 if (result != null) {
192 public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx,
193 final Class<? extends DeclaredStatement<?>> type) {
194 return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
197 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
198 StmtContext<?, ?, ?> current = stmtCtx;
199 while (!current.getParentContext().isRootContext()) {
200 current = current.getParentContext();
201 if (producesDeclared(current, UnknownStatementImpl.class)) {
210 * Checks if the statement context has a 'yang-data' extension node as its parent.
212 * @param stmtCtx statement context to be checked
213 * @return true if the parent node is a 'yang-data' node, otherwise false
215 public static boolean hasYangDataExtensionParent(final StmtContext<?, ?, ?> stmtCtx) {
216 return producesDeclared(stmtCtx.getParentContext(), YangDataStatementImpl.class);
219 public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
220 return producesDeclared(stmtCtx, UnknownStatementImpl.class);
223 public static Collection<SchemaNodeIdentifier> replaceModuleQNameForKey(
224 final StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?> keyStmtCtx,
225 final QNameModule newQNameModule) {
227 final Builder<SchemaNodeIdentifier> builder = ImmutableSet.builder();
228 boolean replaced = false;
229 for (final SchemaNodeIdentifier arg : keyStmtCtx.getStatementArgument()) {
230 final QName qname = arg.getLastComponent();
231 if (!newQNameModule.equals(qname)) {
232 final QName newQname = keyStmtCtx.getFromNamespace(QNameCacheNamespace.class,
233 QName.create(newQNameModule, qname.getLocalName()));
234 builder.add(SchemaNodeIdentifier.create(false, newQname));
241 // This makes sure we reuse the collection when a grouping is
242 // instantiated in the same module
243 return replaced ? builder.build() : keyStmtCtx.getStatementArgument();
246 public static boolean checkFeatureSupport(final StmtContext<?, ?, ?> stmtContext,
247 final Set<QName> supportedFeatures) {
248 boolean isSupported = false;
249 boolean containsIfFeature = false;
250 for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
251 if (YangStmtMapping.IF_FEATURE.equals(stmt.getPublicDefinition())) {
252 if (stmtContext.isInYangDataExtensionBody()) {
256 containsIfFeature = true;
257 if (((Predicate<Set<QName>>) stmt.getStatementArgument()).test(supportedFeatures)) {
266 return !containsIfFeature || isSupported;
270 * Checks whether statement context is a presence container or not.
274 * @return true if it is a presence container
276 public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
277 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
281 * Checks whether statement context is a non-presence container or not.
285 * @return true if it is a non-presence container
287 public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
288 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
291 private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
292 return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
296 * Checks whether statement context is a mandatory leaf, choice, anyxml,
297 * list or leaf-list according to RFC6020 or not.
301 * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
302 * according to RFC6020.
304 public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
305 if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
308 switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
312 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
315 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
316 return minElements != null && minElements > 0;
323 * Checks whether a statement context is a statement of supplied statement
324 * definition and whether it is not mandatory leaf, choice, anyxml, list or
325 * leaf-list according to RFC6020.
330 * statement definition
331 * @return true if supplied statement context is a statement of supplied
332 * statement definition and if it is not mandatory leaf, choice,
333 * anyxml, list or leaf-list according to RFC6020
335 public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
336 final StatementDefinition stmtDef) {
337 return stmtCtx.getPublicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
341 * Checks whether at least one ancestor of a StatementContext matches one
342 * from collection of statement definitions.
345 * StatementContext to be checked
346 * @param ancestorTypes
347 * collection of statement definitions
349 * @return true if at least one ancestor of a StatementContext matches one
350 * from collection of statement definitions, otherwise false.
352 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
353 final Collection<StatementDefinition> ancestorTypes) {
354 Preconditions.checkNotNull(ctx);
355 Preconditions.checkNotNull(ancestorTypes);
356 StmtContext<?, ?, ?> current = ctx.getParentContext();
357 while (current != null) {
358 if (ancestorTypes.contains(current.getPublicDefinition())) {
361 current = current.getParentContext();
367 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
369 * @param ctx StmtContext to be checked
370 * @param ancestorType type of ancestor to search for
371 * @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 <AT, DT extends DeclaredStatement<AT>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
376 final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
377 Preconditions.checkNotNull(ctx);
378 Preconditions.checkNotNull(ancestorType);
379 Preconditions.checkNotNull(ancestorChildType);
381 StmtContext<?, ?, ?> current = ctx.getParentContext();
382 StmtContext<?, ?, ?> parent = current.getParentContext();
383 while (parent != null) {
384 if (ancestorType.equals(current.getPublicDefinition())) {
385 @SuppressWarnings("unchecked")
386 final Class<DT> ancestorChildTypeClass = (Class<DT>) ancestorChildType.getDeclaredRepresentationClass();
387 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
393 parent = current.getParentContext();
400 * Checks whether the parent of StmtContext is of specified type
403 * StmtContext to be checked
405 * type of parent to check
407 * @return true if the parent of StmtContext is of specified type, otherwise
410 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
411 Preconditions.checkNotNull(ctx);
412 Preconditions.checkNotNull(parentType);
413 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
414 return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
418 * Validates the specified statement context with regards to if-feature and when statement on list keys.
419 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
420 * statement defined in a keyed list (a uses statement may add leaves into the list).
422 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
424 * @param ctx statement context to be validated
426 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
427 Preconditions.checkNotNull(ctx);
429 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
433 final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
434 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
435 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
437 if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
438 if (isListKey(ctx, keyStmtCtx)) {
439 disallowIfFeatureAndWhenOnListKeys(ctx);
441 } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
442 StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
443 if (isListKey(leafStmtCtx, keyStmtCtx)) {
444 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
450 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
451 return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
452 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
453 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
456 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
457 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
458 for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
459 if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
467 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
468 Iterables.concat(leafStmtCtx.declaredSubstatements(), leafStmtCtx.effectiveSubstatements()).forEach(
470 final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
471 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
472 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
473 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
474 statementDef.getStatementName(), leafStmtCtx.getStatementArgument());