7aa513a0204e89daf13049c4527fb6bcfce563d0
[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.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.collect.ImmutableList.Builder;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.collect.Iterables;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.List;
18 import java.util.Objects;
19 import java.util.Set;
20 import java.util.regex.Pattern;
21 import javax.annotation.Nonnull;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
24 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
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.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.SubstatementValidator;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractDeclaredStatement;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
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.RootStatementContext;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
48 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.AugmentEffectiveStatementImpl;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 public class AugmentStatementImpl extends AbstractDeclaredStatement<SchemaNodeIdentifier> implements AugmentStatement {
53     private static final Logger LOG = LoggerFactory.getLogger(AugmentStatementImpl.class);
54     private static final Pattern PATH_REL_PATTERN1 = Pattern.compile("\\.\\.?\\s*/(.+)");
55     private static final Pattern PATH_REL_PATTERN2 = Pattern.compile("//.*");
56     private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator
57             .builder(Rfc6020Mapping.AUGMENT)
58             .addAny(Rfc6020Mapping.ANYXML)
59             .addAny(Rfc6020Mapping.CASE)
60             .addAny(Rfc6020Mapping.CHOICE)
61             .addAny(Rfc6020Mapping.CONTAINER)
62             .addOptional(Rfc6020Mapping.DESCRIPTION)
63             .addAny(Rfc6020Mapping.IF_FEATURE)
64             .addAny(Rfc6020Mapping.LEAF)
65             .addAny(Rfc6020Mapping.LEAF_LIST)
66             .addAny(Rfc6020Mapping.LIST)
67             .addOptional(Rfc6020Mapping.REFERENCE)
68             .addOptional(Rfc6020Mapping.STATUS)
69             .addAny(Rfc6020Mapping.USES)
70             .addOptional(Rfc6020Mapping.WHEN)
71             .build();
72
73     protected AugmentStatementImpl(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> context) {
74         super(context);
75     }
76
77     public static class Definition extends
78             AbstractStatementSupport<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> {
79
80         public Definition() {
81             super(Rfc6020Mapping.AUGMENT);
82         }
83
84         @Override
85         public SchemaNodeIdentifier parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
86             Preconditions.checkArgument(!PATH_REL_PATTERN1.matcher(value).matches()
87                 && !PATH_REL_PATTERN2.matcher(value).matches(),
88                 "An argument for augment can be only absolute path; or descendant if used in uses");
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 StmtContext.Mutable<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> augmentNode) {
108             if (!StmtContextUtils.areFeaturesSupported(augmentNode)) {
109                 return;
110             }
111
112             SUBSTATEMENT_VALIDATOR.validate(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() {
128                     final StatementContextBase<?, ?, ?> augmentTargetCtx = (StatementContextBase<?, ?, ?>) target.get();
129                     if (!isSupportedAugmentTarget(augmentTargetCtx)
130                             || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
131                         augmentNode.setIsSupportedToBuildEffective(false);
132                         return;
133                     }
134                     /**
135                      * Marks case short hand in augment
136                      */
137                     if (augmentTargetCtx.getPublicDefinition() == Rfc6020Mapping.CHOICE) {
138                         augmentNode.addToNs(AugmentToChoiceNamespace.class, augmentNode, Boolean.TRUE);
139                     }
140
141                     // FIXME: this is a workaround for models which augment a node which is added via an extension
142                     //        which we do not handle. This needs to be reworked in terms of unknown schema nodes.
143                     final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
144                     try {
145                         copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
146                         augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
147                         updateAugmentOrder(augmentSourceCtx);
148                     } catch (final SourceException e) {
149                         LOG.debug("Failed to add augmentation {} defined at {}",
150                             augmentTargetCtx.getStatementSourceReference(),
151                                 augmentSourceCtx.getStatementSourceReference(), e);
152                     }
153                 }
154
155                 private void updateAugmentOrder(final StatementContextBase<?, ?, ?> augmentSourceCtx) {
156                     Integer currentOrder = augmentSourceCtx.getFromNamespace(StmtOrderingNamespace.class,
157                         Rfc6020Mapping.AUGMENT);
158                     if (currentOrder == null) {
159                         currentOrder = 1;
160                     } else {
161                         currentOrder++;
162                     }
163
164                     augmentSourceCtx.setOrder(currentOrder);
165                     augmentSourceCtx.addToNs(StmtOrderingNamespace.class, Rfc6020Mapping.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 (Rfc6020Mapping.USES == augmentNode.getParentContext().getPublicDefinition()) {
174                         final StatementContextBase<?, ?, ?> targetNode = Utils.findNode(getSearchRoot(augmentNode),
175                                 augmentNode.getStatementArgument());
176                         if (Utils.isUnknownNode(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 (Rfc6020Mapping.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             final Collection<StatementContextBase<?, ?, ?>> declared = sourceCtx.declaredSubstatements();
207             final Collection<StatementContextBase<?, ?, ?>> effective = sourceCtx.effectiveSubstatements();
208             final Collection<StatementContextBase<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
209
210             for (final StatementContextBase<?, ?, ?> originalStmtCtx : declared) {
211                 if (StmtContextUtils.areFeaturesSupported(originalStmtCtx)) {
212                     copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer);
213                 }
214             }
215             for (final StatementContextBase<?, ?, ?> originalStmtCtx : effective) {
216                 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer);
217             }
218
219             targetCtx.addEffectiveSubstatements(buffer);
220         }
221
222         private static void copyStatement(final StatementContextBase<?, ?, ?> original,
223                 final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
224                 final Collection<StatementContextBase<?, ?, ?>> buffer) {
225             if (needToCopyByAugment(original)) {
226                 validateNodeCanBeCopiedByAugment(original, target, typeOfCopy);
227
228                 final StatementContextBase<?, ?, ?> copy = original.createCopy(target, typeOfCopy);
229                 buffer.add(copy);
230             } else if (isReusedByAugment(original)) {
231                 buffer.add(original);
232             }
233         }
234
235         private static void validateNodeCanBeCopiedByAugment(final StatementContextBase<?, ?, ?> sourceCtx,
236                 final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy) {
237
238             if (WhenStatement.class.equals(sourceCtx.getPublicDefinition().getDeclaredRepresentationClass())) {
239                 return;
240             }
241
242             if (typeOfCopy == CopyType.ADDED_BY_AUGMENTATION && reguiredCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
243                 checkForMandatoryNodes(sourceCtx);
244             }
245
246             final List<StatementContextBase<?, ?, ?>> targetSubStatements = new Builder<StatementContextBase<?, ?, ?>>()
247                     .addAll(targetCtx.declaredSubstatements()).addAll(targetCtx.effectiveSubstatements()).build();
248
249             for (final StatementContextBase<?, ?, ?> subStatement : targetSubStatements) {
250
251                 final boolean sourceIsDataNode = DataDefinitionStatement.class.isAssignableFrom(sourceCtx
252                         .getPublicDefinition().getDeclaredRepresentationClass());
253                 final boolean targetIsDataNode = DataDefinitionStatement.class.isAssignableFrom(subStatement
254                         .getPublicDefinition().getDeclaredRepresentationClass());
255                 final boolean qNamesEqual = sourceIsDataNode && targetIsDataNode
256                         && Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument());
257
258                 InferenceException.throwIf(qNamesEqual, sourceCtx.getStatementSourceReference(),
259                         "An augment cannot add node named '%s' because this name is already used in target",
260                         sourceCtx.rawStatementArgument());
261             }
262         }
263
264         private static void checkForMandatoryNodes(final StatementContextBase<?, ?, ?> 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                 for (final StatementContextBase<?, ?, ?> sourceSubStatement : Iterables.concat(
274                         sourceCtx.declaredSubstatements(), sourceCtx.declaredSubstatements())) {
275                     checkForMandatoryNodes(sourceSubStatement);
276                 }
277             }
278
279             InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
280                     sourceCtx.getStatementSourceReference(),
281                     "An augment cannot add node '%s' because it is mandatory and in module different than target",
282                     sourceCtx.rawStatementArgument());
283         }
284
285         private static boolean reguiredCheckOfMandatoryNodes(final StatementContextBase<?, ?, ?> sourceCtx,
286                 StatementContextBase<?, ?, ?> targetCtx) {
287             /*
288              * If the statement argument is not QName, it cannot be mandatory
289              * statement, therefore return false and skip mandatory nodes validation
290              */
291             if (!(sourceCtx.getStatementArgument() instanceof QName)) {
292                 return false;
293             }
294             final QName sourceStmtQName = (QName) sourceCtx.getStatementArgument();
295
296             final RootStatementContext<?, ?, ?> root = targetCtx.getRoot();
297             do {
298                 Verify.verify(targetCtx.getStatementArgument() instanceof QName,
299                         "Argument of augment target statement must be QName.");
300                 final QName targetStmtQName = (QName) targetCtx.getStatementArgument();
301                 /*
302                  * If target is from another module, return true and perform
303                  * mandatory nodes validation
304                  */
305                 if (!Utils.belongsToTheSameModule(targetStmtQName, sourceStmtQName)) {
306                     return true;
307                 }
308
309                 /*
310                  * If target or one of its parent is a presence container from
311                  * the same module, return false and skip mandatory nodes
312                  * validation
313                  */
314                 if (StmtContextUtils.isPresenceContainer(targetCtx)) {
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 Set<Rfc6020Mapping> NOCOPY_DEF_SET = ImmutableSet.of(Rfc6020Mapping.USES, Rfc6020Mapping.WHEN,
327                 Rfc6020Mapping.DESCRIPTION, Rfc6020Mapping.REFERENCE, Rfc6020Mapping.STATUS);
328
329         public static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
330             return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
331         }
332
333         private static final Set<Rfc6020Mapping> REUSED_DEF_SET = ImmutableSet.of(Rfc6020Mapping.TYPEDEF);
334
335         public static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
336             return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
337         }
338
339         static boolean isSupportedAugmentTarget(final StatementContextBase<?, ?, ?> substatementCtx) {
340
341             /*
342              * :TODO Substatement must be allowed augment target type e.g.
343              * Container, etc... and must not be for example grouping, identity etc.
344              * It is problem in case when more than one substatements have the same
345              * QName, for example Grouping and Container are siblings and they have
346              * the same QName. We must find the Container and the Grouping must be
347              * ignored as disallowed augment target.
348              */
349
350             final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(ValidationBundlesNamespace.class,
351                     ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
352
353             // if no allowed target is returned we consider all targets allowed
354             return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
355                     || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
356         }
357
358     }
359
360     @Nonnull
361     @Override
362     public SchemaNodeIdentifier getTargetNode() {
363         return argument();
364     }
365
366     @Override
367     public Collection<? extends DataDefinitionStatement> getDataDefinitions() {
368         return allDeclared(DataDefinitionStatement.class);
369     }
370 }