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