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.List;
18 import java.util.Objects;
19 import java.util.Optional;
20 import org.opendaylight.yangtools.yang.common.Empty;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
23 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
28 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
29 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
38 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
40 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
45 * Inference action, split out of {@link AbstractAugmentStatementSupport} for clarity and potential specialization.
47 final class AugmentInferenceAction implements InferenceAction {
48 private static final Logger LOG = LoggerFactory.getLogger(AugmentInferenceAction.class);
49 private static final ImmutableSet<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES,
50 YangStmtMapping.WHEN, YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
52 private final Mutable<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> augmentNode;
53 private final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target;
54 private final AbstractAugmentStatementSupport statementSupport;
56 AugmentInferenceAction(final AbstractAugmentStatementSupport statementSupport,
57 final Mutable<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> augmentNode,
58 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target) {
59 this.statementSupport = requireNonNull(statementSupport);
60 this.augmentNode = requireNonNull(augmentNode);
61 this.target = requireNonNull(target);
65 public void apply(final InferenceContext ctx) {
66 if (!augmentNode.isSupportedToBuildEffective()) {
67 // We are not building effective model, hence we should not be performing any effects
71 final StatementContextBase<?, ?, ?> augmentTargetCtx = (StatementContextBase<?, ?, ?>) target.resolve(ctx);
72 if (!isSupportedAugmentTarget(augmentTargetCtx)
73 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
74 augmentNode.setIsSupportedToBuildEffective(false);
78 // We are targeting a context which is creating implicit nodes. In order to keep things consistent,
79 // we will need to circle back when creating effective statements.
80 if (augmentTargetCtx.hasImplicitParentSupport()) {
81 augmentNode.addToNs(AugmentImplicitHandlingNamespace.class, Empty.value(), augmentTargetCtx);
84 copyFromSourceToTarget((StatementContextBase<?, ?, ?>) augmentNode, augmentTargetCtx);
85 augmentTargetCtx.addEffectiveSubstatement(augmentNode.replicaAsChildOf(augmentTargetCtx));
89 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
91 * Do not fail, if it is an uses-augment to an unknown node.
93 if (YangStmtMapping.USES == augmentNode.coerceParentContext().publicDefinition()) {
94 final SchemaNodeIdentifier augmentArg = augmentNode.getArgument();
95 final Optional<StmtContext<?, ?, ?>> targetNode = SchemaTreeNamespace.findNode(
96 AbstractAugmentStatementSupport.getSearchRoot(augmentNode), augmentArg);
97 if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
98 augmentNode.setIsSupportedToBuildEffective(false);
99 LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
100 augmentArg, augmentNode.sourceReference());
105 throw new InferenceException(augmentNode, "Augment target '%s' not found", augmentNode.argument());
109 public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
110 if (target.equals(unavail)) {
111 augmentNode.setIsSupportedToBuildEffective(false);
113 prerequisiteFailed(List.of(unavail));
117 private void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
118 final StatementContextBase<?, ?, ?> targetCtx) {
119 final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
120 ? CopyType.ADDED_BY_USES_AUGMENTATION : CopyType.ADDED_BY_AUGMENTATION;
122 * Since Yang 1.1, if an augmentation is made conditional with a
123 * "when" statement, it is allowed to add mandatory nodes.
125 final boolean skipCheckOfMandatoryNodes = statementSupport.allowsMandatory(sourceCtx);
126 final boolean unsupported = !sourceCtx.isSupportedByFeatures();
128 final Collection<? extends Mutable<?, ?, ?>> declared = sourceCtx.mutableDeclaredSubstatements();
129 final Collection<? extends Mutable<?, ?, ?>> effective = sourceCtx.mutableEffectiveSubstatements();
130 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
132 for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
133 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes,
134 unsupported || !originalStmtCtx.isSupportedByFeatures());
136 for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
137 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes, unsupported);
140 targetCtx.addEffectiveSubstatements(buffer);
143 private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
144 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
145 final boolean skipCheckOfMandatoryNodes, final boolean unsupported) {
146 // We always copy statements, but if either the source statement or the augmentation which causes it are not
147 // supported to build we also mark the target as such.
148 if (!NOCOPY_DEF_SET.contains(original.publicDefinition())) {
149 validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
151 final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
153 copy.setIsSupportedToBuildEffective(false);
156 } else if (!unsupported && original.publicDefinition() == YangStmtMapping.TYPEDEF) {
157 // FIXME: what is this branch doing, really?
158 // Typedef's policy would imply a replica, hence normal target.childCopyOf(original, typeOfCopy)
160 // What does the !unsupported thing want to do?
161 buffer.add(original.replicaAsChildOf(target));
165 private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
166 final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
167 final boolean skipCheckOfMandatoryNodes) {
168 if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
169 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
170 checkForMandatoryNodes(sourceCtx);
173 // Data definition statements must not collide on their namespace
174 if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
175 for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
176 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
177 InferenceException.throwIf(Objects.equals(sourceCtx.argument(), subStatement.argument()), sourceCtx,
178 "An augment cannot add node named '%s' because this name is already used in target",
179 sourceCtx.rawArgument());
185 private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
186 if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
188 * We need to iterate over both declared and effective sub-statements,
189 * because a mandatory node can be:
190 * a) declared in augment body
191 * b) added to augment body also via uses of a grouping and
192 * such sub-statements are stored in effective sub-statements collection.
194 sourceCtx.allSubstatementsStream().forEach(AugmentInferenceAction::checkForMandatoryNodes);
197 InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx), sourceCtx,
198 "An augment cannot add node '%s' because it is mandatory and in module different than target",
199 sourceCtx.rawArgument());
202 private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
203 Mutable<?, ?, ?> targetCtx) {
205 * If the statement argument is not QName, it cannot be mandatory
206 * statement, therefore return false and skip mandatory nodes validation
208 final Object arg = sourceCtx.argument();
209 if (!(arg instanceof QName)) {
212 final QName sourceStmtQName = (QName) arg;
214 // RootStatementContext, for example
215 final Mutable<?, ?, ?> root = targetCtx.getRoot();
217 final Object targetArg = targetCtx.argument();
218 verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s", targetArg);
219 final QName targetStmtQName = (QName) targetArg;
221 * If target is from another module, return true and perform mandatory nodes validation
223 if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
228 * If target or one of the target's ancestors from the same namespace
229 * is a presence container
230 * or is non-mandatory choice
231 * or is non-mandatory list
232 * return false and skip mandatory nodes validation, because these nodes
233 * are not mandatory node containers according to RFC 6020 section 3.1.
235 if (StmtContextUtils.isPresenceContainer(targetCtx)
236 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
237 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
241 // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
242 // conditional -- in which case we do not run further checks
243 if (targetCtx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
244 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
245 if (optPrevCopy.isPresent()) {
246 final StmtContext<?, ?, ?> original = optPrevCopy.get();
247 final Object origArg = original.getArgument();
248 verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
250 if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
251 && AbstractAugmentStatementSupport.hasWhenSubstatement(getParentAugmentation(original))) {
256 } while ((targetCtx = targetCtx.getParentContext()) != root);
259 * All target node's parents belong to the same module as source node,
260 * therefore return false and skip mandatory nodes validation.
265 private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
266 StmtContext<?, ?, ?> parent = verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
267 while (parent.publicDefinition() != YangStmtMapping.AUGMENT) {
268 parent = verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
273 private static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
275 * :TODO Substatement must be allowed augment target type e.g.
276 * Container, etc... and must not be for example grouping, identity etc.
277 * It is problem in case when more than one substatements have the same
278 * QName, for example Grouping and Container are siblings and they have
279 * the same QName. We must find the Container and the Grouping must be
280 * ignored as disallowed augment target.
282 final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
283 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
285 // if no allowed target is returned we consider all targets allowed
286 return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
287 || allowedAugmentTargets.contains(substatementCtx.publicDefinition());