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