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 java.util.Objects.requireNonNull;
12 import com.google.common.base.Strings;
13 import com.google.common.base.VerifyException;
14 import com.google.common.collect.ImmutableList;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.List;
18 import java.util.Optional;
20 import java.util.function.Predicate;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.common.QNameModule;
24 import org.opendaylight.yangtools.yang.common.Revision;
25 import org.opendaylight.yangtools.yang.common.YangVersion;
26 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
29 import org.opendaylight.yangtools.yang.model.api.stmt.KeyEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceEffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.UnknownStatement;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
43 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
44 import org.opendaylight.yangtools.yang.parser.spi.source.SourceParserNamespaces;
46 public final class StmtContextUtils {
47 private StmtContextUtils() {
51 @SuppressWarnings("unchecked")
52 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
53 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
54 for (final StmtContext<?, ?, ?> ctx : contexts) {
55 if (ctx.producesDeclared(declaredType)) {
56 return (A) ctx.argument();
62 @SuppressWarnings("unchecked")
63 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
64 final Class<D> declaredType) {
65 return ctx.producesDeclared(declaredType) ? (A) ctx.argument() : null;
68 public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
69 final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
70 return firstAttributeOf(ctx.allSubstatements(), declaredType);
73 @SuppressWarnings("unchecked")
74 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstDeclaredSubstatement(
75 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
76 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
77 if (subStmtContext.producesDeclared(declaredType)) {
78 return (StmtContext<A, ?, ?>) subStmtContext;
85 @SuppressWarnings({ "rawtypes", "unchecked" })
86 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
87 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
88 if (startIndex >= types.length) {
92 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
93 if (subStmtContext.producesDeclared((Class) types[startIndex])) {
94 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
101 @SuppressWarnings("unchecked")
102 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
103 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
104 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
105 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
106 if (subStmtContext.producesDeclared(declaredType)) {
107 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
110 return listBuilder.build();
113 @SuppressWarnings("unchecked")
114 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
115 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
116 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
117 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
118 if (subStmtContext.producesDeclared(type)) {
119 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
122 return listBuilder.build();
125 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
126 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
127 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
128 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
129 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
130 return listBuilder.build();
133 @SuppressWarnings("unchecked")
134 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
135 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
136 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
137 if (subStmtContext.producesDeclared(declaredType)) {
138 return (StmtContext<A, ?, ?>) subStmtContext;
144 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
145 final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType, int sublevel) {
146 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
147 if (sublevel == 1 && subStmtContext.producesDeclared(declaredType)) {
148 return subStmtContext;
151 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
152 declaredType, --sublevel);
153 if (result != null) {
162 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
163 final StmtContext<?, ?, ?> stmtContext, final Class<? super D> declaredType) {
164 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
165 if (subStmtContext.producesDeclared(declaredType)) {
166 return subStmtContext;
169 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
170 if (result != null) {
178 // FIXME: 8.0.0: This method goes back as far as YANGTOOLS-365, when we were build EffectiveStatements for
179 // unsupported YANG extensions. We are not doing that anymore, do we still need this method? Also, it
180 // is only used in augment support to disable mechanics on unknown nodes.
182 // It would seem we can move this method to AbstractAugmentStatementSupport at the very least, but
183 // also: augments are defined to operate on schema tree nodes, hence even if we have an
184 // UnknownStatement, but its EffectiveStatement projection supports SchemaTreeAwareEffectiveStatement
185 // we should operate normally -- the StatementSupport exposing such semantics is responsible for
186 // arranging the backend details.
187 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
188 StmtContext<?, ?, ?> current = stmtCtx;
191 final StmtContext<?, ?, ?> parent = current.coerceParentContext();
192 if (parent.getParentContext() == null) {
195 if (isUnknownStatement(parent)) {
203 * Returns true if supplied statement context represents unknown statement,
204 * otherwise returns false.
207 * statement context to be checked
208 * @return true if supplied statement context represents unknown statement,
210 * @throws NullPointerException
211 * if supplied statement context is null
213 public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
214 return UnknownStatement.class.isAssignableFrom(stmtCtx.publicDefinition().getDeclaredRepresentationClass());
217 public static boolean checkFeatureSupport(final StmtContext<?, ?, ?> stmtContext,
218 final Set<QName> supportedFeatures) {
219 boolean isSupported = false;
220 boolean containsIfFeature = false;
221 for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
222 if (YangStmtMapping.IF_FEATURE.equals(stmt.publicDefinition())) {
223 containsIfFeature = true;
224 @SuppressWarnings("unchecked")
225 final Predicate<Set<QName>> argument = (Predicate<Set<QName>>) stmt.getArgument();
226 if (argument.test(supportedFeatures)) {
235 return !containsIfFeature || isSupported;
239 * Checks whether statement context is a presence container or not.
243 * @return true if it is a presence container
245 public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
246 return stmtCtx.publicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
250 * Checks whether statement context is a non-presence container or not.
254 * @return true if it is a non-presence container
256 public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
257 return stmtCtx.publicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
260 private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
261 return stmtCtx.hasSubstatement(PresenceEffectiveStatement.class);
265 * Checks whether statement context is a mandatory leaf, choice, anyxml,
266 * list or leaf-list according to RFC6020 or not.
270 * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
271 * according to RFC6020.
273 public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
274 if (!(stmtCtx.publicDefinition() instanceof YangStmtMapping)) {
277 switch ((YangStmtMapping) stmtCtx.publicDefinition()) {
281 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
284 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
285 return minElements != null && minElements > 0;
292 * Checks whether a statement context is a statement of supplied statement
293 * definition and whether it is not mandatory leaf, choice, anyxml, list or
294 * leaf-list according to RFC6020.
299 * statement definition
300 * @return true if supplied statement context is a statement of supplied
301 * statement definition and if it is not mandatory leaf, choice,
302 * anyxml, list or leaf-list according to RFC6020
304 public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
305 final StatementDefinition stmtDef) {
306 return stmtCtx.publicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
310 * Checks whether at least one ancestor of a StatementContext matches one from a collection of statement
313 * @param stmt Statement context to be checked
314 * @param ancestorTypes collection of statement definitions
315 * @return true if at least one ancestor of a StatementContext matches one
316 * from collection of statement definitions, otherwise false.
318 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> stmt,
319 final Collection<StatementDefinition> ancestorTypes) {
320 requireNonNull(ancestorTypes);
321 StmtContext<?, ?, ?> current = stmt.getParentContext();
322 while (current != null) {
323 if (ancestorTypes.contains(current.publicDefinition())) {
326 current = current.getParentContext();
332 * Check whether all of StmtContext's {@code list} ancestors have a {@code key}.
334 * @param stmt EffectiveStmtCtx to be checked
335 * @param name Human-friendly statement name
336 * @throws SourceException if there is any keyless list ancestor
338 public static void validateNoKeylessListAncestorOf(final Mutable<?, ?, ?> stmt, final String name) {
339 requireNonNull(stmt);
341 // We do not expect this to by typically populated
342 final List<Mutable<?, ?, ?>> incomplete = new ArrayList<>(0);
344 Mutable<?, ?, ?> current = stmt.coerceParentContext();
345 Mutable<?, ?, ?> parent = current.getParentContext();
346 while (parent != null) {
347 if (YangStmtMapping.LIST == current.publicDefinition()
348 && !current.hasSubstatement(KeyEffectiveStatement.class)) {
349 if (ModelProcessingPhase.FULL_DECLARATION.isCompletedBy(current.getCompletedPhase())) {
350 throw new SourceException(stmt, "%s %s is defined within a list that has no key statement", name,
354 // Ancestor has not completed full declaration yet missing 'key' statement may materialize later
355 incomplete.add(current);
359 parent = current.getParentContext();
362 // Deal with whatever incomplete ancestors we encountered
363 for (Mutable<?, ?, ?> ancestor : incomplete) {
364 // This check must complete during the ancestor's FULL_DECLARATION phase, i.e. the ancestor must not reach
365 // EFFECTIVE_MODEL until it is done.
366 final ModelActionBuilder action = ancestor.newInferenceAction(ModelProcessingPhase.FULL_DECLARATION);
367 action.apply(new InferenceAction() {
369 public void apply(final InferenceContext ctx) {
370 if (!ancestor.hasSubstatement(KeyEffectiveStatement.class)) {
371 throw new SourceException(stmt, "%s %s is defined within a list that has no key statement",
372 name, stmt.argument());
377 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
378 throw new VerifyException("Should never happen");
385 * Checks whether the parent of StmtContext is of specified type.
387 * @param ctx StmtContext to be checked
388 * @param parentType type of parent to check
389 * @return true if the parent of StmtContext is of specified type, otherwise false
391 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
392 requireNonNull(parentType);
393 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
394 return parentContext != null && parentType.equals(parentContext.publicDefinition());
398 * Validates the specified statement context with regards to if-feature and when statement on list keys.
399 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
400 * statement defined in a keyed list (a uses statement may add leaves into the list).
403 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
405 * @param ctx statement context to be validated
407 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
408 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
412 final StmtContext<?, ?, ?> listStmtCtx = ctx.coerceParentContext();
413 final StmtContext<Set<QName>, ?, ?> keyStmtCtx = findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
415 if (YangStmtMapping.LEAF.equals(ctx.publicDefinition())) {
416 if (isListKey(ctx, keyStmtCtx)) {
417 disallowIfFeatureAndWhenOnListKeys(ctx);
419 } else if (YangStmtMapping.USES.equals(ctx.publicDefinition())) {
420 findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
421 if (isListKey(leafStmtCtx, keyStmtCtx)) {
422 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
428 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
429 return YangVersion.VERSION_1_1.equals(ctx.yangVersion()) && hasParentOfType(ctx, YangStmtMapping.LIST)
430 && findFirstDeclaredSubstatement(ctx.coerceParentContext(), KeyStatement.class) != null;
433 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
434 final StmtContext<Set<QName>, ?, ?> keyStmtCtx) {
435 return keyStmtCtx.getArgument().contains(leafStmtCtx.argument());
438 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
439 leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
440 final StatementDefinition statementDef = leafSubstmtCtx.publicDefinition();
441 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
442 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx,
443 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
444 statementDef.getStatementName(), leafStmtCtx.argument());
448 public static @NonNull QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
449 if (Strings.isNullOrEmpty(value)) {
450 return ctx.publicDefinition().getStatementName();
454 QNameModule qnameModule = null;
455 String localName = null;
457 final String[] namesParts = value.split(":");
458 switch (namesParts.length) {
460 localName = namesParts[0];
461 qnameModule = getRootModuleQName(ctx);
464 prefix = namesParts[0];
465 localName = namesParts[1];
466 qnameModule = getModuleQNameByPrefix(ctx, prefix);
467 // in case of unknown statement argument, we're not going to parse it
468 if (qnameModule == null && isUnknownStatement(ctx)) {
470 qnameModule = getRootModuleQName(ctx);
472 if (qnameModule == null && ctx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
473 ctx = ctx.getOriginalCtx().orElse(null);
474 qnameModule = getModuleQNameByPrefix(ctx, prefix);
478 return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx,
479 "Cannot resolve QNameModule for '%s'", value), localName);
483 * Parse a YANG identifier string in context of a statement.
485 * @param ctx Statement context
486 * @param str String to be parsed
487 * @return An interned QName
488 * @throws NullPointerException if any of the arguments are null
489 * @throws SourceException if the string is not a valid YANG identifier
491 public static @NonNull QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
492 SourceException.throwIf(str.isEmpty(), ctx, "Identifier may not be an empty string");
493 return internedQName(ctx, str);
496 public static @NonNull QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String prefix,
497 final String localName) {
498 return internedQName(ctx,
499 InferenceException.throwIfNull(getModuleQNameByPrefix(ctx, prefix), ctx,
500 "Cannot resolve QNameModule for '%s'", prefix),
505 * Parse a YANG node identifier string in context of a statement.
507 * @param ctx Statement context
508 * @param str String to be parsed
509 * @return An interned QName
510 * @throws NullPointerException if any of the arguments are null
511 * @throws SourceException if the string is not a valid YANG node identifier
513 public static @NonNull QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
514 SourceException.throwIf(str.isEmpty(), ctx, "Node identifier may not be an empty string");
516 final int colon = str.indexOf(':');
518 return internedQName(ctx, str);
521 final String prefix = str.substring(0, colon);
522 SourceException.throwIf(prefix.isEmpty(), ctx, "String '%s' has an empty prefix", str);
523 final String localName = str.substring(colon + 1);
524 SourceException.throwIf(localName.isEmpty(), ctx, "String '%s' has an empty identifier", str);
526 return parseNodeIdentifier(ctx, prefix, localName);
529 private static @NonNull QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
530 return internedQName(ctx, getRootModuleQName(ctx), localName);
533 private static @NonNull QName internedQName(final CommonStmtCtx ctx, final QNameModule module,
534 final String localName) {
535 final QName template;
537 template = QName.create(module, localName);
538 } catch (IllegalArgumentException e) {
539 throw new SourceException(ctx, e, "Invalid identifier '%s'", localName);
541 return template.intern();
544 public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
545 return ctx == null ? null : getModuleQName(ctx.getRoot());
548 public static @NonNull QNameModule getModuleQName(final @NonNull RootStmtContext<?, ?, ?> ctx) {
549 if (ctx.producesDeclared(ModuleStatement.class)) {
550 return lookupModuleQName(ctx, ctx);
551 } else if (ctx.producesDeclared(SubmoduleStatement.class)) {
552 final var belongsTo = ctx.getAllFromNamespace(SourceParserNamespaces.BELONGSTO_PREFIX_TO_MODULECTX);
553 if (belongsTo == null || belongsTo.isEmpty()) {
554 throw new IllegalArgumentException(ctx + " does not have belongs-to linkage resolved");
556 return lookupModuleQName(ctx, belongsTo.values().iterator().next());
558 throw new IllegalArgumentException("Unsupported root " + ctx);
562 private static @NonNull QNameModule lookupModuleQName(final NamespaceStmtCtx storage,
563 final StmtContext<?, ?, ?> module) {
564 final var ret = storage.getFromNamespace(SourceParserNamespaces.MODULECTX_TO_QNAME, module);
566 throw new IllegalArgumentException("Failed to look up QNameModule for " + module + " in " + storage);
571 public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
572 final StmtContext<?, ?, ?> root = ctx.getRoot();
573 final StmtContext<?, ?, ?> importedModule = root.getFromNamespace(
574 SourceParserNamespaces.IMPORT_PREFIX_TO_MODULECTX, prefix);
575 final QNameModule qnameModule = ctx.getFromNamespace(SourceParserNamespaces.MODULECTX_TO_QNAME, importedModule);
576 if (qnameModule != null) {
580 if (root.producesDeclared(SubmoduleStatement.class)) {
581 return ctx.getFromNamespace(SourceParserNamespaces.MODULE_NAME_TO_QNAME,
582 root.getFromNamespace(SourceParserNamespaces.BELONGSTO_PREFIX_TO_MODULE_NAME, prefix));
588 public static Optional<Revision> getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
589 Revision revision = null;
590 for (final StmtContext<?, ?, ?> subStmt : subStmts) {
591 if (subStmt.producesDeclared(RevisionStatement.class)) {
592 if (revision == null && subStmt.argument() != null) {
593 revision = (Revision) subStmt.argument();
595 final Revision subArg = (Revision) subStmt.argument();
596 if (subArg != null && subArg.compareTo(revision) > 0) {
602 return Optional.ofNullable(revision);