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