Do not instantiate needless objects in augment
[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 java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.Objects;
15 import java.util.Set;
16 import java.util.regex.Pattern;
17 import javax.annotation.Nonnull;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.common.YangVersion;
20 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
21 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
22 import org.opendaylight.yangtools.yang.model.api.stmt.ActionStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.NotificationStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
27 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.WhenStatement;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractDeclaredStatement;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
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.meta.SubstatementValidator;
40 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
42 import org.opendaylight.yangtools.yang.parser.spi.source.StmtOrderingNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
45 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
46 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.AugmentEffectiveStatementImpl;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 public class AugmentStatementImpl extends AbstractDeclaredStatement<SchemaNodeIdentifier> implements AugmentStatement {
51     private static final Logger LOG = LoggerFactory.getLogger(AugmentStatementImpl.class);
52     private static final Pattern PATH_REL_PATTERN1 = Pattern.compile("\\.\\.?\\s*/(.+)");
53     private static final Pattern PATH_REL_PATTERN2 = Pattern.compile("//.*");
54     private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator
55             .builder(YangStmtMapping.AUGMENT)
56             .addAny(YangStmtMapping.ANYXML)
57             .addAny(YangStmtMapping.CASE)
58             .addAny(YangStmtMapping.CHOICE)
59             .addAny(YangStmtMapping.CONTAINER)
60             .addOptional(YangStmtMapping.DESCRIPTION)
61             .addAny(YangStmtMapping.IF_FEATURE)
62             .addAny(YangStmtMapping.LEAF)
63             .addAny(YangStmtMapping.LEAF_LIST)
64             .addAny(YangStmtMapping.LIST)
65             .addOptional(YangStmtMapping.REFERENCE)
66             .addOptional(YangStmtMapping.STATUS)
67             .addAny(YangStmtMapping.USES)
68             .addOptional(YangStmtMapping.WHEN)
69             .build();
70
71     protected AugmentStatementImpl(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> context) {
72         super(context);
73     }
74
75     public static class Definition extends
76             AbstractStatementSupport<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> {
77
78         public Definition() {
79             super(YangStmtMapping.AUGMENT);
80         }
81
82         @Override
83         public SchemaNodeIdentifier parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
84             SourceException.throwIf(PATH_REL_PATTERN1.matcher(value).matches()
85                 || PATH_REL_PATTERN2.matcher(value).matches(), ctx.getStatementSourceReference(),
86                 "Augment argument \'%s\' is not valid, it can be only absolute path; or descendant if used in uses",
87                 value);
88
89             return Utils.nodeIdentifierFromPath(ctx, value);
90         }
91
92         @Override
93         public AugmentStatement createDeclared(
94                 final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx) {
95             return new AugmentStatementImpl(ctx);
96         }
97
98         @Override
99         public EffectiveStatement<SchemaNodeIdentifier, AugmentStatement> createEffective(
100                 final StmtContext<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> ctx) {
101             return new AugmentEffectiveStatementImpl(ctx);
102         }
103
104         @Override
105         public void onFullDefinitionDeclared(
106                 final Mutable<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> augmentNode) {
107             if (!augmentNode.isSupportedByFeatures()) {
108                 return;
109             }
110
111             super.onFullDefinitionDeclared(augmentNode);
112
113             if (StmtContextUtils.isInExtensionBody(augmentNode)) {
114                 return;
115             }
116
117             final ModelActionBuilder augmentAction = augmentNode.newInferenceAction(
118                 ModelProcessingPhase.EFFECTIVE_MODEL);
119             final ModelActionBuilder.Prerequisite<StmtContext<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>>> sourceCtxPrereq =
120                     augmentAction.requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
121             final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target =
122                     augmentAction.mutatesEffectiveCtx(getSearchRoot(augmentNode), SchemaNodeIdentifierBuildNamespace.class, augmentNode.getStatementArgument());
123             augmentAction.apply(new ModelActionBuilder.InferenceAction() {
124
125                 @Override
126                 public void apply(final ModelActionBuilder.InferenceContext ctx) {
127                     final StatementContextBase<?, ?, ?> augmentTargetCtx =
128                             (StatementContextBase<?, ?, ?>) target.resolve(ctx);
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() == YangStmtMapping.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.warn("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                         YangStmtMapping.AUGMENT);
158                     if (currentOrder == null) {
159                         currentOrder = 1;
160                     } else {
161                         currentOrder++;
162                     }
163
164                     augmentSourceCtx.addToNs(StmtOrderingNamespace.class, YangStmtMapping.AUGMENT, currentOrder);
165                 }
166
167                 @Override
168                 public void prerequisiteFailed(final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed) {
169                     /*
170                      * Do not fail, if it is an uses-augment to an unknown node.
171                      */
172                     if (YangStmtMapping.USES == augmentNode.getParentContext().getPublicDefinition()) {
173                         final StatementContextBase<?, ?, ?> targetNode = Utils.findNode(getSearchRoot(augmentNode),
174                                 augmentNode.getStatementArgument());
175                         if (targetNode != null && StmtContextUtils.isUnknownStatement(targetNode)) {
176                             augmentNode.setIsSupportedToBuildEffective(false);
177                             LOG.warn(
178                                     "Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
179                                     augmentNode.getStatementArgument(), augmentNode.getStatementSourceReference());
180                             return;
181                         }
182                     }
183
184                     throw new InferenceException(augmentNode.getStatementSourceReference(),
185                             "Augment target '%s' not found", augmentNode.getStatementArgument());
186                 }
187             });
188         }
189
190         private static Mutable<?, ?, ?> getSearchRoot(final Mutable<?, ?, ?> augmentContext) {
191             final Mutable<?, ?, ?> parent = augmentContext.getParentContext();
192             // Augment is in uses - we need to augment instantiated nodes in parent.
193             if (YangStmtMapping.USES == parent.getPublicDefinition()) {
194                 return parent.getParentContext();
195             }
196             return parent;
197         }
198
199         public static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
200                 final StatementContextBase<?, ?, ?> targetCtx) {
201             final CopyType typeOfCopy = UsesStatement.class.equals(sourceCtx.getParentContext().getPublicDefinition()
202                     .getDeclaredRepresentationClass()) ? CopyType.ADDED_BY_USES_AUGMENTATION
203                     : CopyType.ADDED_BY_AUGMENTATION;
204             /*
205              * Since Yang 1.1, if an augmentation is made conditional with a
206              * "when" statement, it is allowed to add mandatory nodes.
207              */
208             final boolean skipCheckOfMandatoryNodes = YangVersion.VERSION_1_1.equals(sourceCtx.getRootVersion())
209                     && isConditionalAugmentStmt(sourceCtx);
210
211             final Collection<? extends Mutable<?, ?, ?>> declared = sourceCtx.mutableDeclaredSubstatements();
212             final Collection<? extends Mutable<?, ?, ?>> effective = sourceCtx.mutableEffectiveSubstatements();
213             final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
214
215             for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
216                 if (originalStmtCtx.isSupportedByFeatures()) {
217                     copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
218                 }
219             }
220             for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
221                 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
222             }
223
224             targetCtx.addEffectiveSubstatements(buffer);
225         }
226
227         /**
228          * Checks whether supplied statement context is conditional augment
229          * statement.
230          *
231          * @param ctx
232          *            statement context to be checked
233          *
234          * @return true if supplied statement context is conditional augment
235          *         statement, otherwise false
236          */
237         private static boolean isConditionalAugmentStmt(final StmtContext<?, ?, ?> ctx) {
238             return ctx.getPublicDefinition() == YangStmtMapping.AUGMENT
239                     && StmtContextUtils.findFirstSubstatement(ctx, WhenStatement.class) != null;
240         }
241
242         private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
243                 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
244                 final boolean skipCheckOfMandatoryNodes) {
245             if (needToCopyByAugment(original)) {
246                 validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
247
248                 buffer.add(target.childCopyOf(original, typeOfCopy));
249             } else if (isReusedByAugment(original)) {
250                 buffer.add(original);
251             }
252         }
253
254         private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
255                 final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
256                 final boolean skipCheckOfMandatoryNodes) {
257
258             if (WhenStatement.class.equals(sourceCtx.getPublicDefinition().getDeclaredRepresentationClass())) {
259                 return;
260             }
261
262             if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
263                     && reguiredCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
264                 checkForMandatoryNodes(sourceCtx);
265             }
266
267             for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
268                 final boolean sourceIsDataNode = DataDefinitionStatement.class.isAssignableFrom(sourceCtx
269                         .getPublicDefinition().getDeclaredRepresentationClass());
270                 final boolean targetIsDataNode = DataDefinitionStatement.class.isAssignableFrom(subStatement
271                         .getPublicDefinition().getDeclaredRepresentationClass());
272                 final boolean qNamesEqual = sourceIsDataNode && targetIsDataNode
273                         && Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument());
274
275                 InferenceException.throwIf(qNamesEqual, sourceCtx.getStatementSourceReference(),
276                         "An augment cannot add node named '%s' because this name is already used in target",
277                         sourceCtx.rawStatementArgument());
278             }
279         }
280
281         private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
282             if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
283                 /*
284                  * We need to iterate over both declared and effective sub-statements,
285                  * because a mandatory node can be:
286                  * a) declared in augment body
287                  * b) added to augment body also via uses of a grouping and
288                  * such sub-statements are stored in effective sub-statements collection.
289                  */
290                 sourceCtx.allSubstatementsStream().forEach(Definition::checkForMandatoryNodes);
291             }
292
293             InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
294                     sourceCtx.getStatementSourceReference(),
295                     "An augment cannot add node '%s' because it is mandatory and in module different than target",
296                     sourceCtx.rawStatementArgument());
297         }
298
299         private static boolean reguiredCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
300                 Mutable<?, ?, ?> targetCtx) {
301             /*
302              * If the statement argument is not QName, it cannot be mandatory
303              * statement, therefore return false and skip mandatory nodes validation
304              */
305             if (!(sourceCtx.getStatementArgument() instanceof QName)) {
306                 return false;
307             }
308             final QName sourceStmtQName = (QName) sourceCtx.getStatementArgument();
309
310             // RootStatementContext, for example
311             final Mutable<?, ?, ?> root = targetCtx.getRoot();
312             do {
313                 Verify.verify(targetCtx.getStatementArgument() instanceof QName,
314                         "Argument of augment target statement must be QName.");
315                 final QName targetStmtQName = (QName) targetCtx.getStatementArgument();
316                 /*
317                  * If target is from another module, return true and perform
318                  * mandatory nodes validation
319                  */
320                 if (!Utils.belongsToTheSameModule(targetStmtQName, sourceStmtQName)) {
321                     return true;
322                 }
323
324                 /*
325                  * If target or one of the target's ancestors from the same namespace
326                  * is a presence container
327                  * or is non-mandatory choice
328                  * or is non-mandatory list
329                  * return false and skip mandatory nodes validation, because these nodes
330                  * are not mandatory node containers according to RFC 6020 section 3.1.
331                  */
332                 if (StmtContextUtils.isPresenceContainer(targetCtx)
333                         || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
334                         || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
335                     return false;
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 final Set<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES, YangStmtMapping.WHEN,
347                 YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
348
349         public static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
350             return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
351         }
352
353         private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
354
355         public static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
356             return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
357         }
358
359         static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
360             /*
361              * :TODO Substatement must be allowed augment target type e.g.
362              * Container, etc... and must not be for example grouping, identity etc.
363              * It is problem in case when more than one substatements have the same
364              * QName, for example Grouping and Container are siblings and they have
365              * the same QName. We must find the Container and the Grouping must be
366              * ignored as disallowed augment target.
367              */
368             final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
369                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
370
371             // if no allowed target is returned we consider all targets allowed
372             return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
373                     || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
374         }
375
376         @Override
377         protected SubstatementValidator getSubstatementValidator() {
378             return SUBSTATEMENT_VALIDATOR;
379         }
380     }
381
382     @Nonnull
383     @Override
384     public SchemaNodeIdentifier getTargetNode() {
385         return argument();
386     }
387
388     @Nonnull
389     @Override
390     public Collection<? extends DataDefinitionStatement> getDataDefinitions() {
391         return allDeclared(DataDefinitionStatement.class);
392     }
393
394     @Nonnull
395     @Override
396     public Collection<? extends ActionStatement> getActions() {
397         return allDeclared(ActionStatement.class);
398     }
399
400     @Override
401     public final Collection<? extends NotificationStatement> getNotifications() {
402         return allDeclared(NotificationStatement.class);
403     }
404 }