Do not use StatementSourceReference in AbstractDeclaredEffectiveStatement
[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 static com.google.common.base.Verify.verify;
11
12 import com.google.common.base.Verify;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.collect.Lists;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.List;
19 import java.util.Objects;
20 import java.util.Optional;
21 import java.util.regex.Pattern;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.Status;
25 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
26 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
32 import org.opendaylight.yangtools.yang.model.api.stmt.StatusEffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.WhenEffectiveStatement;
35 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.ArgumentUtils;
36 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.EffectiveStatementMixins.EffectiveStatementWithFlags.FlagsBuilder;
38 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.SubstatementIndexingException;
39 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
51 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
52 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
53 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
54 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 abstract class AbstractAugmentStatementSupport
59         extends BaseStatementSupport<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> {
60     private static final Logger LOG = LoggerFactory.getLogger(AbstractAugmentStatementSupport.class);
61     private static final Pattern PATH_REL_PATTERN1 = Pattern.compile("\\.\\.?\\s*/(.+)");
62     private static final Pattern PATH_REL_PATTERN2 = Pattern.compile("//.*");
63
64     AbstractAugmentStatementSupport() {
65         super(YangStmtMapping.AUGMENT);
66     }
67
68     @Override
69     public final SchemaNodeIdentifier parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
70         SourceException.throwIf(PATH_REL_PATTERN1.matcher(value).matches()
71             || PATH_REL_PATTERN2.matcher(value).matches(), ctx.sourceReference(),
72             "Augment argument \'%s\' is not valid, it can be only absolute path; or descendant if used in uses",
73             value);
74
75         return ArgumentUtils.nodeIdentifierFromPath(ctx, value);
76     }
77
78     @Override
79     public final void onFullDefinitionDeclared(
80             final Mutable<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> augmentNode) {
81         if (!augmentNode.isSupportedByFeatures()) {
82             // We need this augment node to be present, but it should not escape to effective world
83             augmentNode.setIsSupportedToBuildEffective(false);
84         }
85
86         super.onFullDefinitionDeclared(augmentNode);
87
88         if (StmtContextUtils.isInExtensionBody(augmentNode)) {
89             return;
90         }
91
92         final ModelActionBuilder augmentAction = augmentNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
93         augmentAction.requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
94         final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target = augmentAction.mutatesEffectiveCtxPath(
95             getSearchRoot(augmentNode), SchemaTreeNamespace.class, augmentNode.getArgument().getNodeIdentifiers());
96
97         augmentAction.apply(new InferenceAction() {
98             @Override
99             public void apply(final InferenceContext ctx) {
100                 final StatementContextBase<?, ?, ?> augmentTargetCtx =
101                         (StatementContextBase<?, ?, ?>) target.resolve(ctx);
102                 if (!isSupportedAugmentTarget(augmentTargetCtx)
103                         || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
104                     augmentNode.setIsSupportedToBuildEffective(false);
105                     return;
106                 }
107
108                 // We are targeting a context which is creating implicit nodes. In order to keep things consistent,
109                 // we will need to circle back when creating effective statements.
110                 if (augmentTargetCtx.hasImplicitParentSupport()) {
111                     augmentNode.addToNs(AugmentImplicitHandlingNamespace.class, augmentNode, augmentTargetCtx);
112                 }
113
114                 final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
115                 // FIXME: this is a workaround for models which augment a node which is added via an extension
116                 //        which we do not handle. This needs to be reworked in terms of unknown schema nodes.
117                 try {
118                     copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
119                     augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
120                 } catch (final SourceException e) {
121                     LOG.warn("Failed to add augmentation {} defined at {}", augmentTargetCtx.sourceReference(),
122                             augmentSourceCtx.sourceReference(), e);
123                 }
124             }
125
126             @Override
127             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
128                 /*
129                  * Do not fail, if it is an uses-augment to an unknown node.
130                  */
131                 if (YangStmtMapping.USES == augmentNode.coerceParentContext().publicDefinition()) {
132                     final SchemaNodeIdentifier augmentArg = augmentNode.getArgument();
133                     final Optional<StmtContext<?, ?, ?>> targetNode = SchemaTreeNamespace.findNode(
134                         getSearchRoot(augmentNode), augmentArg);
135                     if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
136                         augmentNode.setIsSupportedToBuildEffective(false);
137                         LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
138                             augmentArg, augmentNode.sourceReference());
139                         return;
140                     }
141                 }
142
143                 throw new InferenceException(augmentNode.sourceReference(), "Augment target '%s' not found",
144                     augmentNode.argument());
145             }
146         });
147     }
148
149     @Override
150     protected final AugmentStatement createDeclared(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx,
151             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
152         return new RegularAugmentStatement(ctx.getRawArgument(), ctx.getArgument(), substatements);
153     }
154
155     @Override
156     protected final AugmentStatement createEmptyDeclared(
157             final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx) {
158         return new EmptyAugmentStatement(ctx.getRawArgument(), ctx.getArgument());
159     }
160
161     @Override
162     protected final List<? extends StmtContext<?, ?, ?>> statementsToBuild(
163             final Current<SchemaNodeIdentifier, AugmentStatement> stmt,
164             final List<? extends StmtContext<?, ?, ?>> substatements) {
165         // Pick up the marker left by onFullDefinitionDeclared() inference action. If it is present we need to pass our
166         // children through target's implicit wrapping.
167         final StatementContextBase<?, ?, ?> implicitDef = stmt.getFromNamespace(AugmentImplicitHandlingNamespace.class,
168             stmt.caerbannog());
169         return implicitDef == null ? substatements : Lists.transform(substatements, subCtx -> {
170             verify(subCtx instanceof StatementContextBase);
171             return implicitDef.wrapWithImplicit((StatementContextBase<?, ?, ?>) subCtx);
172         });
173     }
174
175     @Override
176     protected final AugmentEffectiveStatement createEffective(
177             final Current<SchemaNodeIdentifier, AugmentStatement> stmt,
178             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
179         final int flags = new FlagsBuilder()
180                 .setStatus(findFirstArgument(substatements, StatusEffectiveStatement.class, Status.CURRENT))
181                 .toFlags();
182
183         try {
184             return new AugmentEffectiveStatementImpl(stmt.declared(), stmt.getArgument(), flags,
185                 StmtContextUtils.getRootModuleQName(stmt.caerbannog()), substatements,
186                 (AugmentationSchemaNode) stmt.original());
187         } catch (SubstatementIndexingException e) {
188             throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
189         }
190     }
191
192     private static StmtContext<?, ?, ?> getSearchRoot(final StmtContext<?, ?, ?> augmentContext) {
193         // Augment is in uses - we need to augment instantiated nodes in parent.
194         final StmtContext<?, ?, ?> parent = augmentContext.coerceParentContext();
195         if (YangStmtMapping.USES == parent.publicDefinition()) {
196             return parent.getParentContext();
197         }
198         return parent;
199     }
200
201     final void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
202             final StatementContextBase<?, ?, ?> targetCtx) {
203         final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
204                 ? CopyType.ADDED_BY_USES_AUGMENTATION : 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 = allowsMandatory(sourceCtx);
210         final boolean unsupported = !sourceCtx.isSupportedByFeatures();
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             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes,
218                 unsupported || !originalStmtCtx.isSupportedByFeatures());
219         }
220         for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
221             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes, unsupported);
222         }
223
224         targetCtx.addEffectiveSubstatements(buffer);
225     }
226
227     abstract boolean allowsMandatory(StmtContext<?, ?, ?> ctx);
228
229     static boolean hasWhenSubstatement(final StmtContext<?, ?, ?> ctx) {
230         return ctx.hasSubstatement(WhenEffectiveStatement.class);
231     }
232
233     private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
234             final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
235             final boolean skipCheckOfMandatoryNodes, final boolean unsupported) {
236         // We always copy statements, but if either the source statement or the augmentation which causes it are not
237         // supported to build we also mark the target as such.
238         if (needToCopyByAugment(original)) {
239             validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
240
241             final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
242             if (unsupported) {
243                 copy.setIsSupportedToBuildEffective(false);
244             }
245             buffer.add(copy);
246         } else if (isReusedByAugment(original) && !unsupported) {
247             buffer.add(original);
248         }
249     }
250
251     private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
252             final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
253             final boolean skipCheckOfMandatoryNodes) {
254         if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
255                 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
256             checkForMandatoryNodes(sourceCtx);
257         }
258
259         // Data definition statements must not collide on their namespace
260         if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
261             for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
262                 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
263                     InferenceException.throwIf(Objects.equals(sourceCtx.argument(), subStatement.argument()),
264                         sourceCtx.sourceReference(),
265                         "An augment cannot add node named '%s' because this name is already used in target",
266                         sourceCtx.rawArgument());
267                 }
268             }
269         }
270     }
271
272     private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
273         if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
274             /*
275              * We need to iterate over both declared and effective sub-statements,
276              * because a mandatory node can be:
277              * a) declared in augment body
278              * b) added to augment body also via uses of a grouping and
279              * such sub-statements are stored in effective sub-statements collection.
280              */
281             sourceCtx.allSubstatementsStream().forEach(AbstractAugmentStatementSupport::checkForMandatoryNodes);
282         }
283
284         InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx), sourceCtx.sourceReference(),
285             "An augment cannot add node '%s' because it is mandatory and in module different than target",
286             sourceCtx.rawArgument());
287     }
288
289     private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
290             Mutable<?, ?, ?> targetCtx) {
291         /*
292          * If the statement argument is not QName, it cannot be mandatory
293          * statement, therefore return false and skip mandatory nodes validation
294          */
295         final Object arg = sourceCtx.argument();
296         if (!(arg instanceof QName)) {
297             return false;
298         }
299         final QName sourceStmtQName = (QName) arg;
300
301         // RootStatementContext, for example
302         final Mutable<?, ?, ?> root = targetCtx.getRoot();
303         do {
304             final Object targetArg = targetCtx.argument();
305             verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s", targetArg);
306             final QName targetStmtQName = (QName) targetArg;
307             /*
308              * If target is from another module, return true and perform mandatory nodes validation
309              */
310             if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
311                 return true;
312             }
313
314             /*
315              * If target or one of the target's ancestors from the same namespace
316              * is a presence container
317              * or is non-mandatory choice
318              * or is non-mandatory list
319              * return false and skip mandatory nodes validation, because these nodes
320              * are not mandatory node containers according to RFC 6020 section 3.1.
321              */
322             if (StmtContextUtils.isPresenceContainer(targetCtx)
323                     || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
324                     || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
325                 return false;
326             }
327
328             // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
329             // conditional -- in which case we do not run further checks
330             if (targetCtx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
331                 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
332                 if (optPrevCopy.isPresent()) {
333                     final StmtContext<?, ?, ?> original = optPrevCopy.get();
334                     final Object origArg = original.getArgument();
335                     Verify.verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
336
337                     if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
338                             && hasWhenSubstatement(getParentAugmentation(original))) {
339                         return false;
340                     }
341                 }
342             }
343         } while ((targetCtx = targetCtx.getParentContext()) != root);
344
345         /*
346          * All target node's parents belong to the same module as source node,
347          * therefore return false and skip mandatory nodes validation.
348          */
349         return false;
350     }
351
352     private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
353         StmtContext<?, ?, ?> parent = Verify.verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
354         while (parent.publicDefinition() != YangStmtMapping.AUGMENT) {
355             parent = Verify.verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
356         }
357         return parent;
358     }
359
360     private static final ImmutableSet<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES,
361         YangStmtMapping.WHEN, YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
362
363     private static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
364         return !NOCOPY_DEF_SET.contains(stmtContext.publicDefinition());
365     }
366
367     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
368
369     private static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
370         return REUSED_DEF_SET.contains(stmtContext.publicDefinition());
371     }
372
373     static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
374         /*
375          * :TODO Substatement must be allowed augment target type e.g.
376          * Container, etc... and must not be for example grouping, identity etc.
377          * It is problem in case when more than one substatements have the same
378          * QName, for example Grouping and Container are siblings and they have
379          * the same QName. We must find the Container and the Grouping must be
380          * ignored as disallowed augment target.
381          */
382         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
383             ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
384
385         // if no allowed target is returned we consider all targets allowed
386         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
387                 || allowedAugmentTargets.contains(substatementCtx.publicDefinition());
388     }
389 }