Add StmtContext.findFirstSubstatementArgument()
[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.model.api.stmt.WhenStatement;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.namespace.ChildSchemaNodeNamespace;
38 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.ArgumentUtils;
39 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
40 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.EffectiveStatementMixins.EffectiveStatementWithFlags.FlagsBuilder;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
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             return;
83         }
84
85         super.onFullDefinitionDeclared(augmentNode);
86
87         if (StmtContextUtils.isInExtensionBody(augmentNode)) {
88             return;
89         }
90
91         final ModelActionBuilder augmentAction = augmentNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
92         augmentAction.requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
93         final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target = augmentAction.mutatesEffectiveCtxPath(
94             getSearchRoot(augmentNode), ChildSchemaNodeNamespace.class,
95             augmentNode.coerceStatementArgument().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 {}",
122                         augmentTargetCtx.getStatementSourceReference(),
123                             augmentSourceCtx.getStatementSourceReference(), e);
124                 }
125             }
126
127             @Override
128             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
129                 /*
130                  * Do not fail, if it is an uses-augment to an unknown node.
131                  */
132                 if (YangStmtMapping.USES == augmentNode.coerceParentContext().getPublicDefinition()) {
133                     final SchemaNodeIdentifier augmentArg = augmentNode.coerceStatementArgument();
134                     final Optional<StmtContext<?, ?, ?>> targetNode = ChildSchemaNodeNamespace.findNode(
135                         getSearchRoot(augmentNode), augmentArg);
136                     if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
137                         augmentNode.setIsSupportedToBuildEffective(false);
138                         LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
139                             augmentArg, augmentNode.getStatementSourceReference());
140                         return;
141                     }
142                 }
143
144                 throw new InferenceException(augmentNode.getStatementSourceReference(),
145                         "Augment target '%s' not found", augmentNode.getStatementArgument());
146             }
147         });
148     }
149
150     @Override
151     protected final AugmentStatement createDeclared(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx,
152             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
153         return new RegularAugmentStatement(ctx.coerceRawStatementArgument(), ctx.coerceStatementArgument(),
154             substatements);
155     }
156
157     @Override
158     protected final AugmentStatement createEmptyDeclared(
159             final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx) {
160         return new EmptyAugmentStatement(ctx.coerceRawStatementArgument(), ctx.coerceStatementArgument());
161     }
162
163     @Override
164     protected final List<? extends StmtContext<?, ?, ?>> statementsToBuild(
165             final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
166             final List<? extends StmtContext<?, ?, ?>> substatements) {
167         final StatementContextBase<?, ?, ?> implicitDef = ctx.getFromNamespace(AugmentImplicitHandlingNamespace.class,
168             ctx);
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 StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
178             final AugmentStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
179         final int flags = new FlagsBuilder()
180                 .setStatus(findFirstArgument(substatements, StatusEffectiveStatement.class, Status.CURRENT))
181                 .toFlags();
182
183         return new AugmentEffectiveStatementImpl(declared, ctx.coerceStatementArgument(), flags,
184             StmtContextUtils.getRootModuleQName(ctx), substatements, ctx.getStatementSourceReference(),
185             (AugmentationSchemaNode) ctx.getOriginalCtx().map(StmtContext::buildEffective).orElse(null));
186     }
187
188     @Override
189     protected final AugmentEffectiveStatement createEmptyEffective(
190             final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
191             final AugmentStatement declared) {
192         return createEffective(ctx, declared, ImmutableList.of());
193     }
194
195     private static StmtContext<?, ?, ?> getSearchRoot(final StmtContext<?, ?, ?> augmentContext) {
196         // Augment is in uses - we need to augment instantiated nodes in parent.
197         final StmtContext<?, ?, ?> parent = augmentContext.coerceParentContext();
198         if (YangStmtMapping.USES == parent.getPublicDefinition()) {
199             return parent.getParentContext();
200         }
201         return parent;
202     }
203
204     static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
205             final StatementContextBase<?, ?, ?> targetCtx) {
206         final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
207                 ? CopyType.ADDED_BY_USES_AUGMENTATION : CopyType.ADDED_BY_AUGMENTATION;
208         /*
209          * Since Yang 1.1, if an augmentation is made conditional with a
210          * "when" statement, it is allowed to add mandatory nodes.
211          */
212         final boolean skipCheckOfMandatoryNodes = YangVersion.VERSION_1_1.equals(sourceCtx.getRootVersion())
213                 && isConditionalAugmentStmt(sourceCtx);
214
215         final Collection<? extends Mutable<?, ?, ?>> declared = sourceCtx.mutableDeclaredSubstatements();
216         final Collection<? extends Mutable<?, ?, ?>> effective = sourceCtx.mutableEffectiveSubstatements();
217         final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
218
219         for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
220             if (originalStmtCtx.isSupportedByFeatures()) {
221                 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
222             }
223         }
224         for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
225             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
226         }
227
228         targetCtx.addEffectiveSubstatements(buffer);
229     }
230
231     /**
232      * Checks whether supplied statement context is conditional augment
233      * statement.
234      *
235      * @param ctx
236      *            statement context to be checked
237      *
238      * @return true if supplied statement context is conditional augment
239      *         statement, otherwise false
240      */
241     private static boolean isConditionalAugmentStmt(final StmtContext<?, ?, ?> ctx) {
242         return ctx.getPublicDefinition() == YangStmtMapping.AUGMENT && hasWhenSubstatement(ctx);
243     }
244
245     private static boolean hasWhenSubstatement(final StmtContext<?, ?, ?> ctx) {
246         return ctx.hasSubstatement(WhenEffectiveStatement.class);
247     }
248
249     private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
250             final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
251             final boolean skipCheckOfMandatoryNodes) {
252         if (needToCopyByAugment(original)) {
253             validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
254
255             buffer.add(target.childCopyOf(original, typeOfCopy));
256         } else if (isReusedByAugment(original)) {
257             buffer.add(original);
258         }
259     }
260
261     private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
262             final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
263             final boolean skipCheckOfMandatoryNodes) {
264
265         if (sourceCtx.producesDeclared(WhenStatement.class)) {
266             return;
267         }
268
269         if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
270                 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
271             checkForMandatoryNodes(sourceCtx);
272         }
273
274         // Data definition statements must not collide on their namespace
275         if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
276             for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
277                 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
278                     InferenceException.throwIf(
279                         Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument()),
280                         sourceCtx.getStatementSourceReference(),
281                         "An augment cannot add node named '%s' because this name is already used in target",
282                         sourceCtx.rawStatementArgument());
283                 }
284             }
285         }
286     }
287
288     private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
289         if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
290             /*
291              * We need to iterate over both declared and effective sub-statements,
292              * because a mandatory node can be:
293              * a) declared in augment body
294              * b) added to augment body also via uses of a grouping and
295              * such sub-statements are stored in effective sub-statements collection.
296              */
297             sourceCtx.allSubstatementsStream().forEach(AbstractAugmentStatementSupport::checkForMandatoryNodes);
298         }
299
300         InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
301                 sourceCtx.getStatementSourceReference(),
302                 "An augment cannot add node '%s' because it is mandatory and in module different than target",
303                 sourceCtx.rawStatementArgument());
304     }
305
306     private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
307             Mutable<?, ?, ?> targetCtx) {
308         /*
309          * If the statement argument is not QName, it cannot be mandatory
310          * statement, therefore return false and skip mandatory nodes validation
311          */
312         final Object arg = sourceCtx.getStatementArgument();
313         if (!(arg instanceof QName)) {
314             return false;
315         }
316         final QName sourceStmtQName = (QName) arg;
317
318         // RootStatementContext, for example
319         final Mutable<?, ?, ?> root = targetCtx.getRoot();
320         do {
321             final Object targetArg = targetCtx.getStatementArgument();
322             Verify.verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s",
323                 targetArg);
324             final QName targetStmtQName = (QName) targetArg;
325             /*
326              * If target is from another module, return true and perform mandatory nodes validation
327              */
328             if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
329                 return true;
330             }
331
332             /*
333              * If target or one of the target's ancestors from the same namespace
334              * is a presence container
335              * or is non-mandatory choice
336              * or is non-mandatory list
337              * return false and skip mandatory nodes validation, because these nodes
338              * are not mandatory node containers according to RFC 6020 section 3.1.
339              */
340             if (StmtContextUtils.isPresenceContainer(targetCtx)
341                     || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
342                     || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
343                 return false;
344             }
345
346             // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
347             // conditional -- in which case we do not run further checks
348             if (targetCtx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
349                 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
350                 if (optPrevCopy.isPresent()) {
351                     final StmtContext<?, ?, ?> original = optPrevCopy.get();
352                     final Object origArg = original.coerceStatementArgument();
353                     Verify.verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
354
355                     if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
356                             && hasWhenSubstatement(getParentAugmentation(original))) {
357                         return false;
358                     }
359                 }
360             }
361         } while ((targetCtx = targetCtx.getParentContext()) != root);
362
363         /*
364          * All target node's parents belong to the same module as source node,
365          * therefore return false and skip mandatory nodes validation.
366          */
367         return false;
368     }
369
370     private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
371         StmtContext<?, ?, ?> parent = Verify.verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
372         while (parent.getPublicDefinition() != YangStmtMapping.AUGMENT) {
373             parent = Verify.verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
374         }
375         return parent;
376     }
377
378     private static final ImmutableSet<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES,
379         YangStmtMapping.WHEN, YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
380
381     private static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
382         return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
383     }
384
385     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
386
387     private static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
388         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
389     }
390
391     static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
392         /*
393          * :TODO Substatement must be allowed augment target type e.g.
394          * Container, etc... and must not be for example grouping, identity etc.
395          * It is problem in case when more than one substatements have the same
396          * QName, for example Grouping and Container are siblings and they have
397          * the same QName. We must find the Container and the Grouping must be
398          * ignored as disallowed augment target.
399          */
400         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
401             ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
402
403         // if no allowed target is returned we consider all targets allowed
404         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
405                 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
406     }
407 }