Further StmtContext/CommonStmtCtx merge
[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.common.YangVersion;
24 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.Status;
26 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
33 import org.opendaylight.yangtools.yang.model.api.stmt.StatusEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.WhenEffectiveStatement;
36 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.ArgumentUtils;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
38 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.EffectiveStatementMixins.EffectiveStatementWithFlags.FlagsBuilder;
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.getStatementSourceReference(),
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,
96             augmentNode.coerceStatementArgument().getNodeIdentifiers());
97
98         augmentAction.apply(new InferenceAction() {
99             @Override
100             public void apply(final InferenceContext ctx) {
101                 final StatementContextBase<?, ?, ?> augmentTargetCtx =
102                         (StatementContextBase<?, ?, ?>) target.resolve(ctx);
103                 if (!isSupportedAugmentTarget(augmentTargetCtx)
104                         || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
105                     augmentNode.setIsSupportedToBuildEffective(false);
106                     return;
107                 }
108
109                 // We are targeting a context which is creating implicit nodes. In order to keep things consistent,
110                 // we will need to circle back when creating effective statements.
111                 if (augmentTargetCtx.hasImplicitParentSupport()) {
112                     augmentNode.addToNs(AugmentImplicitHandlingNamespace.class, augmentNode, augmentTargetCtx);
113                 }
114
115                 final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
116                 // FIXME: this is a workaround for models which augment a node which is added via an extension
117                 //        which we do not handle. This needs to be reworked in terms of unknown schema nodes.
118                 try {
119                     copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
120                     augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
121                 } catch (final SourceException e) {
122                     LOG.warn("Failed to add augmentation {} defined at {}",
123                         augmentTargetCtx.getStatementSourceReference(),
124                             augmentSourceCtx.getStatementSourceReference(), e);
125                 }
126             }
127
128             @Override
129             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
130                 /*
131                  * Do not fail, if it is an uses-augment to an unknown node.
132                  */
133                 if (YangStmtMapping.USES == augmentNode.coerceParentContext().getPublicDefinition()) {
134                     final SchemaNodeIdentifier augmentArg = augmentNode.coerceStatementArgument();
135                     final Optional<StmtContext<?, ?, ?>> targetNode = SchemaTreeNamespace.findNode(
136                         getSearchRoot(augmentNode), augmentArg);
137                     if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
138                         augmentNode.setIsSupportedToBuildEffective(false);
139                         LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
140                             augmentArg, augmentNode.getStatementSourceReference());
141                         return;
142                     }
143                 }
144
145                 throw new InferenceException(augmentNode.getStatementSourceReference(),
146                         "Augment target '%s' not found", augmentNode.getStatementArgument());
147             }
148         });
149     }
150
151     @Override
152     protected final AugmentStatement createDeclared(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx,
153             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
154         return new RegularAugmentStatement(ctx.coerceRawStatementArgument(), ctx.coerceStatementArgument(),
155             substatements);
156     }
157
158     @Override
159     protected final AugmentStatement createEmptyDeclared(
160             final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx) {
161         return new EmptyAugmentStatement(ctx.coerceRawStatementArgument(), ctx.coerceStatementArgument());
162     }
163
164     @Override
165     protected final List<? extends StmtContext<?, ?, ?>> statementsToBuild(
166             final Current<SchemaNodeIdentifier, AugmentStatement> stmt,
167             final List<? extends StmtContext<?, ?, ?>> substatements) {
168         // Pick up the marker left by onFullDefinitionDeclared() inference action. If it is present we need to pass our
169         // children through target's implicit wrapping.
170         final StatementContextBase<?, ?, ?> implicitDef = stmt.getFromNamespace(AugmentImplicitHandlingNamespace.class,
171             stmt.caerbannog());
172         return implicitDef == null ? substatements : Lists.transform(substatements, subCtx -> {
173             verify(subCtx instanceof StatementContextBase);
174             return implicitDef.wrapWithImplicit((StatementContextBase<?, ?, ?>) subCtx);
175         });
176     }
177
178     @Override
179     protected final AugmentEffectiveStatement createEffective(
180             final Current<SchemaNodeIdentifier, AugmentStatement> stmt,
181             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
182         final int flags = new FlagsBuilder()
183                 .setStatus(findFirstArgument(substatements, StatusEffectiveStatement.class, Status.CURRENT))
184                 .toFlags();
185
186         return new AugmentEffectiveStatementImpl(stmt.declared(), stmt.getArgument(), flags,
187             StmtContextUtils.getRootModuleQName(stmt.caerbannog()), substatements, stmt.sourceReference(),
188             (AugmentationSchemaNode) stmt.original());
189     }
190
191     private static StmtContext<?, ?, ?> getSearchRoot(final StmtContext<?, ?, ?> augmentContext) {
192         // Augment is in uses - we need to augment instantiated nodes in parent.
193         final StmtContext<?, ?, ?> parent = augmentContext.coerceParentContext();
194         if (YangStmtMapping.USES == parent.getPublicDefinition()) {
195             return parent.getParentContext();
196         }
197         return parent;
198     }
199
200     static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
201             final StatementContextBase<?, ?, ?> targetCtx) {
202         final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
203                 ? CopyType.ADDED_BY_USES_AUGMENTATION : 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         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     /**
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 && hasWhenSubstatement(ctx);
239     }
240
241     private static boolean hasWhenSubstatement(final StmtContext<?, ?, ?> ctx) {
242         return ctx.hasSubstatement(WhenEffectiveStatement.class);
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, final boolean unsupported) {
248         // We always copy statements, but if either the source statement or the augmentation which causes it are not
249         // supported to build we also mark the target as such.
250         if (needToCopyByAugment(original)) {
251             validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
252
253             final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
254             if (unsupported) {
255                 copy.setIsSupportedToBuildEffective(false);
256             }
257             buffer.add(copy);
258         } else if (isReusedByAugment(original) && !unsupported) {
259             buffer.add(original);
260         }
261     }
262
263     private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
264             final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
265             final boolean skipCheckOfMandatoryNodes) {
266         if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
267                 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
268             checkForMandatoryNodes(sourceCtx);
269         }
270
271         // Data definition statements must not collide on their namespace
272         if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
273             for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
274                 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
275                     InferenceException.throwIf(
276                         Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument()),
277                         sourceCtx.getStatementSourceReference(),
278                         "An augment cannot add node named '%s' because this name is already used in target",
279                         sourceCtx.rawStatementArgument());
280                 }
281             }
282         }
283     }
284
285     private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
286         if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
287             /*
288              * We need to iterate over both declared and effective sub-statements,
289              * because a mandatory node can be:
290              * a) declared in augment body
291              * b) added to augment body also via uses of a grouping and
292              * such sub-statements are stored in effective sub-statements collection.
293              */
294             sourceCtx.allSubstatementsStream().forEach(AbstractAugmentStatementSupport::checkForMandatoryNodes);
295         }
296
297         InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
298                 sourceCtx.getStatementSourceReference(),
299                 "An augment cannot add node '%s' because it is mandatory and in module different than target",
300                 sourceCtx.rawStatementArgument());
301     }
302
303     private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
304             Mutable<?, ?, ?> targetCtx) {
305         /*
306          * If the statement argument is not QName, it cannot be mandatory
307          * statement, therefore return false and skip mandatory nodes validation
308          */
309         final Object arg = sourceCtx.getStatementArgument();
310         if (!(arg instanceof QName)) {
311             return false;
312         }
313         final QName sourceStmtQName = (QName) arg;
314
315         // RootStatementContext, for example
316         final Mutable<?, ?, ?> root = targetCtx.getRoot();
317         do {
318             final Object targetArg = targetCtx.getStatementArgument();
319             Verify.verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s",
320                 targetArg);
321             final QName targetStmtQName = (QName) targetArg;
322             /*
323              * If target is from another module, return true and perform mandatory nodes validation
324              */
325             if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
326                 return true;
327             }
328
329             /*
330              * If target or one of the target's ancestors from the same namespace
331              * is a presence container
332              * or is non-mandatory choice
333              * or is non-mandatory list
334              * return false and skip mandatory nodes validation, because these nodes
335              * are not mandatory node containers according to RFC 6020 section 3.1.
336              */
337             if (StmtContextUtils.isPresenceContainer(targetCtx)
338                     || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
339                     || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
340                 return false;
341             }
342
343             // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
344             // conditional -- in which case we do not run further checks
345             if (targetCtx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
346                 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
347                 if (optPrevCopy.isPresent()) {
348                     final StmtContext<?, ?, ?> original = optPrevCopy.get();
349                     final Object origArg = original.coerceStatementArgument();
350                     Verify.verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
351
352                     if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
353                             && hasWhenSubstatement(getParentAugmentation(original))) {
354                         return false;
355                     }
356                 }
357             }
358         } while ((targetCtx = targetCtx.getParentContext()) != root);
359
360         /*
361          * All target node's parents belong to the same module as source node,
362          * therefore return false and skip mandatory nodes validation.
363          */
364         return false;
365     }
366
367     private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
368         StmtContext<?, ?, ?> parent = Verify.verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
369         while (parent.getPublicDefinition() != YangStmtMapping.AUGMENT) {
370             parent = Verify.verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
371         }
372         return parent;
373     }
374
375     private static final ImmutableSet<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES,
376         YangStmtMapping.WHEN, YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
377
378     private static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
379         return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
380     }
381
382     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
383
384     private static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
385         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
386     }
387
388     static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
389         /*
390          * :TODO Substatement must be allowed augment target type e.g.
391          * Container, etc... and must not be for example grouping, identity etc.
392          * It is problem in case when more than one substatements have the same
393          * QName, for example Grouping and Container are siblings and they have
394          * the same QName. We must find the Container and the Grouping must be
395          * ignored as disallowed augment target.
396          */
397         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
398             ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
399
400         // if no allowed target is returned we consider all targets allowed
401         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
402                 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
403     }
404 }