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.ParserNamespaces;
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.ValidationBundles;
39 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundles.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 private boolean targetUnavailable;
57 AugmentInferenceAction(final AbstractAugmentStatementSupport statementSupport,
58 final Mutable<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> augmentNode,
59 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target) {
60 this.statementSupport = requireNonNull(statementSupport);
61 this.augmentNode = requireNonNull(augmentNode);
62 this.target = requireNonNull(target);
66 public void apply(final InferenceContext ctx) {
67 if (targetUnavailable) {
68 // Target node is not available, no further processing and the augment should not leak into effective world
69 augmentNode.setUnsupported();
73 final var augmentTargetCtx = target.resolve(ctx);
74 if (!isSupportedAugmentTarget(augmentTargetCtx)
75 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
76 augmentNode.setUnsupported();
80 // We are targeting a context which is creating implicit nodes. In order to keep things consistent,
81 // we will need to circle back when creating effective statements.
82 if (augmentTargetCtx.hasImplicitParentSupport()) {
83 augmentNode.addToNs(AugmentImplicitHandlingNamespace.INSTANCE, Empty.value(), augmentTargetCtx);
86 copyFromSourceToTarget(augmentNode, augmentTargetCtx);
87 augmentTargetCtx.addEffectiveSubstatement(augmentNode.replicaAsChildOf(augmentTargetCtx));
91 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
93 * Do not fail, if it is an uses-augment to an unknown node.
95 if (YangStmtMapping.USES == augmentNode.coerceParentContext().publicDefinition()) {
96 if (!augmentNode.isSupportedToBuildEffective()) {
97 // We are not supported, hence the uses is not effective and we should bail
101 final SchemaNodeIdentifier augmentArg = augmentNode.getArgument();
102 final Optional<StmtContext<?, ?, ?>> targetNode = ParserNamespaces.findSchemaTreeStatement(
103 AbstractAugmentStatementSupport.getSearchRoot(augmentNode), augmentArg);
104 if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
105 augmentNode.setUnsupported();
106 LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
107 augmentArg, augmentNode.sourceReference());
112 throw new InferenceException(augmentNode, "Augment target '%s' not found", augmentNode.argument());
116 public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
117 if (target.equals(unavail)) {
118 targetUnavailable = true;
120 prerequisiteFailed(List.of(unavail));
124 private void copyFromSourceToTarget(final StmtContext<?, ?, ?> sourceCtx, final Mutable<?, ?, ?> targetCtx) {
125 final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
126 ? CopyType.ADDED_BY_USES_AUGMENTATION : CopyType.ADDED_BY_AUGMENTATION;
128 * Since Yang 1.1, if an augmentation is made conditional with a
129 * "when" statement, it is allowed to add mandatory nodes.
131 final boolean skipCheckOfMandatoryNodes = statementSupport.allowsMandatory(sourceCtx);
132 final boolean unsupported = !sourceCtx.isSupportedByFeatures();
134 final var declared = sourceCtx.declaredSubstatements();
135 final var effective = sourceCtx.effectiveSubstatements();
136 final var buffer = new ArrayList<Mutable<?, ?, ?>>(declared.size() + effective.size());
138 for (var originalStmtCtx : declared) {
139 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes,
140 unsupported || !originalStmtCtx.isSupportedByFeatures());
142 for (var originalStmtCtx : effective) {
143 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes, unsupported);
146 targetCtx.addEffectiveSubstatements(buffer);
149 private static void copyStatement(final StmtContext<?, ?, ?> original, final Mutable<?, ?, ?> target,
150 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
151 final boolean skipCheckOfMandatoryNodes, final boolean unsupported) {
152 // We always copy statements, but if either the source statement or the augmentation which causes it are not
153 // supported to build we also mark the target as such.
154 if (!NOCOPY_DEF_SET.contains(original.publicDefinition())) {
155 validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
157 final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
159 copy.setUnsupported();
162 } else if (!unsupported && original.publicDefinition() == YangStmtMapping.TYPEDEF) {
163 // FIXME: what is this branch doing, really?
164 // Typedef's policy would imply a replica, hence normal target.childCopyOf(original, typeOfCopy)
166 // What does the !unsupported thing want to do?
167 buffer.add(original.replicaAsChildOf(target));
171 private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
172 final Mutable<?, ?, ?> targetCtx, final CopyType typeOfCopy, final boolean skipCheckOfMandatoryNodes) {
173 if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
174 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
175 checkForMandatoryNodes(sourceCtx);
178 // Data definition statements must not collide on their namespace
179 if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
180 for (StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
181 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
182 InferenceException.throwIf(Objects.equals(sourceCtx.argument(), subStatement.argument()), sourceCtx,
183 "An augment cannot add node named '%s' because this name is already used in target",
184 sourceCtx.rawArgument());
190 private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
191 if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
193 * We need to iterate over both declared and effective sub-statements,
194 * because a mandatory node can be:
195 * a) declared in augment body
196 * b) added to augment body also via uses of a grouping and
197 * such sub-statements are stored in effective sub-statements collection.
199 sourceCtx.allSubstatementsStream().forEach(AugmentInferenceAction::checkForMandatoryNodes);
202 InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx), sourceCtx,
203 "An augment cannot add node '%s' because it is mandatory and in module different than target",
204 sourceCtx.rawArgument());
207 private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
208 Mutable<?, ?, ?> targetCtx) {
210 * If the statement argument is not QName, it cannot be mandatory
211 * statement, therefore return false and skip mandatory nodes validation
213 final Object arg = sourceCtx.argument();
214 if (!(arg instanceof QName sourceStmtQName)) {
217 // RootStatementContext, for example
218 final Mutable<?, ?, ?> root = targetCtx.getRoot();
220 final Object targetArg = targetCtx.argument();
221 verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s", targetArg);
222 final QName targetStmtQName = (QName) targetArg;
224 * If target is from another module, return true and perform mandatory nodes validation
226 if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
231 * If target or one of the target's ancestors from the same namespace
232 * is a presence container
233 * or is non-mandatory choice
234 * or is non-mandatory list
235 * return false and skip mandatory nodes validation, because these nodes
236 * are not mandatory node containers according to RFC 6020 section 3.1.
238 if (StmtContextUtils.isPresenceContainer(targetCtx)
239 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
240 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
244 // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
245 // conditional -- in which case we do not run further checks
246 if (targetCtx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
247 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
248 if (optPrevCopy.isPresent()) {
249 final StmtContext<?, ?, ?> original = optPrevCopy.get();
250 final Object origArg = original.getArgument();
251 verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
253 if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
254 && AbstractAugmentStatementSupport.hasWhenSubstatement(getParentAugmentation(original))) {
259 } while ((targetCtx = targetCtx.getParentContext()) != root);
262 * All target node's parents belong to the same module as source node,
263 * therefore return false and skip mandatory nodes validation.
268 private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
269 StmtContext<?, ?, ?> parent = verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
270 while (parent.publicDefinition() != YangStmtMapping.AUGMENT) {
271 parent = verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
276 private static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
278 * :TODO Substatement must be allowed augment target type e.g.
279 * Container, etc... and must not be for example grouping, identity etc.
280 * It is problem in case when more than one substatements have the same
281 * QName, for example Grouping and Container are siblings and they have
282 * the same QName. We must find the Container and the Grouping must be
283 * ignored as disallowed augment target.
285 final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
286 ValidationBundles.NAMESPACE, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
288 // if no allowed target is returned we consider all targets allowed
289 return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
290 || allowedAugmentTargets.contains(substatementCtx.publicDefinition());