Fix augment/deviate mechanics
[yangtools.git] / parser / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / augment / AugmentInferenceAction.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.rfc7950.stmt.augment;
9
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;
13
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;
42
43 /**
44  * Inference action, split out of {@link AbstractAugmentStatementSupport} for clarity and potential specialization.
45  */
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);
50
51     private final Mutable<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> augmentNode;
52     private final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target;
53     private final AbstractAugmentStatementSupport statementSupport;
54
55     private boolean targetUnavailable;
56
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);
63     }
64
65     @Override
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();
70             return;
71         }
72
73         final var augmentTargetCtx = target.resolve(ctx);
74         if (!isSupportedAugmentTarget(augmentTargetCtx)
75                 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
76             augmentNode.setUnsupported();
77             return;
78         }
79
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);
84         }
85
86         copyFromSourceToTarget(augmentNode, augmentTargetCtx);
87         augmentTargetCtx.addEffectiveSubstatement(augmentNode.replicaAsChildOf(augmentTargetCtx));
88     }
89
90     @Override
91     public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
92         /*
93          * Do not fail, if it is an uses-augment to an unknown node.
94          */
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
98                 return;
99             }
100
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());
108                 return;
109             }
110         }
111
112         throw new InferenceException(augmentNode, "Augment target '%s' not found", augmentNode.argument());
113     }
114
115     @Override
116     public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
117         if (target.equals(unavail)) {
118             targetUnavailable = true;
119         } else {
120             prerequisiteFailed(List.of(unavail));
121         }
122     }
123
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;
127         /*
128          * Since Yang 1.1, if an augmentation is made conditional with a
129          * "when" statement, it is allowed to add mandatory nodes.
130          */
131         final boolean skipCheckOfMandatoryNodes = statementSupport.allowsMandatory(sourceCtx);
132         final boolean unsupported = !sourceCtx.isSupportedByFeatures();
133
134         final var declared = sourceCtx.declaredSubstatements();
135         final var effective = sourceCtx.effectiveSubstatements();
136         final var buffer = new ArrayList<Mutable<?, ?, ?>>(declared.size() + effective.size());
137
138         for (var originalStmtCtx : declared) {
139             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes,
140                 unsupported || !originalStmtCtx.isSupportedByFeatures());
141         }
142         for (var originalStmtCtx : effective) {
143             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes, unsupported);
144         }
145
146         targetCtx.addEffectiveSubstatements(buffer);
147     }
148
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);
156
157             final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
158             if (unsupported) {
159                 copy.setUnsupported();
160             }
161             buffer.add(copy);
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)
165             //        would suffice.
166             //        What does the !unsupported thing want to do?
167             buffer.add(original.replicaAsChildOf(target));
168         }
169     }
170
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);
176         }
177
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());
185                 }
186             }
187         }
188     }
189
190     private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
191         if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
192             /*
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.
198              */
199             sourceCtx.allSubstatementsStream().forEach(AugmentInferenceAction::checkForMandatoryNodes);
200         }
201
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());
205     }
206
207     private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
208             Mutable<?, ?, ?> targetCtx) {
209         /*
210          * If the statement argument is not QName, it cannot be mandatory
211          * statement, therefore return false and skip mandatory nodes validation
212          */
213         final Object arg = sourceCtx.argument();
214         if (!(arg instanceof QName sourceStmtQName)) {
215             return false;
216         }
217         // RootStatementContext, for example
218         final Mutable<?, ?, ?> root = targetCtx.getRoot();
219         do {
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;
223             /*
224              * If target is from another module, return true and perform mandatory nodes validation
225              */
226             if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
227                 return true;
228             }
229
230             /*
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.
237              */
238             if (StmtContextUtils.isPresenceContainer(targetCtx)
239                 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
240                 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
241                 return false;
242             }
243
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);
252
253                     if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
254                         && AbstractAugmentStatementSupport.hasWhenSubstatement(getParentAugmentation(original))) {
255                         return false;
256                     }
257                 }
258             }
259         } while ((targetCtx = targetCtx.getParentContext()) != root);
260
261         /*
262          * All target node's parents belong to the same module as source node,
263          * therefore return false and skip mandatory nodes validation.
264          */
265         return false;
266     }
267
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);
272         }
273         return parent;
274     }
275
276     private static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
277         /*
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.
284          */
285         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
286             ValidationBundles.NAMESPACE, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
287
288         // if no allowed target is returned we consider all targets allowed
289         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
290                 || allowedAugmentTargets.contains(substatementCtx.publicDefinition());
291     }
292 }