Upstream StmtContextUtils.producesDeclared()
[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.WhenStatement;
36 import org.opendaylight.yangtools.yang.parser.rfc7950.namespace.ChildSchemaNodeNamespace;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.ArgumentUtils;
38 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
39 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.EffectiveStatementMixins.EffectiveStatementWithFlags.FlagsBuilder;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
50 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
51 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
52 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
53 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 abstract class AbstractAugmentStatementSupport
58         extends BaseStatementSupport<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> {
59     private static final Logger LOG = LoggerFactory.getLogger(AbstractAugmentStatementSupport.class);
60     private static final Pattern PATH_REL_PATTERN1 = Pattern.compile("\\.\\.?\\s*/(.+)");
61     private static final Pattern PATH_REL_PATTERN2 = Pattern.compile("//.*");
62
63     AbstractAugmentStatementSupport() {
64         super(YangStmtMapping.AUGMENT);
65     }
66
67     @Override
68     public final SchemaNodeIdentifier parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
69         SourceException.throwIf(PATH_REL_PATTERN1.matcher(value).matches()
70             || PATH_REL_PATTERN2.matcher(value).matches(), ctx.getStatementSourceReference(),
71             "Augment argument \'%s\' is not valid, it can be only absolute path; or descendant if used in uses",
72             value);
73
74         return ArgumentUtils.nodeIdentifierFromPath(ctx, value);
75     }
76
77     @Override
78     public final void onFullDefinitionDeclared(
79             final Mutable<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> augmentNode) {
80         if (!augmentNode.isSupportedByFeatures()) {
81             return;
82         }
83
84         super.onFullDefinitionDeclared(augmentNode);
85
86         if (StmtContextUtils.isInExtensionBody(augmentNode)) {
87             return;
88         }
89
90         final ModelActionBuilder augmentAction = augmentNode.newInferenceAction(
91             ModelProcessingPhase.EFFECTIVE_MODEL);
92         final Prerequisite<StmtContext<SchemaNodeIdentifier, AugmentStatement,
93                 AugmentEffectiveStatement>> sourceCtxPrereq =
94                     augmentAction.requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
95         final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target =
96                 augmentAction.mutatesEffectiveCtxPath(getSearchRoot(augmentNode),
97                     ChildSchemaNodeNamespace.class, augmentNode.coerceStatementArgument().getPathFromRoot());
98
99         augmentAction.apply(new InferenceAction() {
100             @Override
101             public void apply(final InferenceContext ctx) {
102                 final StatementContextBase<?, ?, ?> augmentTargetCtx =
103                         (StatementContextBase<?, ?, ?>) target.resolve(ctx);
104                 if (!isSupportedAugmentTarget(augmentTargetCtx)
105                         || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
106                     augmentNode.setIsSupportedToBuildEffective(false);
107                     return;
108                 }
109
110                 // We are targeting a context which is creating implicit nodes. In order to keep things consistent,
111                 // we will need to circle back when creating effective statements.
112                 if (augmentTargetCtx.hasImplicitParentSupport()) {
113                     augmentNode.addToNs(AugmentImplicitHandlingNamespace.class, augmentNode, augmentTargetCtx);
114                 }
115
116                 final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
117                 // FIXME: this is a workaround for models which augment a node which is added via an extension
118                 //        which we do not handle. This needs to be reworked in terms of unknown schema nodes.
119                 try {
120                     copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
121                     augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
122                 } catch (final SourceException e) {
123                     LOG.warn("Failed to add augmentation {} defined at {}",
124                         augmentTargetCtx.getStatementSourceReference(),
125                             augmentSourceCtx.getStatementSourceReference(), e);
126                 }
127             }
128
129             @Override
130             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
131                 /*
132                  * Do not fail, if it is an uses-augment to an unknown node.
133                  */
134                 if (YangStmtMapping.USES == augmentNode.coerceParentContext().getPublicDefinition()) {
135                     final SchemaNodeIdentifier augmentArg = augmentNode.coerceStatementArgument();
136                     final Optional<StmtContext<?, ?, ?>> targetNode = ChildSchemaNodeNamespace.findNode(
137                         getSearchRoot(augmentNode), augmentArg);
138                     if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
139                         augmentNode.setIsSupportedToBuildEffective(false);
140                         LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
141                             augmentArg, augmentNode.getStatementSourceReference());
142                         return;
143                     }
144                 }
145
146                 throw new InferenceException(augmentNode.getStatementSourceReference(),
147                         "Augment target '%s' not found", augmentNode.getStatementArgument());
148             }
149         });
150     }
151
152     @Override
153     protected final AugmentStatement createDeclared(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx,
154             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
155         return new RegularAugmentStatement(ctx, substatements);
156     }
157
158     @Override
159     protected final AugmentStatement createEmptyDeclared(
160             final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx) {
161         return new EmptyAugmentStatement(ctx);
162     }
163
164     @Override
165     protected final List<? extends StmtContext<?, ?, ?>> statementsToBuild(
166             final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
167             final List<? extends StmtContext<?, ?, ?>> substatements) {
168         final StatementContextBase<?, ?, ?> implicitDef = ctx.getFromNamespace(AugmentImplicitHandlingNamespace.class,
169             ctx);
170         return implicitDef == null ? substatements : Lists.transform(substatements, subCtx -> {
171             verify(subCtx instanceof StatementContextBase);
172             return implicitDef.wrapWithImplicit((StatementContextBase<?, ?, ?>) subCtx);
173         });
174     }
175
176     @Override
177     protected final AugmentEffectiveStatement createEffective(
178             final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
179             final AugmentStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
180         final int flags = new FlagsBuilder()
181                 .setStatus(findFirstArgument(substatements, StatusEffectiveStatement.class, Status.CURRENT))
182                 .toFlags();
183
184         return new AugmentEffectiveStatementImpl(declared, ctx.coerceStatementArgument(), flags,
185             StmtContextUtils.getRootModuleQName(ctx), substatements, ctx.getStatementSourceReference(),
186             (AugmentationSchemaNode) ctx.getOriginalCtx().map(StmtContext::buildEffective).orElse(null));
187     }
188
189     @Override
190     protected final AugmentEffectiveStatement createEmptyEffective(
191             final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
192             final AugmentStatement declared) {
193         return createEffective(ctx, declared, ImmutableList.of());
194     }
195
196     private static StmtContext<?, ?, ?> getSearchRoot(final StmtContext<?, ?, ?> augmentContext) {
197         // Augment is in uses - we need to augment instantiated nodes in parent.
198         final StmtContext<?, ?, ?> parent = augmentContext.coerceParentContext();
199         if (YangStmtMapping.USES == parent.getPublicDefinition()) {
200             return parent.getParentContext();
201         }
202         return parent;
203     }
204
205     static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
206             final StatementContextBase<?, ?, ?> targetCtx) {
207         final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
208                 ? CopyType.ADDED_BY_USES_AUGMENTATION : CopyType.ADDED_BY_AUGMENTATION;
209         /*
210          * Since Yang 1.1, if an augmentation is made conditional with a
211          * "when" statement, it is allowed to add mandatory nodes.
212          */
213         final boolean skipCheckOfMandatoryNodes = YangVersion.VERSION_1_1.equals(sourceCtx.getRootVersion())
214                 && isConditionalAugmentStmt(sourceCtx);
215
216         final Collection<? extends Mutable<?, ?, ?>> declared = sourceCtx.mutableDeclaredSubstatements();
217         final Collection<? extends Mutable<?, ?, ?>> effective = sourceCtx.mutableEffectiveSubstatements();
218         final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
219
220         for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
221             if (originalStmtCtx.isSupportedByFeatures()) {
222                 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
223             }
224         }
225         for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
226             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
227         }
228
229         targetCtx.addEffectiveSubstatements(buffer);
230     }
231
232     /**
233      * Checks whether supplied statement context is conditional augment
234      * statement.
235      *
236      * @param ctx
237      *            statement context to be checked
238      *
239      * @return true if supplied statement context is conditional augment
240      *         statement, otherwise false
241      */
242     private static boolean isConditionalAugmentStmt(final StmtContext<?, ?, ?> ctx) {
243         return ctx.getPublicDefinition() == YangStmtMapping.AUGMENT && hasWhenSubstatement(ctx);
244     }
245
246     private static boolean hasWhenSubstatement(final StmtContext<?, ?, ?> ctx) {
247         return StmtContextUtils.findFirstSubstatement(ctx, WhenStatement.class) != null;
248     }
249
250     private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
251             final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
252             final boolean skipCheckOfMandatoryNodes) {
253         if (needToCopyByAugment(original)) {
254             validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
255
256             buffer.add(target.childCopyOf(original, typeOfCopy));
257         } else if (isReusedByAugment(original)) {
258             buffer.add(original);
259         }
260     }
261
262     private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
263             final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
264             final boolean skipCheckOfMandatoryNodes) {
265
266         if (sourceCtx.producesDeclared(WhenStatement.class)) {
267             return;
268         }
269
270         if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
271                 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
272             checkForMandatoryNodes(sourceCtx);
273         }
274
275         // Data definition statements must not collide on their namespace
276         if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
277             for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
278                 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
279                     InferenceException.throwIf(
280                         Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument()),
281                         sourceCtx.getStatementSourceReference(),
282                         "An augment cannot add node named '%s' because this name is already used in target",
283                         sourceCtx.rawStatementArgument());
284                 }
285             }
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.allSubstatementsStream().forEach(AbstractAugmentStatementSupport::checkForMandatoryNodes);
299         }
300
301         InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
302                 sourceCtx.getStatementSourceReference(),
303                 "An augment cannot add node '%s' because it is mandatory and in module different than target",
304                 sourceCtx.rawStatementArgument());
305     }
306
307     private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
308             Mutable<?, ?, ?> targetCtx) {
309         /*
310          * If the statement argument is not QName, it cannot be mandatory
311          * statement, therefore return false and skip mandatory nodes validation
312          */
313         final Object arg = sourceCtx.getStatementArgument();
314         if (!(arg instanceof QName)) {
315             return false;
316         }
317         final QName sourceStmtQName = (QName) arg;
318
319         // RootStatementContext, for example
320         final Mutable<?, ?, ?> root = targetCtx.getRoot();
321         do {
322             final Object targetArg = targetCtx.getStatementArgument();
323             Verify.verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s",
324                 targetArg);
325             final QName targetStmtQName = (QName) targetArg;
326             /*
327              * If target is from another module, return true and perform mandatory nodes validation
328              */
329             if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
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
347             // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
348             // conditional -- in which case we do not run further checks
349             if (targetCtx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
350                 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
351                 if (optPrevCopy.isPresent()) {
352                     final StmtContext<?, ?, ?> original = optPrevCopy.get();
353                     final Object origArg = original.coerceStatementArgument();
354                     Verify.verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
355
356                     if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
357                             && hasWhenSubstatement(getParentAugmentation(original))) {
358                         return false;
359                     }
360                 }
361             }
362         } while ((targetCtx = targetCtx.getParentContext()) != root);
363
364         /*
365          * All target node's parents belong to the same module as source node,
366          * therefore return false and skip mandatory nodes validation.
367          */
368         return false;
369     }
370
371     private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
372         StmtContext<?, ?, ?> parent = Verify.verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
373         while (parent.getPublicDefinition() != YangStmtMapping.AUGMENT) {
374             parent = Verify.verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
375         }
376         return parent;
377     }
378
379     private static final ImmutableSet<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES,
380         YangStmtMapping.WHEN, YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
381
382     private static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
383         return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
384     }
385
386     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
387
388     private static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
389         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
390     }
391
392     static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
393         /*
394          * :TODO Substatement must be allowed augment target type e.g.
395          * Container, etc... and must not be for example grouping, identity etc.
396          * It is problem in case when more than one substatements have the same
397          * QName, for example Grouping and Container are siblings and they have
398          * the same QName. We must find the Container and the Grouping must be
399          * ignored as disallowed augment target.
400          */
401         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
402             ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
403
404         // if no allowed target is returned we consider all targets allowed
405         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
406                 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
407     }
408 }