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.StatementDefinition;
26 import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceEffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.UnknownStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.UnrecognizedStatement;
37 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
38 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
39 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
40 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
41 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
43 public final class StmtContextUtils {
44 private StmtContextUtils() {
48 @SuppressWarnings("unchecked")
49 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
50 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
51 for (final StmtContext<?, ?, ?> ctx : contexts) {
52 if (ctx.producesDeclared(declaredType)) {
53 return (A) ctx.getStatementArgument();
59 @SuppressWarnings("unchecked")
60 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
61 final Class<D> declaredType) {
62 return ctx.producesDeclared(declaredType) ? (A) ctx.getStatementArgument() : null;
65 public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
66 final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
67 return firstAttributeOf(ctx.allSubstatements(), declaredType);
70 @SuppressWarnings("unchecked")
71 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstDeclaredSubstatement(
72 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
73 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
74 if (subStmtContext.producesDeclared(declaredType)) {
75 return (StmtContext<A, ?, ?>) subStmtContext;
82 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
83 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
84 if (startIndex >= types.length) {
88 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
89 if (producesDeclared(subStmtContext, types[startIndex])) {
90 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
97 @SuppressWarnings("unchecked")
98 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
99 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
100 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
101 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
102 if (subStmtContext.producesDeclared(declaredType)) {
103 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
106 return listBuilder.build();
109 @SuppressWarnings("unchecked")
110 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
111 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
112 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
113 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
114 if (subStmtContext.producesDeclared(type)) {
115 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
118 return listBuilder.build();
121 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
122 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
123 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
124 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
125 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
126 return listBuilder.build();
129 @SuppressWarnings("unchecked")
130 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
131 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
132 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
133 if (subStmtContext.producesDeclared(declaredType)) {
134 return (StmtContext<A, ?, ?>) subStmtContext;
141 * Searches for the first substatement of the specified type in the specified statement context.
142 * First, it tries to find the substatement in the effective substatements of the statement context.
143 * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
144 * the method returns null.
146 * @param stmtContext statement context to search in
147 * @param declaredType substatement type to search for
148 * @param <A> statement argument type
149 * @param <D> declared statement type
150 * @return statement context that was searched for or null if was not found
151 * @deprecated Use {@link StmtContext#findSubstatementArgument(Class)} instead.
153 @Deprecated(forRemoval = true)
154 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
155 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
156 final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
157 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
161 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
162 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType, int sublevel) {
163 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
164 if (sublevel == 1 && producesDeclared(subStmtContext, declaredType)) {
165 return subStmtContext;
168 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
169 declaredType, --sublevel);
170 if (result != null) {
179 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
180 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
181 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
182 if (producesDeclared(subStmtContext, declaredType)) {
183 return subStmtContext;
186 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
187 if (result != null) {
195 @Deprecated(forRemoval = true)
196 public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx,
197 final Class<? extends DeclaredStatement<?>> type) {
198 return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
201 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
202 StmtContext<?, ?, ?> current = stmtCtx;
205 final StmtContext<?, ?, ?> parent = current.coerceParentContext();
206 if (parent.getParentContext() == null) {
209 if (isUnknownStatement(parent)) {
217 * Returns true if supplied statement context represents unknown statement,
218 * otherwise returns false.
221 * statement context to be checked
222 * @return true if supplied statement context represents unknown statement,
224 * @throws NullPointerException
225 * if supplied statement context is null
227 public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
228 return UnknownStatement.class
229 .isAssignableFrom(stmtCtx.getPublicDefinition().getDeclaredRepresentationClass());
233 * Returns true if supplied statement context represents unrecognized
234 * statement, otherwise returns false.
237 * statement context to be checked
238 * @return true if supplied statement context represents unrecognized
239 * statement, otherwise false
240 * @throws NullPointerException
241 * if supplied statement context is null
243 public static boolean isUnrecognizedStatement(final StmtContext<?, ?, ?> stmtCtx) {
244 return stmtCtx.producesDeclared(UnrecognizedStatement.class);
247 public static boolean checkFeatureSupport(final StmtContext<?, ?, ?> stmtContext,
248 final Set<QName> supportedFeatures) {
249 boolean isSupported = false;
250 boolean containsIfFeature = false;
251 for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
252 if (YangStmtMapping.IF_FEATURE.equals(stmt.getPublicDefinition())) {
253 containsIfFeature = true;
254 @SuppressWarnings("unchecked")
255 final Predicate<Set<QName>> argument = (Predicate<Set<QName>>) stmt.coerceStatementArgument();
256 if (argument.test(supportedFeatures)) {
265 return !containsIfFeature || isSupported;
269 * Checks whether statement context is a presence container or not.
273 * @return true if it is a presence container
275 public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
276 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
280 * Checks whether statement context is a non-presence container or not.
284 * @return true if it is a non-presence container
286 public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
287 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
290 private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
291 return stmtCtx.hasSubstatement(PresenceEffectiveStatement.class);
295 * Checks whether statement context is a mandatory leaf, choice, anyxml,
296 * list or leaf-list according to RFC6020 or not.
300 * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
301 * according to RFC6020.
303 public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
304 if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
307 switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
311 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
314 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
315 return minElements != null && minElements > 0;
322 * Checks whether a statement context is a statement of supplied statement
323 * definition and whether it is not mandatory leaf, choice, anyxml, list or
324 * leaf-list according to RFC6020.
329 * statement definition
330 * @return true if supplied statement context is a statement of supplied
331 * statement definition and if it is not mandatory leaf, choice,
332 * anyxml, list or leaf-list according to RFC6020
334 public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
335 final StatementDefinition stmtDef) {
336 return stmtCtx.getPublicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
340 * Checks whether at least one ancestor of a StatementContext matches one from a collection of statement
344 * StatementContext to be checked
345 * @param ancestorTypes
346 * collection of statement definitions
347 * @return true if at least one ancestor of a StatementContext matches one
348 * from collection of statement definitions, otherwise false.
350 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
351 final Collection<StatementDefinition> ancestorTypes) {
352 requireNonNull(ancestorTypes);
353 StmtContext<?, ?, ?> current = ctx.getParentContext();
354 while (current != null) {
355 if (ancestorTypes.contains(current.getPublicDefinition())) {
358 current = current.getParentContext();
364 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type.
366 * @param ctx StmtContext to be checked
367 * @param ancestorType type of ancestor to search for
368 * @param ancestorChildType type of child to search for in the specified ancestor type
369 * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
371 public static <A, D extends DeclaredStatement<A>> boolean hasAncestorOfTypeWithChildOfType(
372 final StmtContext<?, ?, ?> ctx, final StatementDefinition ancestorType,
373 final StatementDefinition ancestorChildType) {
375 requireNonNull(ancestorType);
376 requireNonNull(ancestorChildType);
378 StmtContext<?, ?, ?> current = ctx.coerceParentContext();
379 StmtContext<?, ?, ?> parent = current.getParentContext();
380 while (parent != null) {
381 if (ancestorType.equals(current.getPublicDefinition())
382 && !current.hasSubstatement(ancestorChildType.getEffectiveRepresentationClass())) {
387 parent = current.getParentContext();
394 * Checks whether the parent of StmtContext is of specified type.
397 * StmtContext to be checked
399 * type of parent to check
400 * @return true if the parent of StmtContext is of specified type, otherwise false
402 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
403 requireNonNull(parentType);
404 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
405 return parentContext != null && parentType.equals(parentContext.getPublicDefinition());
409 * Validates the specified statement context with regards to if-feature and when statement on list keys.
410 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
411 * statement defined in a keyed list (a uses statement may add leaves into the list).
414 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
416 * @param ctx statement context to be validated
418 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
419 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
423 final StmtContext<?, ?, ?> listStmtCtx = ctx.coerceParentContext();
424 final StmtContext<Set<QName>, ?, ?> keyStmtCtx = findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
426 if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
427 if (isListKey(ctx, keyStmtCtx)) {
428 disallowIfFeatureAndWhenOnListKeys(ctx);
430 } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
431 findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
432 if (isListKey(leafStmtCtx, keyStmtCtx)) {
433 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
439 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
440 return YangVersion.VERSION_1_1.equals(ctx.getRootVersion()) && hasParentOfType(ctx, YangStmtMapping.LIST)
441 && findFirstDeclaredSubstatement(ctx.coerceParentContext(), KeyStatement.class) != null;
444 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
445 final StmtContext<Set<QName>, ?, ?> keyStmtCtx) {
446 return keyStmtCtx.coerceStatementArgument().contains(leafStmtCtx.getStatementArgument());
449 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
450 leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
451 final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
452 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
453 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
454 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
455 statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
459 public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
460 if (Strings.isNullOrEmpty(value)) {
461 return ctx.getPublicDefinition().getStatementName();
465 QNameModule qnameModule = null;
466 String localName = null;
468 final String[] namesParts = value.split(":");
469 switch (namesParts.length) {
471 localName = namesParts[0];
472 qnameModule = getRootModuleQName(ctx);
475 prefix = namesParts[0];
476 localName = namesParts[1];
477 qnameModule = getModuleQNameByPrefix(ctx, prefix);
478 // in case of unknown statement argument, we're not going to parse it
479 if (qnameModule == null && isUnknownStatement(ctx)) {
481 qnameModule = getRootModuleQName(ctx);
483 if (qnameModule == null && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
484 ctx = ctx.getOriginalCtx().orElse(null);
485 qnameModule = getModuleQNameByPrefix(ctx, prefix);
489 return internedQName(ctx,
490 InferenceException.throwIfNull(qnameModule, ctx.getStatementSourceReference(),
491 "Cannot resolve QNameModule for '%s'", value), localName);
495 * Parse a YANG identifier string in context of a statement.
497 * @param ctx Statement context
498 * @param str String to be parsed
499 * @return An interned QName
500 * @throws NullPointerException if any of the arguments are null
501 * @throws SourceException if the string is not a valid YANG identifier
503 public static QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
504 SourceException.throwIf(str.isEmpty(), ctx.getStatementSourceReference(),
505 "Identifier may not be an empty string");
506 return internedQName(ctx, str);
509 public static QName parseNodeIdentifier(StmtContext<?, ?, ?> ctx, final String prefix,
510 final String localName) {
511 final QNameModule module = getModuleQNameByPrefix(ctx, prefix);
512 if (module != null) {
513 return internedQName(ctx, module, localName);
516 if (ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
517 final Optional<? extends StmtContext<?, ?, ?>> optOrigCtx = ctx.getOriginalCtx();
518 if (optOrigCtx.isPresent()) {
519 ctx = optOrigCtx.get();
520 final QNameModule origModule = getModuleQNameByPrefix(ctx, prefix);
521 if (origModule != null) {
522 return internedQName(ctx, origModule, localName);
527 throw new InferenceException(ctx.getStatementSourceReference(), "Cannot resolve QNameModule for '%s'", prefix);
531 * Parse a YANG node identifier string in context of a statement.
533 * @param ctx Statement context
534 * @param str String to be parsed
535 * @return An interned QName
536 * @throws NullPointerException if any of the arguments are null
537 * @throws SourceException if the string is not a valid YANG node identifier
539 public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
540 SourceException.throwIf(str.isEmpty(), ctx.getStatementSourceReference(),
541 "Node identifier may not be an empty string");
543 final int colon = str.indexOf(':');
545 return internedQName(ctx, str);
548 final String prefix = str.substring(0, colon);
549 SourceException.throwIf(prefix.isEmpty(), ctx.getStatementSourceReference(),
550 "String '%s' has an empty prefix", str);
551 final String localName = str.substring(colon + 1);
552 SourceException.throwIf(localName.isEmpty(), ctx.getStatementSourceReference(),
553 "String '%s' has an empty identifier", str);
555 return parseNodeIdentifier(ctx, prefix, localName);
558 private static QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
559 return internedQName(ctx, getRootModuleQName(ctx), localName);
562 private static QName internedQName(final StmtContext<?, ?, ?> ctx, final QNameModule module,
563 final String localName) {
564 final QName template;
566 template = QName.create(module, localName);
567 } catch (IllegalArgumentException e) {
568 throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid identifier '%s'", localName);
570 return template.intern();
573 public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
578 final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
579 final QNameModule qnameModule;
581 if (rootCtx.producesDeclared(ModuleStatement.class)) {
582 qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
583 } else if (rootCtx.producesDeclared(SubmoduleStatement.class)) {
584 final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
585 BelongsToStatement.class);
586 qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
591 checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
595 public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
596 final StmtContext<?, ?, ?> root = ctx.getRoot();
597 final StmtContext<?, ?, ?> importedModule = root.getFromNamespace(ImportPrefixToModuleCtx.class, prefix);
598 final QNameModule qnameModule = ctx.getFromNamespace(ModuleCtxToModuleQName.class, importedModule);
599 if (qnameModule != null) {
603 if (root.producesDeclared(SubmoduleStatement.class)) {
604 final String moduleName = root.getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
605 return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
611 public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
612 Revision revision = null;
613 for (final StmtContext<?, ?, ?> subStmt : subStmts) {
614 if (subStmt.producesDeclared(RevisionStatement.class)) {
615 if (revision == null && subStmt.getStatementArgument() != null) {
616 revision = (Revision) subStmt.getStatementArgument();
618 final Revision subArg = (Revision) subStmt.getStatementArgument();
619 if (subArg != null && subArg.compareTo(revision) > 0) {
625 return Optional.ofNullable(revision);