985b5e9855c8e03925af8daf12de3adc6d06a259
[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.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     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);
61     }
62
63     @Override
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
67             return;
68         }
69
70         final var augmentTargetCtx = target.resolve(ctx);
71         if (!isSupportedAugmentTarget(augmentTargetCtx)
72                 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
73             augmentNode.setUnsupported();
74             return;
75         }
76
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);
81         }
82
83         copyFromSourceToTarget(augmentNode, augmentTargetCtx);
84         augmentTargetCtx.addEffectiveSubstatement(augmentNode.replicaAsChildOf(augmentTargetCtx));
85     }
86
87     @Override
88     public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
89         /*
90          * Do not fail, if it is an uses-augment to an unknown node.
91          */
92         if (YangStmtMapping.USES == augmentNode.coerceParentContext().publicDefinition()) {
93             final SchemaNodeIdentifier augmentArg = augmentNode.getArgument();
94             final Optional<StmtContext<?, ?, ?>> targetNode = SchemaTreeNamespace.findNode(
95                 AbstractAugmentStatementSupport.getSearchRoot(augmentNode), augmentArg);
96             if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
97                 augmentNode.setUnsupported();
98                 LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
99                     augmentArg, augmentNode.sourceReference());
100                 return;
101             }
102         }
103
104         throw new InferenceException(augmentNode, "Augment target '%s' not found", augmentNode.argument());
105     }
106
107     @Override
108     public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
109         if (target.equals(unavail)) {
110             augmentNode.setUnsupported();
111         } else {
112             prerequisiteFailed(List.of(unavail));
113         }
114     }
115
116     private void copyFromSourceToTarget(final StmtContext<?, ?, ?> sourceCtx, final Mutable<?, ?, ?> targetCtx) {
117         final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
118             ? CopyType.ADDED_BY_USES_AUGMENTATION : CopyType.ADDED_BY_AUGMENTATION;
119         /*
120          * Since Yang 1.1, if an augmentation is made conditional with a
121          * "when" statement, it is allowed to add mandatory nodes.
122          */
123         final boolean skipCheckOfMandatoryNodes = statementSupport.allowsMandatory(sourceCtx);
124         final boolean unsupported = !sourceCtx.isSupportedByFeatures();
125
126         final var declared = sourceCtx.declaredSubstatements();
127         final var effective = sourceCtx.effectiveSubstatements();
128         final var buffer = new ArrayList<Mutable<?, ?, ?>>(declared.size() + effective.size());
129
130         for (var originalStmtCtx : declared) {
131             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes,
132                 unsupported || !originalStmtCtx.isSupportedByFeatures());
133         }
134         for (var originalStmtCtx : effective) {
135             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes, unsupported);
136         }
137
138         targetCtx.addEffectiveSubstatements(buffer);
139     }
140
141     private static void copyStatement(final StmtContext<?, ?, ?> original, final Mutable<?, ?, ?> target,
142             final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
143             final boolean skipCheckOfMandatoryNodes, final boolean unsupported) {
144         // We always copy statements, but if either the source statement or the augmentation which causes it are not
145         // supported to build we also mark the target as such.
146         if (!NOCOPY_DEF_SET.contains(original.publicDefinition())) {
147             validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
148
149             final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
150             if (unsupported) {
151                 copy.setUnsupported();
152             }
153             buffer.add(copy);
154         } else if (!unsupported && original.publicDefinition() == YangStmtMapping.TYPEDEF) {
155             // FIXME: what is this branch doing, really?
156             //        Typedef's policy would imply a replica, hence normal target.childCopyOf(original, typeOfCopy)
157             //        would suffice.
158             //        What does the !unsupported thing want to do?
159             buffer.add(original.replicaAsChildOf(target));
160         }
161     }
162
163     private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
164             final Mutable<?, ?, ?> targetCtx, final CopyType typeOfCopy, final boolean skipCheckOfMandatoryNodes) {
165         if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
166                 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
167             checkForMandatoryNodes(sourceCtx);
168         }
169
170         // Data definition statements must not collide on their namespace
171         if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
172             for (StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
173                 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
174                     InferenceException.throwIf(Objects.equals(sourceCtx.argument(), subStatement.argument()), sourceCtx,
175                         "An augment cannot add node named '%s' because this name is already used in target",
176                         sourceCtx.rawArgument());
177                 }
178             }
179         }
180     }
181
182     private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
183         if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
184             /*
185              * We need to iterate over both declared and effective sub-statements,
186              * because a mandatory node can be:
187              * a) declared in augment body
188              * b) added to augment body also via uses of a grouping and
189              * such sub-statements are stored in effective sub-statements collection.
190              */
191             sourceCtx.allSubstatementsStream().forEach(AugmentInferenceAction::checkForMandatoryNodes);
192         }
193
194         InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx), sourceCtx,
195             "An augment cannot add node '%s' because it is mandatory and in module different than target",
196             sourceCtx.rawArgument());
197     }
198
199     private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
200             Mutable<?, ?, ?> targetCtx) {
201         /*
202          * If the statement argument is not QName, it cannot be mandatory
203          * statement, therefore return false and skip mandatory nodes validation
204          */
205         final Object arg = sourceCtx.argument();
206         if (!(arg instanceof QName)) {
207             return false;
208         }
209         final QName sourceStmtQName = (QName) arg;
210
211         // RootStatementContext, for example
212         final Mutable<?, ?, ?> root = targetCtx.getRoot();
213         do {
214             final Object targetArg = targetCtx.argument();
215             verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s", targetArg);
216             final QName targetStmtQName = (QName) targetArg;
217             /*
218              * If target is from another module, return true and perform mandatory nodes validation
219              */
220             if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
221                 return true;
222             }
223
224             /*
225              * If target or one of the target's ancestors from the same namespace
226              * is a presence container
227              * or is non-mandatory choice
228              * or is non-mandatory list
229              * return false and skip mandatory nodes validation, because these nodes
230              * are not mandatory node containers according to RFC 6020 section 3.1.
231              */
232             if (StmtContextUtils.isPresenceContainer(targetCtx)
233                 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
234                 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
235                 return false;
236             }
237
238             // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
239             // conditional -- in which case we do not run further checks
240             if (targetCtx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
241                 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
242                 if (optPrevCopy.isPresent()) {
243                     final StmtContext<?, ?, ?> original = optPrevCopy.get();
244                     final Object origArg = original.getArgument();
245                     verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
246
247                     if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
248                         && AbstractAugmentStatementSupport.hasWhenSubstatement(getParentAugmentation(original))) {
249                         return false;
250                     }
251                 }
252             }
253         } while ((targetCtx = targetCtx.getParentContext()) != root);
254
255         /*
256          * All target node's parents belong to the same module as source node,
257          * therefore return false and skip mandatory nodes validation.
258          */
259         return false;
260     }
261
262     private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
263         StmtContext<?, ?, ?> parent = verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
264         while (parent.publicDefinition() != YangStmtMapping.AUGMENT) {
265             parent = verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
266         }
267         return parent;
268     }
269
270     private static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
271         /*
272          * :TODO Substatement must be allowed augment target type e.g.
273          * Container, etc... and must not be for example grouping, identity etc.
274          * It is problem in case when more than one substatements have the same
275          * QName, for example Grouping and Container are siblings and they have
276          * the same QName. We must find the Container and the Grouping must be
277          * ignored as disallowed augment target.
278          */
279         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
280             ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
281
282         // if no allowed target is returned we consider all targets allowed
283         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
284                 || allowedAugmentTargets.contains(substatementCtx.publicDefinition());
285     }
286 }