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