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