2 * Copyright (c) 2015 Cisco Systems, Inc. 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.stmt.rfc6020;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.collect.ImmutableList.Builder;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.collect.Iterables;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.List;
18 import java.util.Objects;
20 import java.util.regex.Pattern;
21 import javax.annotation.Nonnull;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
24 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
28 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.WhenStatement;
30 import org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractDeclaredStatement;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
41 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
42 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
43 import org.opendaylight.yangtools.yang.parser.spi.source.StmtOrderingNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
45 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
46 import org.opendaylight.yangtools.yang.parser.stmt.reactor.RootStatementContext;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
48 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.AugmentEffectiveStatementImpl;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 public class AugmentStatementImpl extends AbstractDeclaredStatement<SchemaNodeIdentifier> implements AugmentStatement {
53 private static final Logger LOG = LoggerFactory.getLogger(AugmentStatementImpl.class);
54 private static final Pattern PATH_REL_PATTERN1 = Pattern.compile("\\.\\.?\\s*/(.+)");
55 private static final Pattern PATH_REL_PATTERN2 = Pattern.compile("//.*");
56 private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator
57 .builder(YangStmtMapping.AUGMENT)
58 .addAny(YangStmtMapping.ANYXML)
59 .addAny(YangStmtMapping.CASE)
60 .addAny(YangStmtMapping.CHOICE)
61 .addAny(YangStmtMapping.CONTAINER)
62 .addOptional(YangStmtMapping.DESCRIPTION)
63 .addAny(YangStmtMapping.IF_FEATURE)
64 .addAny(YangStmtMapping.LEAF)
65 .addAny(YangStmtMapping.LEAF_LIST)
66 .addAny(YangStmtMapping.LIST)
67 .addOptional(YangStmtMapping.REFERENCE)
68 .addOptional(YangStmtMapping.STATUS)
69 .addAny(YangStmtMapping.USES)
70 .addOptional(YangStmtMapping.WHEN)
73 protected AugmentStatementImpl(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> context) {
77 public static class Definition extends
78 AbstractStatementSupport<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> {
81 super(YangStmtMapping.AUGMENT);
85 public SchemaNodeIdentifier parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
86 Preconditions.checkArgument(!PATH_REL_PATTERN1.matcher(value).matches()
87 && !PATH_REL_PATTERN2.matcher(value).matches(),
88 "An argument for augment can be only absolute path; or descendant if used in uses");
90 return Utils.nodeIdentifierFromPath(ctx, value);
94 public AugmentStatement createDeclared(
95 final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx) {
96 return new AugmentStatementImpl(ctx);
100 public EffectiveStatement<SchemaNodeIdentifier, AugmentStatement> createEffective(
101 final StmtContext<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> ctx) {
102 return new AugmentEffectiveStatementImpl(ctx);
106 public void onFullDefinitionDeclared(
107 final StmtContext.Mutable<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> augmentNode) {
108 if (!StmtContextUtils.areFeaturesSupported(augmentNode)) {
112 SUBSTATEMENT_VALIDATOR.validate(augmentNode);
114 if (StmtContextUtils.isInExtensionBody(augmentNode)) {
118 final ModelActionBuilder augmentAction = augmentNode.newInferenceAction(
119 ModelProcessingPhase.EFFECTIVE_MODEL);
120 final ModelActionBuilder.Prerequisite<StmtContext<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>>> sourceCtxPrereq =
121 augmentAction.requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
122 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target =
123 augmentAction.mutatesEffectiveCtx(getSearchRoot(augmentNode), SchemaNodeIdentifierBuildNamespace.class, augmentNode.getStatementArgument());
124 augmentAction.apply(new ModelActionBuilder.InferenceAction() {
127 public void apply() {
128 final StatementContextBase<?, ?, ?> augmentTargetCtx = (StatementContextBase<?, ?, ?>) target.get();
129 if (!isSupportedAugmentTarget(augmentTargetCtx)
130 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
131 augmentNode.setIsSupportedToBuildEffective(false);
135 * Marks case short hand in augment
137 if (augmentTargetCtx.getPublicDefinition() == YangStmtMapping.CHOICE) {
138 augmentNode.addToNs(AugmentToChoiceNamespace.class, augmentNode, Boolean.TRUE);
141 // FIXME: this is a workaround for models which augment a node which is added via an extension
142 // which we do not handle. This needs to be reworked in terms of unknown schema nodes.
143 final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
145 copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
146 augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
147 updateAugmentOrder(augmentSourceCtx);
148 } catch (final SourceException e) {
149 LOG.debug("Failed to add augmentation {} defined at {}",
150 augmentTargetCtx.getStatementSourceReference(),
151 augmentSourceCtx.getStatementSourceReference(), e);
155 private void updateAugmentOrder(final StatementContextBase<?, ?, ?> augmentSourceCtx) {
156 Integer currentOrder = augmentSourceCtx.getFromNamespace(StmtOrderingNamespace.class,
157 YangStmtMapping.AUGMENT);
158 if (currentOrder == null) {
164 augmentSourceCtx.setOrder(currentOrder);
165 augmentSourceCtx.addToNs(StmtOrderingNamespace.class, YangStmtMapping.AUGMENT, currentOrder);
169 public void prerequisiteFailed(final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed) {
171 * Do not fail, if it is an uses-augment to an unknown node.
173 if (YangStmtMapping.USES == augmentNode.getParentContext().getPublicDefinition()) {
174 final StatementContextBase<?, ?, ?> targetNode = Utils.findNode(getSearchRoot(augmentNode),
175 augmentNode.getStatementArgument());
176 if (Utils.isUnknownNode(targetNode)) {
177 augmentNode.setIsSupportedToBuildEffective(false);
179 "Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
180 augmentNode.getStatementArgument(), augmentNode.getStatementSourceReference());
185 throw new InferenceException(augmentNode.getStatementSourceReference(),
186 "Augment target '%s' not found", augmentNode.getStatementArgument());
191 private static Mutable<?, ?, ?> getSearchRoot(final Mutable<?, ?, ?> augmentContext) {
192 final Mutable<?, ?, ?> parent = augmentContext.getParentContext();
193 // Augment is in uses - we need to augment instantiated nodes in parent.
194 if (YangStmtMapping.USES == parent.getPublicDefinition()) {
195 return parent.getParentContext();
200 public static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
201 final StatementContextBase<?, ?, ?> targetCtx) {
202 final CopyType typeOfCopy = UsesStatement.class.equals(sourceCtx.getParentContext().getPublicDefinition()
203 .getDeclaredRepresentationClass()) ? CopyType.ADDED_BY_USES_AUGMENTATION
204 : CopyType.ADDED_BY_AUGMENTATION;
206 final Collection<StatementContextBase<?, ?, ?>> declared = sourceCtx.declaredSubstatements();
207 final Collection<StatementContextBase<?, ?, ?>> effective = sourceCtx.effectiveSubstatements();
208 final Collection<StatementContextBase<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
210 for (final StatementContextBase<?, ?, ?> originalStmtCtx : declared) {
211 if (StmtContextUtils.areFeaturesSupported(originalStmtCtx)) {
212 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer);
215 for (final StatementContextBase<?, ?, ?> originalStmtCtx : effective) {
216 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer);
219 targetCtx.addEffectiveSubstatements(buffer);
222 private static void copyStatement(final StatementContextBase<?, ?, ?> original,
223 final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
224 final Collection<StatementContextBase<?, ?, ?>> buffer) {
225 if (needToCopyByAugment(original)) {
226 validateNodeCanBeCopiedByAugment(original, target, typeOfCopy);
228 final StatementContextBase<?, ?, ?> copy = original.createCopy(target, typeOfCopy);
230 } else if (isReusedByAugment(original)) {
231 buffer.add(original);
235 private static void validateNodeCanBeCopiedByAugment(final StatementContextBase<?, ?, ?> sourceCtx,
236 final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy) {
238 if (WhenStatement.class.equals(sourceCtx.getPublicDefinition().getDeclaredRepresentationClass())) {
242 if (typeOfCopy == CopyType.ADDED_BY_AUGMENTATION && reguiredCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
243 checkForMandatoryNodes(sourceCtx);
246 final List<StatementContextBase<?, ?, ?>> targetSubStatements = new Builder<StatementContextBase<?, ?, ?>>()
247 .addAll(targetCtx.declaredSubstatements()).addAll(targetCtx.effectiveSubstatements()).build();
249 for (final StatementContextBase<?, ?, ?> subStatement : targetSubStatements) {
251 final boolean sourceIsDataNode = DataDefinitionStatement.class.isAssignableFrom(sourceCtx
252 .getPublicDefinition().getDeclaredRepresentationClass());
253 final boolean targetIsDataNode = DataDefinitionStatement.class.isAssignableFrom(subStatement
254 .getPublicDefinition().getDeclaredRepresentationClass());
255 final boolean qNamesEqual = sourceIsDataNode && targetIsDataNode
256 && Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument());
258 InferenceException.throwIf(qNamesEqual, sourceCtx.getStatementSourceReference(),
259 "An augment cannot add node named '%s' because this name is already used in target",
260 sourceCtx.rawStatementArgument());
264 private static void checkForMandatoryNodes(final StatementContextBase<?, ?, ?> sourceCtx) {
265 if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
267 * We need to iterate over both declared and effective sub-statements,
268 * because a mandatory node can be:
269 * a) declared in augment body
270 * b) added to augment body also via uses of a grouping and
271 * such sub-statements are stored in effective sub-statements collection.
273 for (final StatementContextBase<?, ?, ?> sourceSubStatement : Iterables.concat(
274 sourceCtx.declaredSubstatements(), sourceCtx.declaredSubstatements())) {
275 checkForMandatoryNodes(sourceSubStatement);
279 InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
280 sourceCtx.getStatementSourceReference(),
281 "An augment cannot add node '%s' because it is mandatory and in module different than target",
282 sourceCtx.rawStatementArgument());
285 private static boolean reguiredCheckOfMandatoryNodes(final StatementContextBase<?, ?, ?> sourceCtx,
286 StatementContextBase<?, ?, ?> targetCtx) {
288 * If the statement argument is not QName, it cannot be mandatory
289 * statement, therefore return false and skip mandatory nodes validation
291 if (!(sourceCtx.getStatementArgument() instanceof QName)) {
294 final QName sourceStmtQName = (QName) sourceCtx.getStatementArgument();
296 final RootStatementContext<?, ?, ?> root = targetCtx.getRoot();
298 Verify.verify(targetCtx.getStatementArgument() instanceof QName,
299 "Argument of augment target statement must be QName.");
300 final QName targetStmtQName = (QName) targetCtx.getStatementArgument();
302 * If target is from another module, return true and perform
303 * mandatory nodes validation
305 if (!Utils.belongsToTheSameModule(targetStmtQName, sourceStmtQName)) {
310 * If target or one of its parent is a presence container from
311 * the same module, return false and skip mandatory nodes
314 if (StmtContextUtils.isPresenceContainer(targetCtx)) {
317 } while ((targetCtx = targetCtx.getParentContext()) != root);
320 * All target node's parents belong to the same module as source node,
321 * therefore return false and skip mandatory nodes validation.
326 private static final Set<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES, YangStmtMapping.WHEN,
327 YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
329 public static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
330 return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
333 private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
335 public static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
336 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
339 static boolean isSupportedAugmentTarget(final StatementContextBase<?, ?, ?> substatementCtx) {
342 * :TODO Substatement must be allowed augment target type e.g.
343 * Container, etc... and must not be for example grouping, identity etc.
344 * It is problem in case when more than one substatements have the same
345 * QName, for example Grouping and Container are siblings and they have
346 * the same QName. We must find the Container and the Grouping must be
347 * ignored as disallowed augment target.
350 final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(ValidationBundlesNamespace.class,
351 ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
353 // if no allowed target is returned we consider all targets allowed
354 return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
355 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
362 public SchemaNodeIdentifier getTargetNode() {
368 public Collection<? extends DataDefinitionStatement> getDataDefinitions() {
369 return allDeclared(DataDefinitionStatement.class);