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.EffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
27 import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
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.parser.spi.meta.EffectiveStmtCtx.Parent;
39 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
40 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
41 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
42 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
43 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
45 public final class StmtContextUtils {
46 private StmtContextUtils() {
50 @SuppressWarnings("unchecked")
51 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
52 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
53 for (final StmtContext<?, ?, ?> ctx : contexts) {
54 if (ctx.producesDeclared(declaredType)) {
55 return (A) ctx.argument();
61 @SuppressWarnings("unchecked")
62 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
63 final Class<D> declaredType) {
64 return ctx.producesDeclared(declaredType) ? (A) ctx.argument() : null;
67 public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
68 final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
69 return firstAttributeOf(ctx.allSubstatements(), declaredType);
72 @SuppressWarnings("unchecked")
73 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstDeclaredSubstatement(
74 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
75 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
76 if (subStmtContext.producesDeclared(declaredType)) {
77 return (StmtContext<A, ?, ?>) subStmtContext;
84 @SuppressWarnings({ "rawtypes", "unchecked" })
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 (subStmtContext.producesDeclared((Class) 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 (subStmtContext.producesDeclared(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 (subStmtContext.producesDeclared(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 (subStmtContext.producesDeclared(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
154 * @deprecated Use {@link StmtContext#findSubstatementArgument(Class)} instead.
156 @Deprecated(forRemoval = true)
157 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
158 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
159 final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
160 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
164 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
165 final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType, int sublevel) {
166 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
167 if (sublevel == 1 && subStmtContext.producesDeclared(declaredType)) {
168 return subStmtContext;
171 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
172 declaredType, --sublevel);
173 if (result != null) {
182 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
183 final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType) {
184 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
185 if (subStmtContext.producesDeclared(declaredType)) {
186 return subStmtContext;
189 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
190 if (result != null) {
198 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
199 StmtContext<?, ?, ?> current = stmtCtx;
202 final StmtContext<?, ?, ?> parent = current.coerceParentContext();
203 if (parent.getParentContext() == null) {
206 if (isUnknownStatement(parent)) {
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.isAssignableFrom(stmtCtx.publicDefinition().getDeclaredRepresentationClass());
229 * Returns true if supplied statement context represents unrecognized
230 * statement, otherwise returns false.
233 * statement context to be checked
234 * @return true if supplied statement context represents unrecognized
235 * statement, otherwise false
236 * @throws NullPointerException
237 * if supplied statement context is null
239 public static boolean isUnrecognizedStatement(final StmtContext<?, ?, ?> stmtCtx) {
240 return stmtCtx.producesDeclared(UnrecognizedStatement.class);
243 public static boolean checkFeatureSupport(final StmtContext<?, ?, ?> stmtContext,
244 final Set<QName> supportedFeatures) {
245 boolean isSupported = false;
246 boolean containsIfFeature = false;
247 for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
248 if (YangStmtMapping.IF_FEATURE.equals(stmt.publicDefinition())) {
249 containsIfFeature = true;
250 @SuppressWarnings("unchecked")
251 final Predicate<Set<QName>> argument = (Predicate<Set<QName>>) stmt.getArgument();
252 if (argument.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.publicDefinition() == 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.publicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
286 private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
287 return stmtCtx.hasSubstatement(PresenceEffectiveStatement.class);
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.publicDefinition() instanceof YangStmtMapping)) {
303 switch ((YangStmtMapping) stmtCtx.publicDefinition()) {
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.publicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
336 * Checks whether at least one ancestor of a StatementContext matches one from a collection of statement
339 * @param stmt EffectiveStmtCtx to be checked
340 * @param ancestorTypes collection of statement definitions
341 * @return true if at least one ancestor of a StatementContext matches one
342 * from collection of statement definitions, otherwise false.
344 public static boolean hasAncestorOfType(final EffectiveStmtCtx stmt,
345 final Collection<StatementDefinition> ancestorTypes) {
346 requireNonNull(ancestorTypes);
347 Parent current = stmt.effectiveParent();
348 while (current != null) {
349 if (ancestorTypes.contains(current.publicDefinition())) {
352 current = current.effectiveParent();
358 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type.
360 * @param stmt EffectiveStmtCtx to be checked
361 * @param ancestorType type of ancestor to search for
362 * @param ancestorChildType type of child to search for in the specified ancestor type
363 * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
365 public static <A, D extends DeclaredStatement<A>> boolean hasAncestorOfTypeWithChildOfType(
366 final EffectiveStmtCtx.Current<?, ?> stmt, final StatementDefinition ancestorType,
367 final StatementDefinition ancestorChildType) {
368 requireNonNull(stmt);
369 requireNonNull(ancestorType);
371 final Class<? extends EffectiveStatement<?, ?>> repr = ancestorChildType.getEffectiveRepresentationClass();
372 StmtContext<?, ?, ?> current = stmt.caerbannog().getParentContext();
373 StmtContext<?, ?, ?> parent = current.getParentContext();
374 while (parent != null) {
375 if (ancestorType.equals(current.publicDefinition()) && !current.hasSubstatement(repr)) {
380 parent = current.getParentContext();
387 * Checks whether the parent of EffectiveStmtCtx is of specified type.
389 * @param stmt EffectiveStmtCtx to be checked
390 * @param parentType type of parent to check
391 * @return true if the parent of StmtContext is of specified type, otherwise false
393 public static boolean hasParentOfType(final EffectiveStmtCtx.Current<?, ?> stmt,
394 final StatementDefinition parentType) {
395 return hasParentOfType(stmt.caerbannog(), parentType);
399 * Checks whether the parent of StmtContext is of specified type.
401 * @param ctx StmtContext to be checked
402 * @param parentType type of parent to check
403 * @return true if the parent of StmtContext is of specified type, otherwise false
405 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
406 requireNonNull(parentType);
407 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
408 return parentContext != null && parentType.equals(parentContext.publicDefinition());
412 * Validates the specified statement context with regards to if-feature and when statement on list keys.
413 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
414 * statement defined in a keyed list (a uses statement may add leaves into the list).
417 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
419 * @param ctx statement context to be validated
421 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
422 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
426 final StmtContext<?, ?, ?> listStmtCtx = ctx.coerceParentContext();
427 final StmtContext<Set<QName>, ?, ?> keyStmtCtx = findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
429 if (YangStmtMapping.LEAF.equals(ctx.publicDefinition())) {
430 if (isListKey(ctx, keyStmtCtx)) {
431 disallowIfFeatureAndWhenOnListKeys(ctx);
433 } else if (YangStmtMapping.USES.equals(ctx.publicDefinition())) {
434 findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
435 if (isListKey(leafStmtCtx, keyStmtCtx)) {
436 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
442 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
443 return YangVersion.VERSION_1_1.equals(ctx.yangVersion()) && hasParentOfType(ctx, YangStmtMapping.LIST)
444 && findFirstDeclaredSubstatement(ctx.coerceParentContext(), KeyStatement.class) != null;
447 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
448 final StmtContext<Set<QName>, ?, ?> keyStmtCtx) {
449 return keyStmtCtx.getArgument().contains(leafStmtCtx.argument());
452 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
453 leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
454 final StatementDefinition statementDef = leafSubstmtCtx.publicDefinition();
455 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
456 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx,
457 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
458 statementDef.getStatementName(), leafStmtCtx.argument());
462 public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
463 if (Strings.isNullOrEmpty(value)) {
464 return ctx.publicDefinition().getStatementName();
468 QNameModule qnameModule = null;
469 String localName = null;
471 final String[] namesParts = value.split(":");
472 switch (namesParts.length) {
474 localName = namesParts[0];
475 qnameModule = getRootModuleQName(ctx);
478 prefix = namesParts[0];
479 localName = namesParts[1];
480 qnameModule = getModuleQNameByPrefix(ctx, prefix);
481 // in case of unknown statement argument, we're not going to parse it
482 if (qnameModule == null && isUnknownStatement(ctx)) {
484 qnameModule = getRootModuleQName(ctx);
486 if (qnameModule == null && ctx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
487 ctx = ctx.getOriginalCtx().orElse(null);
488 qnameModule = getModuleQNameByPrefix(ctx, prefix);
492 return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx,
493 "Cannot resolve QNameModule for '%s'", value), localName);
497 * Parse a YANG identifier string in context of a statement.
499 * @param ctx Statement context
500 * @param str String to be parsed
501 * @return An interned QName
502 * @throws NullPointerException if any of the arguments are null
503 * @throws SourceException if the string is not a valid YANG identifier
505 public static QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
506 SourceException.throwIf(str.isEmpty(), ctx, "Identifier may not be an empty string");
507 return internedQName(ctx, str);
510 public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String prefix,
511 final String localName) {
512 return internedQName(ctx,
513 InferenceException.throwIfNull(getModuleQNameByPrefix(ctx, prefix), ctx,
514 "Cannot resolve QNameModule for '%s'", prefix),
519 * Parse a YANG node identifier string in context of a statement.
521 * @param ctx Statement context
522 * @param str String to be parsed
523 * @return An interned QName
524 * @throws NullPointerException if any of the arguments are null
525 * @throws SourceException if the string is not a valid YANG node identifier
527 public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
528 SourceException.throwIf(str.isEmpty(), ctx, "Node identifier may not be an empty string");
530 final int colon = str.indexOf(':');
532 return internedQName(ctx, str);
535 final String prefix = str.substring(0, colon);
536 SourceException.throwIf(prefix.isEmpty(), ctx, "String '%s' has an empty prefix", str);
537 final String localName = str.substring(colon + 1);
538 SourceException.throwIf(localName.isEmpty(), ctx, "String '%s' has an empty identifier", str);
540 return parseNodeIdentifier(ctx, prefix, localName);
543 private static QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
544 return internedQName(ctx, getRootModuleQName(ctx), localName);
547 private static QName internedQName(final CommonStmtCtx ctx, final QNameModule module,
548 final String localName) {
549 final QName template;
551 template = QName.create(module, localName);
552 } catch (IllegalArgumentException e) {
553 throw new SourceException(ctx, e, "Invalid identifier '%s'", localName);
555 return template.intern();
558 public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
563 final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
564 final QNameModule qnameModule;
566 if (rootCtx.producesDeclared(ModuleStatement.class)) {
567 qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
568 } else if (rootCtx.producesDeclared(SubmoduleStatement.class)) {
569 final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
570 BelongsToStatement.class);
571 qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
576 checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
580 public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
581 final StmtContext<?, ?, ?> root = ctx.getRoot();
582 final StmtContext<?, ?, ?> importedModule = root.getFromNamespace(ImportPrefixToModuleCtx.class, prefix);
583 final QNameModule qnameModule = ctx.getFromNamespace(ModuleCtxToModuleQName.class, importedModule);
584 if (qnameModule != null) {
588 if (root.producesDeclared(SubmoduleStatement.class)) {
589 final String moduleName = root.getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
590 return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
596 public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
597 Revision revision = null;
598 for (final StmtContext<?, ?, ?> subStmt : subStmts) {
599 if (subStmt.producesDeclared(RevisionStatement.class)) {
600 if (revision == null && subStmt.argument() != null) {
601 revision = (Revision) subStmt.argument();
603 final Revision subArg = (Revision) subStmt.argument();
604 if (subArg != null && subArg.compareTo(revision) > 0) {
610 return Optional.ofNullable(revision);