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