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