f00172ffbc0b550aca1114024307426e8c9a92ef
[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.Empty;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
22 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
27 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
28 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
37 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
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         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, Empty.getInstance(), augmentTargetCtx);
77         }
78
79         // FIXME: this is a workaround for models which augment a node which is added via an extension
80         //        which we do not handle. This needs to be reworked in terms of unknown schema nodes.
81         try {
82             copyFromSourceToTarget((StatementContextBase<?, ?, ?>) augmentNode, augmentTargetCtx);
83             augmentTargetCtx.addEffectiveSubstatement(augmentNode.replicaAsChildOf(augmentTargetCtx));
84         } catch (final SourceException e) {
85             LOG.warn("Failed to add augmentation {} defined at {}", augmentTargetCtx.sourceReference(),
86                 augmentNode.sourceReference(), e);
87         }
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             final SchemaNodeIdentifier augmentArg = augmentNode.getArgument();
97             final Optional<StmtContext<?, ?, ?>> targetNode = SchemaTreeNamespace.findNode(
98                 AbstractAugmentStatementSupport.getSearchRoot(augmentNode), augmentArg);
99             if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
100                 augmentNode.setIsSupportedToBuildEffective(false);
101                 LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
102                     augmentArg, augmentNode.sourceReference());
103                 return;
104             }
105         }
106
107         throw new InferenceException(augmentNode, "Augment target '%s' not found", 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 (!NOCOPY_DEF_SET.contains(original.publicDefinition())) {
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()), sourceCtx,
167                         "An augment cannot add node named '%s' because this name is already used in target",
168                         sourceCtx.rawArgument());
169                 }
170             }
171         }
172     }
173
174     private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
175         if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
176             /*
177              * We need to iterate over both declared and effective sub-statements,
178              * because a mandatory node can be:
179              * a) declared in augment body
180              * b) added to augment body also via uses of a grouping and
181              * such sub-statements are stored in effective sub-statements collection.
182              */
183             sourceCtx.allSubstatementsStream().forEach(AugmentInferenceAction::checkForMandatoryNodes);
184         }
185
186         InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx), sourceCtx,
187             "An augment cannot add node '%s' because it is mandatory and in module different than target",
188             sourceCtx.rawArgument());
189     }
190
191     private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
192             Mutable<?, ?, ?> targetCtx) {
193         /*
194          * If the statement argument is not QName, it cannot be mandatory
195          * statement, therefore return false and skip mandatory nodes validation
196          */
197         final Object arg = sourceCtx.argument();
198         if (!(arg instanceof QName)) {
199             return false;
200         }
201         final QName sourceStmtQName = (QName) arg;
202
203         // RootStatementContext, for example
204         final Mutable<?, ?, ?> root = targetCtx.getRoot();
205         do {
206             final Object targetArg = targetCtx.argument();
207             verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s", targetArg);
208             final QName targetStmtQName = (QName) targetArg;
209             /*
210              * If target is from another module, return true and perform mandatory nodes validation
211              */
212             if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
213                 return true;
214             }
215
216             /*
217              * If target or one of the target's ancestors from the same namespace
218              * is a presence container
219              * or is non-mandatory choice
220              * or is non-mandatory list
221              * return false and skip mandatory nodes validation, because these nodes
222              * are not mandatory node containers according to RFC 6020 section 3.1.
223              */
224             if (StmtContextUtils.isPresenceContainer(targetCtx)
225                 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
226                 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
227                 return false;
228             }
229
230             // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
231             // conditional -- in which case we do not run further checks
232             if (targetCtx.history().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
233                 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
234                 if (optPrevCopy.isPresent()) {
235                     final StmtContext<?, ?, ?> original = optPrevCopy.get();
236                     final Object origArg = original.getArgument();
237                     verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
238
239                     if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
240                         && AbstractAugmentStatementSupport.hasWhenSubstatement(getParentAugmentation(original))) {
241                         return false;
242                     }
243                 }
244             }
245         } while ((targetCtx = targetCtx.getParentContext()) != root);
246
247         /*
248          * All target node's parents belong to the same module as source node,
249          * therefore return false and skip mandatory nodes validation.
250          */
251         return false;
252     }
253
254     private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
255         StmtContext<?, ?, ?> parent = verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
256         while (parent.publicDefinition() != YangStmtMapping.AUGMENT) {
257             parent = verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
258         }
259         return parent;
260     }
261
262     private static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
263         /*
264          * :TODO Substatement must be allowed augment target type e.g.
265          * Container, etc... and must not be for example grouping, identity etc.
266          * It is problem in case when more than one substatements have the same
267          * QName, for example Grouping and Container are siblings and they have
268          * the same QName. We must find the Container and the Grouping must be
269          * ignored as disallowed augment target.
270          */
271         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
272             ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
273
274         // if no allowed target is returned we consider all targets allowed
275         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
276                 || allowedAugmentTargets.contains(substatementCtx.publicDefinition());
277     }
278 }