2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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.rfc7950.stmt.augment;
10 import static com.google.common.base.Verify.verify;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.collect.ImmutableSet;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Objects;
18 import java.util.Optional;
19 import org.opendaylight.yangtools.yang.common.Empty;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
22 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
27 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
28 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
37 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
38 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
39 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * Inference action, split out of {@link AbstractAugmentStatementSupport} for clarity and potential specialization.
46 final class AugmentInferenceAction implements InferenceAction {
47 private static final Logger LOG = LoggerFactory.getLogger(AugmentInferenceAction.class);
48 private static final ImmutableSet<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES,
49 YangStmtMapping.WHEN, YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
51 private final Mutable<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> augmentNode;
52 private final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target;
53 private final AbstractAugmentStatementSupport statementSupport;
55 AugmentInferenceAction(final AbstractAugmentStatementSupport statementSupport,
56 final Mutable<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> augmentNode,
57 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target) {
58 this.statementSupport = requireNonNull(statementSupport);
59 this.augmentNode = requireNonNull(augmentNode);
60 this.target = requireNonNull(target);
64 public void apply(final InferenceContext ctx) {
65 final StatementContextBase<?, ?, ?> augmentTargetCtx = (StatementContextBase<?, ?, ?>) target.resolve(ctx);
66 if (!isSupportedAugmentTarget(augmentTargetCtx)
67 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
68 augmentNode.setIsSupportedToBuildEffective(false);
72 // We are targeting a context which is creating implicit nodes. In order to keep things consistent,
73 // we will need to circle back when creating effective statements.
74 if (augmentTargetCtx.hasImplicitParentSupport()) {
75 augmentNode.addToNs(AugmentImplicitHandlingNamespace.class, Empty.getInstance(), augmentTargetCtx);
78 copyFromSourceToTarget((StatementContextBase<?, ?, ?>) augmentNode, augmentTargetCtx);
79 augmentTargetCtx.addEffectiveSubstatement(augmentNode.replicaAsChildOf(augmentTargetCtx));
83 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
85 * Do not fail, if it is an uses-augment to an unknown node.
87 if (YangStmtMapping.USES == augmentNode.coerceParentContext().publicDefinition()) {
88 final SchemaNodeIdentifier augmentArg = augmentNode.getArgument();
89 final Optional<StmtContext<?, ?, ?>> targetNode = SchemaTreeNamespace.findNode(
90 AbstractAugmentStatementSupport.getSearchRoot(augmentNode), augmentArg);
91 if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
92 augmentNode.setIsSupportedToBuildEffective(false);
93 LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
94 augmentArg, augmentNode.sourceReference());
99 throw new InferenceException(augmentNode, "Augment target '%s' not found", augmentNode.argument());
102 private void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
103 final StatementContextBase<?, ?, ?> targetCtx) {
104 final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
105 ? CopyType.ADDED_BY_USES_AUGMENTATION : CopyType.ADDED_BY_AUGMENTATION;
107 * Since Yang 1.1, if an augmentation is made conditional with a
108 * "when" statement, it is allowed to add mandatory nodes.
110 final boolean skipCheckOfMandatoryNodes = statementSupport.allowsMandatory(sourceCtx);
111 final boolean unsupported = !sourceCtx.isSupportedByFeatures();
113 final Collection<? extends Mutable<?, ?, ?>> declared = sourceCtx.mutableDeclaredSubstatements();
114 final Collection<? extends Mutable<?, ?, ?>> effective = sourceCtx.mutableEffectiveSubstatements();
115 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
117 for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
118 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes,
119 unsupported || !originalStmtCtx.isSupportedByFeatures());
121 for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
122 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes, unsupported);
125 targetCtx.addEffectiveSubstatements(buffer);
128 private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
129 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
130 final boolean skipCheckOfMandatoryNodes, final boolean unsupported) {
131 // We always copy statements, but if either the source statement or the augmentation which causes it are not
132 // supported to build we also mark the target as such.
133 if (!NOCOPY_DEF_SET.contains(original.publicDefinition())) {
134 validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
136 final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
138 copy.setIsSupportedToBuildEffective(false);
141 } else if (!unsupported && original.publicDefinition() == YangStmtMapping.TYPEDEF) {
142 buffer.add(original.replicaAsChildOf(target));
146 private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
147 final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
148 final boolean skipCheckOfMandatoryNodes) {
149 if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
150 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
151 checkForMandatoryNodes(sourceCtx);
154 // Data definition statements must not collide on their namespace
155 if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
156 for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
157 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
158 InferenceException.throwIf(Objects.equals(sourceCtx.argument(), subStatement.argument()), sourceCtx,
159 "An augment cannot add node named '%s' because this name is already used in target",
160 sourceCtx.rawArgument());
166 private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
167 if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
169 * We need to iterate over both declared and effective sub-statements,
170 * because a mandatory node can be:
171 * a) declared in augment body
172 * b) added to augment body also via uses of a grouping and
173 * such sub-statements are stored in effective sub-statements collection.
175 sourceCtx.allSubstatementsStream().forEach(AugmentInferenceAction::checkForMandatoryNodes);
178 InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx), sourceCtx,
179 "An augment cannot add node '%s' because it is mandatory and in module different than target",
180 sourceCtx.rawArgument());
183 private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
184 Mutable<?, ?, ?> targetCtx) {
186 * If the statement argument is not QName, it cannot be mandatory
187 * statement, therefore return false and skip mandatory nodes validation
189 final Object arg = sourceCtx.argument();
190 if (!(arg instanceof QName)) {
193 final QName sourceStmtQName = (QName) arg;
195 // RootStatementContext, for example
196 final Mutable<?, ?, ?> root = targetCtx.getRoot();
198 final Object targetArg = targetCtx.argument();
199 verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s", targetArg);
200 final QName targetStmtQName = (QName) targetArg;
202 * If target is from another module, return true and perform mandatory nodes validation
204 if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
209 * If target or one of the target's ancestors from the same namespace
210 * is a presence container
211 * or is non-mandatory choice
212 * or is non-mandatory list
213 * return false and skip mandatory nodes validation, because these nodes
214 * are not mandatory node containers according to RFC 6020 section 3.1.
216 if (StmtContextUtils.isPresenceContainer(targetCtx)
217 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
218 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
222 // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
223 // conditional -- in which case we do not run further checks
224 if (targetCtx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
225 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
226 if (optPrevCopy.isPresent()) {
227 final StmtContext<?, ?, ?> original = optPrevCopy.get();
228 final Object origArg = original.getArgument();
229 verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
231 if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
232 && AbstractAugmentStatementSupport.hasWhenSubstatement(getParentAugmentation(original))) {
237 } while ((targetCtx = targetCtx.getParentContext()) != root);
240 * All target node's parents belong to the same module as source node,
241 * therefore return false and skip mandatory nodes validation.
246 private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
247 StmtContext<?, ?, ?> parent = verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
248 while (parent.publicDefinition() != YangStmtMapping.AUGMENT) {
249 parent = verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
254 private static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
256 * :TODO Substatement must be allowed augment target type e.g.
257 * Container, etc... and must not be for example grouping, identity etc.
258 * It is problem in case when more than one substatements have the same
259 * QName, for example Grouping and Container are siblings and they have
260 * the same QName. We must find the Container and the Grouping must be
261 * ignored as disallowed augment target.
263 final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
264 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
266 // if no allowed target is returned we consider all targets allowed
267 return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
268 || allowedAugmentTargets.contains(substatementCtx.publicDefinition());