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