Revert "Check for nested augmentations"
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / augment / AbstractAugmentStatementSupport.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, 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 com.google.common.base.Verify;
11 import com.google.common.collect.ImmutableSet;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.Objects;
15 import java.util.Optional;
16 import java.util.regex.Pattern;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.common.YangVersion;
19 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
20 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
21 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
22 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
24 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.WhenStatement;
26 import org.opendaylight.yangtools.yang.parser.rfc7950.namespace.ChildSchemaNodeNamespace;
27 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.ArgumentUtils;
28 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
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;
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.ModelProcessingPhase;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
39 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
41 import org.opendaylight.yangtools.yang.parser.spi.source.StmtOrderingNamespace;
42 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
44 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 abstract class AbstractAugmentStatementSupport extends AbstractStatementSupport<SchemaNodeIdentifier, AugmentStatement,
49         EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> {
50     private static final Logger LOG = LoggerFactory.getLogger(AbstractAugmentStatementSupport.class);
51     private static final Pattern PATH_REL_PATTERN1 = Pattern.compile("\\.\\.?\\s*/(.+)");
52     private static final Pattern PATH_REL_PATTERN2 = Pattern.compile("//.*");
53
54     AbstractAugmentStatementSupport() {
55         super(YangStmtMapping.AUGMENT);
56     }
57
58     @Override
59     public final SchemaNodeIdentifier parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
60         SourceException.throwIf(PATH_REL_PATTERN1.matcher(value).matches()
61             || PATH_REL_PATTERN2.matcher(value).matches(), ctx.getStatementSourceReference(),
62             "Augment argument \'%s\' is not valid, it can be only absolute path; or descendant if used in uses",
63             value);
64
65         return ArgumentUtils.nodeIdentifierFromPath(ctx, value);
66     }
67
68     @Override
69     public final AugmentStatement createDeclared(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx) {
70         return new AugmentStatementImpl(ctx);
71     }
72
73     @Override
74     public final EffectiveStatement<SchemaNodeIdentifier, AugmentStatement> createEffective(
75             final StmtContext<SchemaNodeIdentifier, AugmentStatement,
76             EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> ctx) {
77         return new AugmentEffectiveStatementImpl(ctx);
78     }
79
80     @Override
81     public final void onFullDefinitionDeclared(final Mutable<SchemaNodeIdentifier, AugmentStatement,
82             EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> augmentNode) {
83         if (!augmentNode.isSupportedByFeatures()) {
84             return;
85         }
86
87         super.onFullDefinitionDeclared(augmentNode);
88
89         if (StmtContextUtils.isInExtensionBody(augmentNode)) {
90             return;
91         }
92
93         final ModelActionBuilder augmentAction = augmentNode.newInferenceAction(
94             ModelProcessingPhase.EFFECTIVE_MODEL);
95         final Prerequisite<StmtContext<SchemaNodeIdentifier, AugmentStatement,
96             EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>>> sourceCtxPrereq =
97                 augmentAction.requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
98         final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target =
99                 augmentAction.mutatesEffectiveCtxPath(getSearchRoot(augmentNode),
100                     ChildSchemaNodeNamespace.class, augmentNode.coerceStatementArgument().getPathFromRoot());
101
102         augmentAction.apply(new InferenceAction() {
103             @Override
104             public void apply(final InferenceContext ctx) {
105                 final StatementContextBase<?, ?, ?> augmentTargetCtx =
106                         (StatementContextBase<?, ?, ?>) target.resolve(ctx);
107                 if (!isSupportedAugmentTarget(augmentTargetCtx)
108                         || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
109                     augmentNode.setIsSupportedToBuildEffective(false);
110                     return;
111                 }
112                 /**
113                  * Marks case short hand in augment
114                  */
115                 if (augmentTargetCtx.getPublicDefinition() == YangStmtMapping.CHOICE) {
116                     augmentNode.addToNs(AugmentToChoiceNamespace.class, augmentNode, Boolean.TRUE);
117                 }
118
119                 // FIXME: this is a workaround for models which augment a node which is added via an extension
120                 //        which we do not handle. This needs to be reworked in terms of unknown schema nodes.
121                 final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
122                 try {
123                     copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
124                     augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
125                     updateAugmentOrder(augmentSourceCtx);
126                 } catch (final SourceException e) {
127                     LOG.warn("Failed to add augmentation {} defined at {}",
128                         augmentTargetCtx.getStatementSourceReference(),
129                             augmentSourceCtx.getStatementSourceReference(), e);
130                 }
131             }
132
133             private void updateAugmentOrder(final StatementContextBase<?, ?, ?> augmentSourceCtx) {
134                 Integer currentOrder = augmentSourceCtx.getFromNamespace(StmtOrderingNamespace.class,
135                     YangStmtMapping.AUGMENT);
136                 if (currentOrder == null) {
137                     currentOrder = 1;
138                 } else {
139                     currentOrder++;
140                 }
141
142                 augmentSourceCtx.addToNs(StmtOrderingNamespace.class, YangStmtMapping.AUGMENT, currentOrder);
143             }
144
145             @Override
146             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
147                 /*
148                  * Do not fail, if it is an uses-augment to an unknown node.
149                  */
150                 if (YangStmtMapping.USES == augmentNode.coerceParentContext().getPublicDefinition()) {
151                     final SchemaNodeIdentifier augmentArg = augmentNode.coerceStatementArgument();
152                     final Optional<StmtContext<?, ?, ?>> targetNode = ChildSchemaNodeNamespace.findNode(
153                         getSearchRoot(augmentNode), augmentArg);
154                     if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
155                         augmentNode.setIsSupportedToBuildEffective(false);
156                         LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
157                             augmentArg, augmentNode.getStatementSourceReference());
158                         return;
159                     }
160                 }
161
162                 throw new InferenceException(augmentNode.getStatementSourceReference(),
163                         "Augment target '%s' not found", augmentNode.getStatementArgument());
164             }
165         });
166     }
167
168     private static StmtContext<?, ?, ?> getSearchRoot(final StmtContext<?, ?, ?> augmentContext) {
169         // Augment is in uses - we need to augment instantiated nodes in parent.
170         final StmtContext<?, ?, ?> parent = augmentContext.coerceParentContext();
171         if (YangStmtMapping.USES == parent.getPublicDefinition()) {
172             return parent.getParentContext();
173         }
174         return parent;
175     }
176
177     static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
178             final StatementContextBase<?, ?, ?> targetCtx) {
179         final CopyType typeOfCopy = UsesStatement.class.equals(sourceCtx.coerceParentContext().getPublicDefinition()
180                 .getDeclaredRepresentationClass()) ? CopyType.ADDED_BY_USES_AUGMENTATION
181                 : CopyType.ADDED_BY_AUGMENTATION;
182         /*
183          * Since Yang 1.1, if an augmentation is made conditional with a
184          * "when" statement, it is allowed to add mandatory nodes.
185          */
186         final boolean skipCheckOfMandatoryNodes = YangVersion.VERSION_1_1.equals(sourceCtx.getRootVersion())
187                 && isConditionalAugmentStmt(sourceCtx);
188
189         final Collection<? extends Mutable<?, ?, ?>> declared = sourceCtx.mutableDeclaredSubstatements();
190         final Collection<? extends Mutable<?, ?, ?>> effective = sourceCtx.mutableEffectiveSubstatements();
191         final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
192
193         for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
194             if (originalStmtCtx.isSupportedByFeatures()) {
195                 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
196             }
197         }
198         for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
199             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
200         }
201
202         targetCtx.addEffectiveSubstatements(buffer);
203     }
204
205     /**
206      * Checks whether supplied statement context is conditional augment
207      * statement.
208      *
209      * @param ctx
210      *            statement context to be checked
211      *
212      * @return true if supplied statement context is conditional augment
213      *         statement, otherwise false
214      */
215     private static boolean isConditionalAugmentStmt(final StmtContext<?, ?, ?> ctx) {
216         return ctx.getPublicDefinition() == YangStmtMapping.AUGMENT
217                 && StmtContextUtils.findFirstSubstatement(ctx, WhenStatement.class) != null;
218     }
219
220     private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
221             final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
222             final boolean skipCheckOfMandatoryNodes) {
223         if (needToCopyByAugment(original)) {
224             validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
225
226             buffer.add(target.childCopyOf(original, typeOfCopy));
227         } else if (isReusedByAugment(original)) {
228             buffer.add(original);
229         }
230     }
231
232     private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
233             final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
234             final boolean skipCheckOfMandatoryNodes) {
235
236         if (WhenStatement.class.equals(sourceCtx.getPublicDefinition().getDeclaredRepresentationClass())) {
237             return;
238         }
239
240         if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
241                 && reguiredCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
242             checkForMandatoryNodes(sourceCtx);
243         }
244
245         // Data definition statements must not collide on their namespace
246         if (DataDefinitionStatement.class.isAssignableFrom(
247             sourceCtx.getPublicDefinition().getDeclaredRepresentationClass())) {
248             for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
249                 if (DataDefinitionStatement.class.isAssignableFrom(
250                     subStatement.getPublicDefinition().getDeclaredRepresentationClass())) {
251
252                     InferenceException.throwIf(
253                         Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument()),
254                         sourceCtx.getStatementSourceReference(),
255                         "An augment cannot add node named '%s' because this name is already used in target",
256                         sourceCtx.rawStatementArgument());
257                 }
258             }
259         }
260     }
261
262     private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
263         if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
264             /*
265              * We need to iterate over both declared and effective sub-statements,
266              * because a mandatory node can be:
267              * a) declared in augment body
268              * b) added to augment body also via uses of a grouping and
269              * such sub-statements are stored in effective sub-statements collection.
270              */
271             sourceCtx.allSubstatementsStream().forEach(AbstractAugmentStatementSupport::checkForMandatoryNodes);
272         }
273
274         InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
275                 sourceCtx.getStatementSourceReference(),
276                 "An augment cannot add node '%s' because it is mandatory and in module different than target",
277                 sourceCtx.rawStatementArgument());
278     }
279
280     private static boolean reguiredCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
281             Mutable<?, ?, ?> targetCtx) {
282         /*
283          * If the statement argument is not QName, it cannot be mandatory
284          * statement, therefore return false and skip mandatory nodes validation
285          */
286         if (!(sourceCtx.getStatementArgument() instanceof QName)) {
287             return false;
288         }
289         final QName sourceStmtQName = (QName) sourceCtx.getStatementArgument();
290
291         // RootStatementContext, for example
292         final Mutable<?, ?, ?> root = targetCtx.getRoot();
293         do {
294             Verify.verify(targetCtx.getStatementArgument() instanceof QName,
295                     "Argument of augment target statement must be QName.");
296             final QName targetStmtQName = (QName) targetCtx.getStatementArgument();
297             /*
298              * If target is from another module, return true and perform mandatory nodes validation
299              */
300             if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
301                 return true;
302             }
303
304             /*
305              * If target or one of the target's ancestors from the same namespace
306              * is a presence container
307              * or is non-mandatory choice
308              * or is non-mandatory list
309              * return false and skip mandatory nodes validation, because these nodes
310              * are not mandatory node containers according to RFC 6020 section 3.1.
311              */
312             if (StmtContextUtils.isPresenceContainer(targetCtx)
313                     || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
314                     || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
315                 return false;
316             }
317         } while ((targetCtx = targetCtx.getParentContext()) != root);
318
319         /*
320          * All target node's parents belong to the same module as source node,
321          * therefore return false and skip mandatory nodes validation.
322          */
323         return false;
324     }
325
326     private static final ImmutableSet<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES,
327         YangStmtMapping.WHEN, YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
328
329     private static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
330         return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
331     }
332
333     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
334
335     private static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
336         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
337     }
338
339     static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
340         /*
341          * :TODO Substatement must be allowed augment target type e.g.
342          * Container, etc... and must not be for example grouping, identity etc.
343          * It is problem in case when more than one substatements have the same
344          * QName, for example Grouping and Container are siblings and they have
345          * the same QName. We must find the Container and the Grouping must be
346          * ignored as disallowed augment target.
347          */
348         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
349             ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
350
351         // if no allowed target is returned we consider all targets allowed
352         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
353                 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
354     }
355 }