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.base.VerifyException;
15 import com.google.common.collect.ImmutableList;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.List;
19 import java.util.Optional;
21 import java.util.function.Predicate;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.common.QNameModule;
25 import org.opendaylight.yangtools.yang.common.Revision;
26 import org.opendaylight.yangtools.yang.common.YangVersion;
27 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
28 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
30 import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.KeyEffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceEffectiveStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
39 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
40 import org.opendaylight.yangtools.yang.model.api.stmt.UnknownStatement;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
45 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
49 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
51 public final class StmtContextUtils {
52 private StmtContextUtils() {
56 @SuppressWarnings("unchecked")
57 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
58 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
59 for (final StmtContext<?, ?, ?> ctx : contexts) {
60 if (ctx.producesDeclared(declaredType)) {
61 return (A) ctx.argument();
67 @SuppressWarnings("unchecked")
68 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
69 final Class<D> declaredType) {
70 return ctx.producesDeclared(declaredType) ? (A) ctx.argument() : null;
73 public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
74 final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
75 return firstAttributeOf(ctx.allSubstatements(), declaredType);
78 @SuppressWarnings("unchecked")
79 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstDeclaredSubstatement(
80 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
81 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
82 if (subStmtContext.producesDeclared(declaredType)) {
83 return (StmtContext<A, ?, ?>) subStmtContext;
90 @SuppressWarnings({ "rawtypes", "unchecked" })
91 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
92 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
93 if (startIndex >= types.length) {
97 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
98 if (subStmtContext.producesDeclared((Class) types[startIndex])) {
99 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
100 ++startIndex, types);
106 @SuppressWarnings("unchecked")
107 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
108 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
109 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
110 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
111 if (subStmtContext.producesDeclared(declaredType)) {
112 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
115 return listBuilder.build();
118 @SuppressWarnings("unchecked")
119 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
120 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
121 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
122 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
123 if (subStmtContext.producesDeclared(type)) {
124 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
127 return listBuilder.build();
130 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
131 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
132 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
133 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
134 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
135 return listBuilder.build();
138 @SuppressWarnings("unchecked")
139 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
140 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
141 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
142 if (subStmtContext.producesDeclared(declaredType)) {
143 return (StmtContext<A, ?, ?>) subStmtContext;
150 * Searches for the first substatement of the specified type in the specified statement context.
151 * First, it tries to find the substatement in the effective substatements of the statement context.
152 * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
153 * the method returns null.
155 * @param stmtContext statement context to search in
156 * @param declaredType substatement type to search for
157 * @param <A> statement argument type
158 * @param <D> declared statement type
159 * @return statement context that was searched for or null if was not found
160 * @deprecated Use {@link BoundStmtCtx#findSubstatementArgument(Class)} instead.
162 @Deprecated(forRemoval = true)
163 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
164 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
165 final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
166 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
170 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
171 final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType, int sublevel) {
172 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
173 if (sublevel == 1 && subStmtContext.producesDeclared(declaredType)) {
174 return subStmtContext;
177 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
178 declaredType, --sublevel);
179 if (result != null) {
188 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
189 final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType) {
190 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
191 if (subStmtContext.producesDeclared(declaredType)) {
192 return subStmtContext;
195 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
196 if (result != null) {
204 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
205 StmtContext<?, ?, ?> current = stmtCtx;
208 final StmtContext<?, ?, ?> parent = current.coerceParentContext();
209 if (parent.getParentContext() == null) {
212 if (isUnknownStatement(parent)) {
220 * Returns true if supplied statement context represents unknown statement,
221 * otherwise returns false.
224 * statement context to be checked
225 * @return true if supplied statement context represents unknown statement,
227 * @throws NullPointerException
228 * if supplied statement context is null
230 public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
231 return UnknownStatement.class.isAssignableFrom(stmtCtx.publicDefinition().getDeclaredRepresentationClass());
234 public static boolean checkFeatureSupport(final StmtContext<?, ?, ?> stmtContext,
235 final Set<QName> supportedFeatures) {
236 boolean isSupported = false;
237 boolean containsIfFeature = false;
238 for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
239 if (YangStmtMapping.IF_FEATURE.equals(stmt.publicDefinition())) {
240 containsIfFeature = true;
241 @SuppressWarnings("unchecked")
242 final Predicate<Set<QName>> argument = (Predicate<Set<QName>>) stmt.getArgument();
243 if (argument.test(supportedFeatures)) {
252 return !containsIfFeature || isSupported;
256 * Checks whether statement context is a presence container or not.
260 * @return true if it is a presence container
262 public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
263 return stmtCtx.publicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
267 * Checks whether statement context is a non-presence container or not.
271 * @return true if it is a non-presence container
273 public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
274 return stmtCtx.publicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
277 private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
278 return stmtCtx.hasSubstatement(PresenceEffectiveStatement.class);
282 * Checks whether statement context is a mandatory leaf, choice, anyxml,
283 * list or leaf-list according to RFC6020 or not.
287 * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
288 * according to RFC6020.
290 public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
291 if (!(stmtCtx.publicDefinition() instanceof YangStmtMapping)) {
294 switch ((YangStmtMapping) stmtCtx.publicDefinition()) {
298 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
301 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
302 return minElements != null && minElements > 0;
309 * Checks whether a statement context is a statement of supplied statement
310 * definition and whether it is not mandatory leaf, choice, anyxml, list or
311 * leaf-list according to RFC6020.
316 * statement definition
317 * @return true if supplied statement context is a statement of supplied
318 * statement definition and if it is not mandatory leaf, choice,
319 * anyxml, list or leaf-list according to RFC6020
321 public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
322 final StatementDefinition stmtDef) {
323 return stmtCtx.publicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
327 * Checks whether at least one ancestor of a StatementContext matches one from a collection of statement
330 * @param stmt Statement context to be checked
331 * @param ancestorTypes collection of statement definitions
332 * @return true if at least one ancestor of a StatementContext matches one
333 * from collection of statement definitions, otherwise false.
335 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> stmt,
336 final Collection<StatementDefinition> ancestorTypes) {
337 requireNonNull(ancestorTypes);
338 StmtContext<?, ?, ?> current = stmt.getParentContext();
339 while (current != null) {
340 if (ancestorTypes.contains(current.publicDefinition())) {
343 current = current.getParentContext();
349 * Check whether all of StmtContext's {@code list} ancestors have a {@code key}.
351 * @param stmt EffectiveStmtCtx to be checked
352 * @param name Human-friendly statement name
353 * @throws SourceException if there is any keyless list ancestor
355 public static void validateNoKeylessListAncestorOf(final Mutable<?, ?, ?> stmt, final String name) {
356 requireNonNull(stmt);
358 // We do not expect this to by typically populated
359 final List<Mutable<?, ?, ?>> incomplete = new ArrayList<>(0);
361 Mutable<?, ?, ?> current = stmt.coerceParentContext();
362 Mutable<?, ?, ?> parent = current.getParentContext();
363 while (parent != null) {
364 if (YangStmtMapping.LIST == current.publicDefinition()
365 && !current.hasSubstatement(KeyEffectiveStatement.class)) {
366 if (ModelProcessingPhase.FULL_DECLARATION.isCompletedBy(current.getCompletedPhase())) {
367 throw new SourceException(stmt, "%s %s is defined within a list that has no key statement", name,
371 // Ancestor has not completed full declaration yet missing 'key' statement may materialize later
372 incomplete.add(current);
376 parent = current.getParentContext();
379 // Deal with whatever incomplete ancestors we encountered
380 for (Mutable<?, ?, ?> ancestor : incomplete) {
381 // This check must complete during the ancestor's FULL_DECLARATION phase, i.e. the ancestor must not reach
382 // EFFECTIVE_MODEL until it is done.
383 final ModelActionBuilder action = ancestor.newInferenceAction(ModelProcessingPhase.FULL_DECLARATION);
384 action.apply(new InferenceAction() {
386 public void apply(final InferenceContext ctx) {
387 if (!ancestor.hasSubstatement(KeyEffectiveStatement.class)) {
388 throw new SourceException(stmt, "%s %s is defined within a list that has no key statement",
389 name, stmt.argument());
394 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
395 throw new VerifyException("Should never happen");
402 * Checks whether the parent of StmtContext is of specified type.
404 * @param ctx StmtContext to be checked
405 * @param parentType type of parent to check
406 * @return true if the parent of StmtContext is of specified type, otherwise false
408 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
409 requireNonNull(parentType);
410 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
411 return parentContext != null && parentType.equals(parentContext.publicDefinition());
415 * Validates the specified statement context with regards to if-feature and when statement on list keys.
416 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
417 * statement defined in a keyed list (a uses statement may add leaves into the list).
420 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
422 * @param ctx statement context to be validated
424 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
425 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
429 final StmtContext<?, ?, ?> listStmtCtx = ctx.coerceParentContext();
430 final StmtContext<Set<QName>, ?, ?> keyStmtCtx = findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
432 if (YangStmtMapping.LEAF.equals(ctx.publicDefinition())) {
433 if (isListKey(ctx, keyStmtCtx)) {
434 disallowIfFeatureAndWhenOnListKeys(ctx);
436 } else if (YangStmtMapping.USES.equals(ctx.publicDefinition())) {
437 findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
438 if (isListKey(leafStmtCtx, keyStmtCtx)) {
439 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
445 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
446 return YangVersion.VERSION_1_1.equals(ctx.yangVersion()) && hasParentOfType(ctx, YangStmtMapping.LIST)
447 && findFirstDeclaredSubstatement(ctx.coerceParentContext(), KeyStatement.class) != null;
450 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
451 final StmtContext<Set<QName>, ?, ?> keyStmtCtx) {
452 return keyStmtCtx.getArgument().contains(leafStmtCtx.argument());
455 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
456 leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
457 final StatementDefinition statementDef = leafSubstmtCtx.publicDefinition();
458 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
459 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx,
460 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
461 statementDef.getStatementName(), leafStmtCtx.argument());
465 public static @NonNull QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
466 if (Strings.isNullOrEmpty(value)) {
467 return ctx.publicDefinition().getStatementName();
471 QNameModule qnameModule = null;
472 String localName = null;
474 final String[] namesParts = value.split(":");
475 switch (namesParts.length) {
477 localName = namesParts[0];
478 qnameModule = getRootModuleQName(ctx);
481 prefix = namesParts[0];
482 localName = namesParts[1];
483 qnameModule = getModuleQNameByPrefix(ctx, prefix);
484 // in case of unknown statement argument, we're not going to parse it
485 if (qnameModule == null && isUnknownStatement(ctx)) {
487 qnameModule = getRootModuleQName(ctx);
489 if (qnameModule == null && ctx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
490 ctx = ctx.getOriginalCtx().orElse(null);
491 qnameModule = getModuleQNameByPrefix(ctx, prefix);
495 return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx,
496 "Cannot resolve QNameModule for '%s'", value), localName);
500 * Parse a YANG identifier string in context of a statement.
502 * @param ctx Statement context
503 * @param str String to be parsed
504 * @return An interned QName
505 * @throws NullPointerException if any of the arguments are null
506 * @throws SourceException if the string is not a valid YANG identifier
508 public static @NonNull QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
509 SourceException.throwIf(str.isEmpty(), ctx, "Identifier may not be an empty string");
510 return internedQName(ctx, str);
513 public static @NonNull QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String prefix,
514 final String localName) {
515 return internedQName(ctx,
516 InferenceException.throwIfNull(getModuleQNameByPrefix(ctx, prefix), ctx,
517 "Cannot resolve QNameModule for '%s'", prefix),
522 * Parse a YANG node identifier string in context of a statement.
524 * @param ctx Statement context
525 * @param str String to be parsed
526 * @return An interned QName
527 * @throws NullPointerException if any of the arguments are null
528 * @throws SourceException if the string is not a valid YANG node identifier
530 public static @NonNull QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
531 SourceException.throwIf(str.isEmpty(), ctx, "Node identifier may not be an empty string");
533 final int colon = str.indexOf(':');
535 return internedQName(ctx, str);
538 final String prefix = str.substring(0, colon);
539 SourceException.throwIf(prefix.isEmpty(), ctx, "String '%s' has an empty prefix", str);
540 final String localName = str.substring(colon + 1);
541 SourceException.throwIf(localName.isEmpty(), ctx, "String '%s' has an empty identifier", str);
543 return parseNodeIdentifier(ctx, prefix, localName);
546 private static @NonNull QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
547 return internedQName(ctx, getRootModuleQName(ctx), localName);
550 private static @NonNull QName internedQName(final CommonStmtCtx ctx, final QNameModule module,
551 final String localName) {
552 final QName template;
554 template = QName.create(module, localName);
555 } catch (IllegalArgumentException e) {
556 throw new SourceException(ctx, e, "Invalid identifier '%s'", localName);
558 return template.intern();
561 public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
566 final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
567 final QNameModule qnameModule;
569 if (rootCtx.producesDeclared(ModuleStatement.class)) {
570 qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
571 } else if (rootCtx.producesDeclared(SubmoduleStatement.class)) {
572 final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
573 BelongsToStatement.class);
574 qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
579 checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
583 public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
584 final StmtContext<?, ?, ?> root = ctx.getRoot();
585 final StmtContext<?, ?, ?> importedModule = root.getFromNamespace(ImportPrefixToModuleCtx.class, prefix);
586 final QNameModule qnameModule = ctx.getFromNamespace(ModuleCtxToModuleQName.class, importedModule);
587 if (qnameModule != null) {
591 if (root.producesDeclared(SubmoduleStatement.class)) {
592 final String moduleName = root.getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
593 return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
599 public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
600 Revision revision = null;
601 for (final StmtContext<?, ?, ?> subStmt : subStmts) {
602 if (subStmt.producesDeclared(RevisionStatement.class)) {
603 if (revision == null && subStmt.argument() != null) {
604 revision = (Revision) subStmt.argument();
606 final Revision subArg = (Revision) subStmt.argument();
607 if (subArg != null && subArg.compareTo(revision) > 0) {
613 return Optional.ofNullable(revision);