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.Verify;
11 import com.google.common.collect.ImmutableSet;
12 import com.google.common.collect.Iterables;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Objects;
17 import java.util.regex.Pattern;
18 import javax.annotation.Nonnull;
19 import org.opendaylight.yangtools.yang.common.QName;
20 import org.opendaylight.yangtools.yang.common.YangVersion;
21 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
22 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.ActionStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.NotificationStatement;
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.meta.AbstractDeclaredStatement;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
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.StatementContextBase;
47 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.AugmentEffectiveStatementImpl;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 public class AugmentStatementImpl extends AbstractDeclaredStatement<SchemaNodeIdentifier> implements AugmentStatement {
52 private static final Logger LOG = LoggerFactory.getLogger(AugmentStatementImpl.class);
53 private static final Pattern PATH_REL_PATTERN1 = Pattern.compile("\\.\\.?\\s*/(.+)");
54 private static final Pattern PATH_REL_PATTERN2 = Pattern.compile("//.*");
55 private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator
56 .builder(YangStmtMapping.AUGMENT)
57 .addAny(YangStmtMapping.ANYXML)
58 .addAny(YangStmtMapping.CASE)
59 .addAny(YangStmtMapping.CHOICE)
60 .addAny(YangStmtMapping.CONTAINER)
61 .addOptional(YangStmtMapping.DESCRIPTION)
62 .addAny(YangStmtMapping.IF_FEATURE)
63 .addAny(YangStmtMapping.LEAF)
64 .addAny(YangStmtMapping.LEAF_LIST)
65 .addAny(YangStmtMapping.LIST)
66 .addOptional(YangStmtMapping.REFERENCE)
67 .addOptional(YangStmtMapping.STATUS)
68 .addAny(YangStmtMapping.USES)
69 .addOptional(YangStmtMapping.WHEN)
72 protected AugmentStatementImpl(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> context) {
76 public static class Definition extends
77 AbstractStatementSupport<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> {
80 super(YangStmtMapping.AUGMENT);
84 public SchemaNodeIdentifier parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
85 SourceException.throwIf(PATH_REL_PATTERN1.matcher(value).matches()
86 || PATH_REL_PATTERN2.matcher(value).matches(), ctx.getStatementSourceReference(),
87 "Augment argument \'%s\' is not valid, it 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 Mutable<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> augmentNode) {
108 if (!augmentNode.isSupportedByFeatures()) {
112 super.onFullDefinitionDeclared(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(final ModelActionBuilder.InferenceContext ctx) {
128 final StatementContextBase<?, ?, ?> augmentTargetCtx =
129 (StatementContextBase<?, ?, ?>) target.resolve(ctx);
130 if (!isSupportedAugmentTarget(augmentTargetCtx)
131 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
132 augmentNode.setIsSupportedToBuildEffective(false);
136 * Marks case short hand in augment
138 if (augmentTargetCtx.getPublicDefinition() == YangStmtMapping.CHOICE) {
139 augmentNode.addToNs(AugmentToChoiceNamespace.class, augmentNode, Boolean.TRUE);
142 // FIXME: this is a workaround for models which augment a node which is added via an extension
143 // which we do not handle. This needs to be reworked in terms of unknown schema nodes.
144 final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
146 copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
147 augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
148 updateAugmentOrder(augmentSourceCtx);
149 } catch (final SourceException e) {
150 LOG.warn("Failed to add augmentation {} defined at {}",
151 augmentTargetCtx.getStatementSourceReference(),
152 augmentSourceCtx.getStatementSourceReference(), e);
156 private void updateAugmentOrder(final StatementContextBase<?, ?, ?> augmentSourceCtx) {
157 Integer currentOrder = augmentSourceCtx.getFromNamespace(StmtOrderingNamespace.class,
158 YangStmtMapping.AUGMENT);
159 if (currentOrder == null) {
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 (targetNode != null && StmtContextUtils.isUnknownStatement(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 * Since Yang 1.1, if an augmentation is made conditional with a
207 * "when" statement, it is allowed to add mandatory nodes.
209 final boolean skipCheckOfMandatoryNodes = YangVersion.VERSION_1_1.equals(sourceCtx.getRootVersion())
210 && isConditionalAugmentStmt(sourceCtx);
212 final Collection<? extends Mutable<?, ?, ?>> declared = sourceCtx.mutableDeclaredSubstatements();
213 final Collection<? extends Mutable<?, ?, ?>> effective = sourceCtx.mutableEffectiveSubstatements();
214 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
216 for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
217 if (originalStmtCtx.isSupportedByFeatures()) {
218 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
221 for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
222 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
225 targetCtx.addEffectiveSubstatements(buffer);
229 * Checks whether supplied statement context is conditional augment
233 * statement context to be checked
235 * @return true if supplied statement context is conditional augment
236 * statement, otherwise false
238 private static boolean isConditionalAugmentStmt(final StmtContext<?, ?, ?> ctx) {
239 return ctx.getPublicDefinition() == YangStmtMapping.AUGMENT
240 && StmtContextUtils.findFirstSubstatement(ctx, WhenStatement.class) != null;
243 private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
244 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
245 final boolean skipCheckOfMandatoryNodes) {
246 if (needToCopyByAugment(original)) {
247 validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
249 final Mutable<?, ?, ?> copy = original.createCopy(target, typeOfCopy);
251 } else if (isReusedByAugment(original)) {
252 buffer.add(original);
256 private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
257 final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
258 final boolean skipCheckOfMandatoryNodes) {
260 if (WhenStatement.class.equals(sourceCtx.getPublicDefinition().getDeclaredRepresentationClass())) {
264 if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
265 && reguiredCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
266 checkForMandatoryNodes(sourceCtx);
269 // Data definition statements must not collide on their namespace
270 if (DataDefinitionStatement.class.isAssignableFrom(
271 sourceCtx.getPublicDefinition().getDeclaredRepresentationClass())) {
272 final Iterable<Mutable<?, ?, ?>> targetSubStatements = Iterables.concat(
273 targetCtx.mutableDeclaredSubstatements(), targetCtx.mutableEffectiveSubstatements());
274 for (final StmtContext<?, ?, ?> subStatement : targetSubStatements) {
275 if (DataDefinitionStatement.class.isAssignableFrom(
276 subStatement.getPublicDefinition().getDeclaredRepresentationClass())) {
278 InferenceException.throwIf(
279 Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument()),
280 sourceCtx.getStatementSourceReference(),
281 "An augment cannot add node named '%s' because this name is already used in target",
282 sourceCtx.rawStatementArgument());
288 private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
289 if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
291 * We need to iterate over both declared and effective sub-statements,
292 * because a mandatory node can be:
293 * a) declared in augment body
294 * b) added to augment body also via uses of a grouping and
295 * such sub-statements are stored in effective sub-statements collection.
297 sourceCtx.declaredSubstatements().forEach(Definition::checkForMandatoryNodes);
298 sourceCtx.effectiveSubstatements().forEach(Definition::checkForMandatoryNodes);
301 InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
302 sourceCtx.getStatementSourceReference(),
303 "An augment cannot add node '%s' because it is mandatory and in module different than target",
304 sourceCtx.rawStatementArgument());
307 private static boolean reguiredCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
308 Mutable<?, ?, ?> targetCtx) {
310 * If the statement argument is not QName, it cannot be mandatory
311 * statement, therefore return false and skip mandatory nodes validation
313 if (!(sourceCtx.getStatementArgument() instanceof QName)) {
316 final QName sourceStmtQName = (QName) sourceCtx.getStatementArgument();
318 // RootStatementContext, for example
319 final Mutable<?, ?, ?> root = targetCtx.getRoot();
321 Verify.verify(targetCtx.getStatementArgument() instanceof QName,
322 "Argument of augment target statement must be QName.");
323 final QName targetStmtQName = (QName) targetCtx.getStatementArgument();
325 * If target is from another module, return true and perform
326 * mandatory nodes validation
328 if (!Utils.belongsToTheSameModule(targetStmtQName, sourceStmtQName)) {
333 * If target or one of the target's ancestors from the same namespace
334 * is a presence container
335 * or is non-mandatory choice
336 * or is non-mandatory list
337 * return false and skip mandatory nodes validation, because these nodes
338 * are not mandatory node containers according to RFC 6020 section 3.1.
340 if (StmtContextUtils.isPresenceContainer(targetCtx)
341 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
342 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
345 } while ((targetCtx = targetCtx.getParentContext()) != root);
348 * All target node's parents belong to the same module as source node,
349 * therefore return false and skip mandatory nodes validation.
354 private static final Set<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES, YangStmtMapping.WHEN,
355 YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
357 public static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
358 return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
361 private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
363 public static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
364 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
367 static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
369 * :TODO Substatement must be allowed augment target type e.g.
370 * Container, etc... and must not be for example grouping, identity etc.
371 * It is problem in case when more than one substatements have the same
372 * QName, for example Grouping and Container are siblings and they have
373 * the same QName. We must find the Container and the Grouping must be
374 * ignored as disallowed augment target.
376 final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
377 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
379 // if no allowed target is returned we consider all targets allowed
380 return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
381 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
385 protected SubstatementValidator getSubstatementValidator() {
386 return SUBSTATEMENT_VALIDATOR;
392 public SchemaNodeIdentifier getTargetNode() {
398 public Collection<? extends DataDefinitionStatement> getDataDefinitions() {
399 return allDeclared(DataDefinitionStatement.class);
404 public Collection<? extends ActionStatement> getActions() {
405 return allDeclared(ActionStatement.class);
409 public final Collection<? extends NotificationStatement> getNotifications() {
410 return allDeclared(NotificationStatement.class);