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.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 if (!augmentNode.isSupportedToBuildEffective()) {
66 // We are not building effective model, hence we should not be performing any effects
70 final var augmentTargetCtx = target.resolve(ctx);
71 if (!isSupportedAugmentTarget(augmentTargetCtx)
72 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
73 augmentNode.setUnsupported();
77 // We are targeting a context which is creating implicit nodes. In order to keep things consistent,
78 // we will need to circle back when creating effective statements.
79 if (augmentTargetCtx.hasImplicitParentSupport()) {
80 augmentNode.addToNs(AugmentImplicitHandlingNamespace.class, Empty.value(), augmentTargetCtx);
83 copyFromSourceToTarget(augmentNode, augmentTargetCtx);
84 augmentTargetCtx.addEffectiveSubstatement(augmentNode.replicaAsChildOf(augmentTargetCtx));
88 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
90 * Do not fail, if it is an uses-augment to an unknown node.
92 if (YangStmtMapping.USES == augmentNode.coerceParentContext().publicDefinition()) {
93 if (!augmentNode.isSupportedToBuildEffective()) {
94 // We are not supported, hence the uses is not effective and we should bail
98 final SchemaNodeIdentifier augmentArg = augmentNode.getArgument();
99 final Optional<StmtContext<?, ?, ?>> targetNode = SchemaTreeNamespace.findNode(
100 AbstractAugmentStatementSupport.getSearchRoot(augmentNode), augmentArg);
101 if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
102 augmentNode.setUnsupported();
103 LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
104 augmentArg, augmentNode.sourceReference());
109 throw new InferenceException(augmentNode, "Augment target '%s' not found", augmentNode.argument());
113 public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
114 if (target.equals(unavail)) {
115 augmentNode.setUnsupported();
117 prerequisiteFailed(List.of(unavail));
121 private void copyFromSourceToTarget(final StmtContext<?, ?, ?> sourceCtx, final Mutable<?, ?, ?> targetCtx) {
122 final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
123 ? CopyType.ADDED_BY_USES_AUGMENTATION : CopyType.ADDED_BY_AUGMENTATION;
125 * Since Yang 1.1, if an augmentation is made conditional with a
126 * "when" statement, it is allowed to add mandatory nodes.
128 final boolean skipCheckOfMandatoryNodes = statementSupport.allowsMandatory(sourceCtx);
129 final boolean unsupported = !sourceCtx.isSupportedByFeatures();
131 final var declared = sourceCtx.declaredSubstatements();
132 final var effective = sourceCtx.effectiveSubstatements();
133 final var buffer = new ArrayList<Mutable<?, ?, ?>>(declared.size() + effective.size());
135 for (var originalStmtCtx : declared) {
136 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes,
137 unsupported || !originalStmtCtx.isSupportedByFeatures());
139 for (var originalStmtCtx : effective) {
140 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes, unsupported);
143 targetCtx.addEffectiveSubstatements(buffer);
146 private static void copyStatement(final StmtContext<?, ?, ?> original, final Mutable<?, ?, ?> target,
147 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
148 final boolean skipCheckOfMandatoryNodes, final boolean unsupported) {
149 // We always copy statements, but if either the source statement or the augmentation which causes it are not
150 // supported to build we also mark the target as such.
151 if (!NOCOPY_DEF_SET.contains(original.publicDefinition())) {
152 validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
154 final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
156 copy.setUnsupported();
159 } else if (!unsupported && original.publicDefinition() == YangStmtMapping.TYPEDEF) {
160 // FIXME: what is this branch doing, really?
161 // Typedef's policy would imply a replica, hence normal target.childCopyOf(original, typeOfCopy)
163 // What does the !unsupported thing want to do?
164 buffer.add(original.replicaAsChildOf(target));
168 private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
169 final Mutable<?, ?, ?> targetCtx, final CopyType typeOfCopy, final boolean skipCheckOfMandatoryNodes) {
170 if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
171 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
172 checkForMandatoryNodes(sourceCtx);
175 // Data definition statements must not collide on their namespace
176 if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
177 for (StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
178 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
179 InferenceException.throwIf(Objects.equals(sourceCtx.argument(), subStatement.argument()), sourceCtx,
180 "An augment cannot add node named '%s' because this name is already used in target",
181 sourceCtx.rawArgument());
187 private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
188 if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
190 * We need to iterate over both declared and effective sub-statements,
191 * because a mandatory node can be:
192 * a) declared in augment body
193 * b) added to augment body also via uses of a grouping and
194 * such sub-statements are stored in effective sub-statements collection.
196 sourceCtx.allSubstatementsStream().forEach(AugmentInferenceAction::checkForMandatoryNodes);
199 InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx), sourceCtx,
200 "An augment cannot add node '%s' because it is mandatory and in module different than target",
201 sourceCtx.rawArgument());
204 private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
205 Mutable<?, ?, ?> targetCtx) {
207 * If the statement argument is not QName, it cannot be mandatory
208 * statement, therefore return false and skip mandatory nodes validation
210 final Object arg = sourceCtx.argument();
211 if (!(arg instanceof QName)) {
214 final QName sourceStmtQName = (QName) arg;
216 // RootStatementContext, for example
217 final Mutable<?, ?, ?> root = targetCtx.getRoot();
219 final Object targetArg = targetCtx.argument();
220 verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s", targetArg);
221 final QName targetStmtQName = (QName) targetArg;
223 * If target is from another module, return true and perform mandatory nodes validation
225 if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
230 * If target or one of the target's ancestors from the same namespace
231 * is a presence container
232 * or is non-mandatory choice
233 * or is non-mandatory list
234 * return false and skip mandatory nodes validation, because these nodes
235 * are not mandatory node containers according to RFC 6020 section 3.1.
237 if (StmtContextUtils.isPresenceContainer(targetCtx)
238 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
239 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
243 // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
244 // conditional -- in which case we do not run further checks
245 if (targetCtx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
246 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
247 if (optPrevCopy.isPresent()) {
248 final StmtContext<?, ?, ?> original = optPrevCopy.get();
249 final Object origArg = original.getArgument();
250 verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
252 if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
253 && AbstractAugmentStatementSupport.hasWhenSubstatement(getParentAugmentation(original))) {
258 } while ((targetCtx = targetCtx.getParentContext()) != root);
261 * All target node's parents belong to the same module as source node,
262 * therefore return false and skip mandatory nodes validation.
267 private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
268 StmtContext<?, ?, ?> parent = verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
269 while (parent.publicDefinition() != YangStmtMapping.AUGMENT) {
270 parent = verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
275 private static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
277 * :TODO Substatement must be allowed augment target type e.g.
278 * Container, etc... and must not be for example grouping, identity etc.
279 * It is problem in case when more than one substatements have the same
280 * QName, for example Grouping and Container are siblings and they have
281 * the same QName. We must find the Container and the Grouping must be
282 * ignored as disallowed augment target.
284 final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
285 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
287 // if no allowed target is returned we consider all targets allowed
288 return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
289 || allowedAugmentTargets.contains(substatementCtx.publicDefinition());