Augments should get disabled if target is unsupported
[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.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;
43
44 /**
45  * Inference action, split out of {@link AbstractAugmentStatementSupport} for clarity and potential specialization.
46  */
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);
51
52     private final Mutable<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> augmentNode;
53     private final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target;
54     private final AbstractAugmentStatementSupport statementSupport;
55
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);
62     }
63
64     @Override
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
68             return;
69         }
70
71         final StatementContextBase<?, ?, ?> augmentTargetCtx = (StatementContextBase<?, ?, ?>) target.resolve(ctx);
72         if (!isSupportedAugmentTarget(augmentTargetCtx)
73                 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
74             augmentNode.setIsSupportedToBuildEffective(false);
75             return;
76         }
77
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);
82         }
83
84         copyFromSourceToTarget((StatementContextBase<?, ?, ?>) augmentNode, augmentTargetCtx);
85         augmentTargetCtx.addEffectiveSubstatement(augmentNode.replicaAsChildOf(augmentTargetCtx));
86     }
87
88     @Override
89     public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
90         /*
91          * Do not fail, if it is an uses-augment to an unknown node.
92          */
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());
101                 return;
102             }
103         }
104
105         throw new InferenceException(augmentNode, "Augment target '%s' not found", augmentNode.argument());
106     }
107
108     @Override
109     public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
110         if (target.equals(unavail)) {
111             augmentNode.setIsSupportedToBuildEffective(false);
112         } else {
113             prerequisiteFailed(List.of(unavail));
114         }
115     }
116
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;
121         /*
122          * Since Yang 1.1, if an augmentation is made conditional with a
123          * "when" statement, it is allowed to add mandatory nodes.
124          */
125         final boolean skipCheckOfMandatoryNodes = statementSupport.allowsMandatory(sourceCtx);
126         final boolean unsupported = !sourceCtx.isSupportedByFeatures();
127
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());
131
132         for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
133             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes,
134                 unsupported || !originalStmtCtx.isSupportedByFeatures());
135         }
136         for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
137             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes, unsupported);
138         }
139
140         targetCtx.addEffectiveSubstatements(buffer);
141     }
142
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);
150
151             final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
152             if (unsupported) {
153                 copy.setIsSupportedToBuildEffective(false);
154             }
155             buffer.add(copy);
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)
159             //        would suffice.
160             //        What does the !unsupported thing want to do?
161             buffer.add(original.replicaAsChildOf(target));
162         }
163     }
164
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);
171         }
172
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());
180                 }
181             }
182         }
183     }
184
185     private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
186         if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
187             /*
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.
193              */
194             sourceCtx.allSubstatementsStream().forEach(AugmentInferenceAction::checkForMandatoryNodes);
195         }
196
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());
200     }
201
202     private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
203             Mutable<?, ?, ?> targetCtx) {
204         /*
205          * If the statement argument is not QName, it cannot be mandatory
206          * statement, therefore return false and skip mandatory nodes validation
207          */
208         final Object arg = sourceCtx.argument();
209         if (!(arg instanceof QName)) {
210             return false;
211         }
212         final QName sourceStmtQName = (QName) arg;
213
214         // RootStatementContext, for example
215         final Mutable<?, ?, ?> root = targetCtx.getRoot();
216         do {
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;
220             /*
221              * If target is from another module, return true and perform mandatory nodes validation
222              */
223             if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
224                 return true;
225             }
226
227             /*
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.
234              */
235             if (StmtContextUtils.isPresenceContainer(targetCtx)
236                 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
237                 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
238                 return false;
239             }
240
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);
249
250                     if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
251                         && AbstractAugmentStatementSupport.hasWhenSubstatement(getParentAugmentation(original))) {
252                         return false;
253                     }
254                 }
255             }
256         } while ((targetCtx = targetCtx.getParentContext()) != root);
257
258         /*
259          * All target node's parents belong to the same module as source node,
260          * therefore return false and skip mandatory nodes validation.
261          */
262         return false;
263     }
264
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);
269         }
270         return parent;
271     }
272
273     private static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
274         /*
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.
281          */
282         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
283             ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
284
285         // if no allowed target is returned we consider all targets allowed
286         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
287                 || allowedAugmentTargets.contains(substatementCtx.publicDefinition());
288     }
289 }