2 * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.rfc7950.stmt.augment;
10 import static com.google.common.base.Verify.verify;
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.parser.rfc7950.stmt.ArgumentUtils;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
38 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.EffectiveStatementMixins.EffectiveStatementWithFlags.FlagsBuilder;
39 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
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;
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("//.*");
63 AbstractAugmentStatementSupport() {
64 super(YangStmtMapping.AUGMENT);
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",
74 return ArgumentUtils.nodeIdentifierFromPath(ctx, value);
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);
85 super.onFullDefinitionDeclared(augmentNode);
87 if (StmtContextUtils.isInExtensionBody(augmentNode)) {
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,
95 augmentNode.coerceStatementArgument().getNodeIdentifiers());
97 augmentAction.apply(new InferenceAction() {
99 public void apply(final InferenceContext ctx) {
100 if (!augmentNode.isSupportedToBuildEffective()) {
101 // We are not building effective model, hence we should not be performing any effects
105 final StatementContextBase<?, ?, ?> augmentTargetCtx =
106 (StatementContextBase<?, ?, ?>) target.resolve(ctx);
107 if (!isSupportedAugmentTarget(augmentTargetCtx)
108 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
109 augmentNode.setIsSupportedToBuildEffective(false);
113 // We are targeting a context which is creating implicit nodes. In order to keep things consistent,
114 // we will need to circle back when creating effective statements.
115 if (augmentTargetCtx.hasImplicitParentSupport()) {
116 augmentNode.addToNs(AugmentImplicitHandlingNamespace.class, augmentNode, augmentTargetCtx);
119 final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
120 // FIXME: this is a workaround for models which augment a node which is added via an extension
121 // which we do not handle. This needs to be reworked in terms of unknown schema nodes.
123 copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
124 augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
125 } catch (final SourceException e) {
126 LOG.warn("Failed to add augmentation {} defined at {}",
127 augmentTargetCtx.getStatementSourceReference(),
128 augmentSourceCtx.getStatementSourceReference(), e);
133 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
135 * Do not fail, if it is an uses-augment to an unknown node.
137 if (YangStmtMapping.USES == augmentNode.coerceParentContext().getPublicDefinition()) {
138 final SchemaNodeIdentifier augmentArg = augmentNode.coerceStatementArgument();
139 final Optional<StmtContext<?, ?, ?>> targetNode = SchemaTreeNamespace.findNode(
140 getSearchRoot(augmentNode), augmentArg);
141 if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
142 augmentNode.setIsSupportedToBuildEffective(false);
143 LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
144 augmentArg, augmentNode.getStatementSourceReference());
149 throw new InferenceException(augmentNode.getStatementSourceReference(),
150 "Augment target '%s' not found", augmentNode.getStatementArgument());
154 public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
155 if (target.equals(unavail)) {
156 augmentNode.setIsSupportedToBuildEffective(false);
158 prerequisiteFailed(List.of(unavail));
165 protected final AugmentStatement createDeclared(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx,
166 final ImmutableList<? extends DeclaredStatement<?>> substatements) {
167 return new RegularAugmentStatement(ctx.coerceRawStatementArgument(), ctx.coerceStatementArgument(),
172 protected final AugmentStatement createEmptyDeclared(
173 final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx) {
174 return new EmptyAugmentStatement(ctx.coerceRawStatementArgument(), ctx.coerceStatementArgument());
178 protected final List<? extends StmtContext<?, ?, ?>> statementsToBuild(
179 final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
180 final List<? extends StmtContext<?, ?, ?>> substatements) {
181 final StatementContextBase<?, ?, ?> implicitDef = ctx.getFromNamespace(AugmentImplicitHandlingNamespace.class,
183 return implicitDef == null ? substatements : Lists.transform(substatements, subCtx -> {
184 verify(subCtx instanceof StatementContextBase);
185 return implicitDef.wrapWithImplicit((StatementContextBase<?, ?, ?>) subCtx);
190 protected final AugmentEffectiveStatement createEffective(
191 final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
192 final AugmentStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
193 final int flags = new FlagsBuilder()
194 .setStatus(findFirstArgument(substatements, StatusEffectiveStatement.class, Status.CURRENT))
197 return new AugmentEffectiveStatementImpl(declared, ctx.coerceStatementArgument(), flags,
198 StmtContextUtils.getRootModuleQName(ctx), substatements, ctx.getStatementSourceReference(),
199 (AugmentationSchemaNode) ctx.getOriginalCtx().map(StmtContext::buildEffective).orElse(null));
203 protected final AugmentEffectiveStatement createEmptyEffective(
204 final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
205 final AugmentStatement declared) {
206 return createEffective(ctx, declared, ImmutableList.of());
209 private static StmtContext<?, ?, ?> getSearchRoot(final StmtContext<?, ?, ?> augmentContext) {
210 // Augment is in uses - we need to augment instantiated nodes in parent.
211 final StmtContext<?, ?, ?> parent = augmentContext.coerceParentContext();
212 if (YangStmtMapping.USES == parent.getPublicDefinition()) {
213 return parent.getParentContext();
218 static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
219 final StatementContextBase<?, ?, ?> targetCtx) {
220 final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
221 ? CopyType.ADDED_BY_USES_AUGMENTATION : CopyType.ADDED_BY_AUGMENTATION;
223 * Since Yang 1.1, if an augmentation is made conditional with a
224 * "when" statement, it is allowed to add mandatory nodes.
226 final boolean skipCheckOfMandatoryNodes = YangVersion.VERSION_1_1.equals(sourceCtx.getRootVersion())
227 && isConditionalAugmentStmt(sourceCtx);
228 final boolean unsupported = !sourceCtx.isSupportedByFeatures();
230 final Collection<? extends Mutable<?, ?, ?>> declared = sourceCtx.mutableDeclaredSubstatements();
231 final Collection<? extends Mutable<?, ?, ?>> effective = sourceCtx.mutableEffectiveSubstatements();
232 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
234 for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
235 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes,
236 unsupported || !originalStmtCtx.isSupportedByFeatures());
238 for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
239 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes, unsupported);
242 targetCtx.addEffectiveSubstatements(buffer);
246 * Checks whether supplied statement context is conditional augment
250 * statement context to be checked
252 * @return true if supplied statement context is conditional augment
253 * statement, otherwise false
255 private static boolean isConditionalAugmentStmt(final StmtContext<?, ?, ?> ctx) {
256 return ctx.getPublicDefinition() == YangStmtMapping.AUGMENT && hasWhenSubstatement(ctx);
259 private static boolean hasWhenSubstatement(final StmtContext<?, ?, ?> ctx) {
260 return ctx.hasSubstatement(WhenEffectiveStatement.class);
263 private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
264 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
265 final boolean skipCheckOfMandatoryNodes, final boolean unsupported) {
266 // We always copy statements, but if either the source statement or the augmentation which causes it are not
267 // supported to build we also mark the target as such.
268 if (needToCopyByAugment(original)) {
269 validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
271 final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
273 copy.setIsSupportedToBuildEffective(false);
276 } else if (isReusedByAugment(original) && !unsupported) {
277 buffer.add(original);
281 private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
282 final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
283 final boolean skipCheckOfMandatoryNodes) {
284 if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
285 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
286 checkForMandatoryNodes(sourceCtx);
289 // Data definition statements must not collide on their namespace
290 if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
291 for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
292 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
293 InferenceException.throwIf(
294 Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument()),
295 sourceCtx.getStatementSourceReference(),
296 "An augment cannot add node named '%s' because this name is already used in target",
297 sourceCtx.rawStatementArgument());
303 private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
304 if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
306 * We need to iterate over both declared and effective sub-statements,
307 * because a mandatory node can be:
308 * a) declared in augment body
309 * b) added to augment body also via uses of a grouping and
310 * such sub-statements are stored in effective sub-statements collection.
312 sourceCtx.allSubstatementsStream().forEach(AbstractAugmentStatementSupport::checkForMandatoryNodes);
315 InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
316 sourceCtx.getStatementSourceReference(),
317 "An augment cannot add node '%s' because it is mandatory and in module different than target",
318 sourceCtx.rawStatementArgument());
321 private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
322 Mutable<?, ?, ?> targetCtx) {
324 * If the statement argument is not QName, it cannot be mandatory
325 * statement, therefore return false and skip mandatory nodes validation
327 final Object arg = sourceCtx.getStatementArgument();
328 if (!(arg instanceof QName)) {
331 final QName sourceStmtQName = (QName) arg;
333 // RootStatementContext, for example
334 final Mutable<?, ?, ?> root = targetCtx.getRoot();
336 final Object targetArg = targetCtx.getStatementArgument();
337 Verify.verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s",
339 final QName targetStmtQName = (QName) targetArg;
341 * If target is from another module, return true and perform mandatory nodes validation
343 if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
348 * If target or one of the target's ancestors from the same namespace
349 * is a presence container
350 * or is non-mandatory choice
351 * or is non-mandatory list
352 * return false and skip mandatory nodes validation, because these nodes
353 * are not mandatory node containers according to RFC 6020 section 3.1.
355 if (StmtContextUtils.isPresenceContainer(targetCtx)
356 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
357 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
361 // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
362 // conditional -- in which case we do not run further checks
363 if (targetCtx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
364 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
365 if (optPrevCopy.isPresent()) {
366 final StmtContext<?, ?, ?> original = optPrevCopy.get();
367 final Object origArg = original.coerceStatementArgument();
368 Verify.verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
370 if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
371 && hasWhenSubstatement(getParentAugmentation(original))) {
376 } while ((targetCtx = targetCtx.getParentContext()) != root);
379 * All target node's parents belong to the same module as source node,
380 * therefore return false and skip mandatory nodes validation.
385 private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
386 StmtContext<?, ?, ?> parent = Verify.verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
387 while (parent.getPublicDefinition() != YangStmtMapping.AUGMENT) {
388 parent = Verify.verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
393 private static final ImmutableSet<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES,
394 YangStmtMapping.WHEN, YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
396 private static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
397 return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
400 private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
402 private static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
403 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
406 static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
408 * :TODO Substatement must be allowed augment target type e.g.
409 * Container, etc... and must not be for example grouping, identity etc.
410 * It is problem in case when more than one substatements have the same
411 * QName, for example Grouping and Container are siblings and they have
412 * the same QName. We must find the Container and the Grouping must be
413 * ignored as disallowed augment target.
415 final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
416 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
418 // if no allowed target is returned we consider all targets allowed
419 return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
420 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());