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