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 com.google.common.base.Verify;
11 import com.google.common.collect.ImmutableSet;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.Objects;
15 import java.util.Optional;
17 import java.util.regex.Pattern;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.common.YangVersion;
20 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
21 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
22 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
25 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.WhenStatement;
27 import org.opendaylight.yangtools.yang.parser.rfc7950.namespace.SchemaNodeIdentifierBuildNamespace;
28 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.ArgumentUtils;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
38 import org.opendaylight.yangtools.yang.parser.spi.source.AugmentToChoiceNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
40 import org.opendaylight.yangtools.yang.parser.spi.source.StmtOrderingNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
42 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
43 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 abstract class AbstractAugmentStatementSupport extends AbstractStatementSupport<SchemaNodeIdentifier, AugmentStatement,
48 EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> {
49 private static final Logger LOG = LoggerFactory.getLogger(AugmentStatementImpl.class);
50 private static final Pattern PATH_REL_PATTERN1 = Pattern.compile("\\.\\.?\\s*/(.+)");
51 private static final Pattern PATH_REL_PATTERN2 = Pattern.compile("//.*");
53 AbstractAugmentStatementSupport() {
54 super(YangStmtMapping.AUGMENT);
58 public final SchemaNodeIdentifier parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
59 SourceException.throwIf(PATH_REL_PATTERN1.matcher(value).matches()
60 || PATH_REL_PATTERN2.matcher(value).matches(), ctx.getStatementSourceReference(),
61 "Augment argument \'%s\' is not valid, it can be only absolute path; or descendant if used in uses",
64 return ArgumentUtils.nodeIdentifierFromPath(ctx, value);
68 public final AugmentStatement createDeclared(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx) {
69 return new AugmentStatementImpl(ctx);
73 public final EffectiveStatement<SchemaNodeIdentifier, AugmentStatement> createEffective(
74 final StmtContext<SchemaNodeIdentifier, AugmentStatement,
75 EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> ctx) {
76 return new AugmentEffectiveStatementImpl(ctx);
80 public final void onFullDefinitionDeclared(final Mutable<SchemaNodeIdentifier, AugmentStatement,
81 EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> augmentNode) {
82 if (!augmentNode.isSupportedByFeatures()) {
86 super.onFullDefinitionDeclared(augmentNode);
88 if (StmtContextUtils.isInExtensionBody(augmentNode)) {
92 final ModelActionBuilder augmentAction = augmentNode.newInferenceAction(
93 ModelProcessingPhase.EFFECTIVE_MODEL);
94 final Prerequisite<StmtContext<SchemaNodeIdentifier, AugmentStatement,
95 EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>>> sourceCtxPrereq =
96 augmentAction.requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
97 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target =
98 augmentAction.mutatesEffectiveCtx(getSearchRoot(augmentNode),
99 SchemaNodeIdentifierBuildNamespace.class, augmentNode.getStatementArgument());
101 augmentAction.apply(new ModelActionBuilder.InferenceAction() {
103 public void apply(final ModelActionBuilder.InferenceContext ctx) {
104 final StatementContextBase<?, ?, ?> augmentTargetCtx =
105 (StatementContextBase<?, ?, ?>) target.resolve(ctx);
106 if (!isSupportedAugmentTarget(augmentTargetCtx)
107 || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
108 augmentNode.setIsSupportedToBuildEffective(false);
112 * Marks case short hand in augment
114 if (augmentTargetCtx.getPublicDefinition() == YangStmtMapping.CHOICE) {
115 augmentNode.addToNs(AugmentToChoiceNamespace.class, augmentNode, Boolean.TRUE);
118 // FIXME: this is a workaround for models which augment a node which is added via an extension
119 // which we do not handle. This needs to be reworked in terms of unknown schema nodes.
120 final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
122 copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
123 augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
124 updateAugmentOrder(augmentSourceCtx);
125 } catch (final SourceException e) {
126 LOG.warn("Failed to add augmentation {} defined at {}",
127 augmentTargetCtx.getStatementSourceReference(),
128 augmentSourceCtx.getStatementSourceReference(), e);
132 private void updateAugmentOrder(final StatementContextBase<?, ?, ?> augmentSourceCtx) {
133 Integer currentOrder = augmentSourceCtx.getFromNamespace(StmtOrderingNamespace.class,
134 YangStmtMapping.AUGMENT);
135 if (currentOrder == null) {
141 augmentSourceCtx.addToNs(StmtOrderingNamespace.class, YangStmtMapping.AUGMENT, currentOrder);
145 public void prerequisiteFailed(final Collection<? extends ModelActionBuilder.Prerequisite<?>> failed) {
147 * Do not fail, if it is an uses-augment to an unknown node.
149 if (YangStmtMapping.USES == augmentNode.getParentContext().getPublicDefinition()) {
150 final Optional<StmtContext<?, ?, ?>> targetNode = SchemaNodeIdentifierBuildNamespace.findNode(
151 getSearchRoot(augmentNode), augmentNode.getStatementArgument());
152 if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
153 augmentNode.setIsSupportedToBuildEffective(false);
155 "Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
156 augmentNode.getStatementArgument(), augmentNode.getStatementSourceReference());
161 throw new InferenceException(augmentNode.getStatementSourceReference(),
162 "Augment target '%s' not found", augmentNode.getStatementArgument());
167 private static StmtContext<?, ?, ?> getSearchRoot(final StmtContext<?, ?, ?> augmentContext) {
168 final StmtContext<?, ?, ?> parent = augmentContext.getParentContext();
169 // Augment is in uses - we need to augment instantiated nodes in parent.
170 if (YangStmtMapping.USES == parent.getPublicDefinition()) {
171 return parent.getParentContext();
176 static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
177 final StatementContextBase<?, ?, ?> targetCtx) {
178 final CopyType typeOfCopy = UsesStatement.class.equals(sourceCtx.getParentContext().getPublicDefinition()
179 .getDeclaredRepresentationClass()) ? CopyType.ADDED_BY_USES_AUGMENTATION
180 : CopyType.ADDED_BY_AUGMENTATION;
182 * Since Yang 1.1, if an augmentation is made conditional with a
183 * "when" statement, it is allowed to add mandatory nodes.
185 final boolean skipCheckOfMandatoryNodes = YangVersion.VERSION_1_1.equals(sourceCtx.getRootVersion())
186 && isConditionalAugmentStmt(sourceCtx);
188 final Collection<? extends Mutable<?, ?, ?>> declared = sourceCtx.mutableDeclaredSubstatements();
189 final Collection<? extends Mutable<?, ?, ?>> effective = sourceCtx.mutableEffectiveSubstatements();
190 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
192 for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
193 if (originalStmtCtx.isSupportedByFeatures()) {
194 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
197 for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
198 copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes);
201 targetCtx.addEffectiveSubstatements(buffer);
205 * Checks whether supplied statement context is conditional augment
209 * statement context to be checked
211 * @return true if supplied statement context is conditional augment
212 * statement, otherwise false
214 private static boolean isConditionalAugmentStmt(final StmtContext<?, ?, ?> ctx) {
215 return ctx.getPublicDefinition() == YangStmtMapping.AUGMENT
216 && StmtContextUtils.findFirstSubstatement(ctx, WhenStatement.class) != null;
219 private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
220 final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
221 final boolean skipCheckOfMandatoryNodes) {
222 if (needToCopyByAugment(original)) {
223 validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
225 buffer.add(target.childCopyOf(original, typeOfCopy));
226 } else if (isReusedByAugment(original)) {
227 buffer.add(original);
231 private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
232 final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
233 final boolean skipCheckOfMandatoryNodes) {
235 if (WhenStatement.class.equals(sourceCtx.getPublicDefinition().getDeclaredRepresentationClass())) {
239 if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
240 && reguiredCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
241 checkForMandatoryNodes(sourceCtx);
244 for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
245 final boolean sourceIsDataNode = DataDefinitionStatement.class.isAssignableFrom(sourceCtx
246 .getPublicDefinition().getDeclaredRepresentationClass());
247 final boolean targetIsDataNode = DataDefinitionStatement.class.isAssignableFrom(subStatement
248 .getPublicDefinition().getDeclaredRepresentationClass());
249 final boolean qNamesEqual = sourceIsDataNode && targetIsDataNode
250 && Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument());
252 InferenceException.throwIf(qNamesEqual, sourceCtx.getStatementSourceReference(),
253 "An augment cannot add node named '%s' because this name is already used in target",
254 sourceCtx.rawStatementArgument());
258 private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
259 if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
261 * We need to iterate over both declared and effective sub-statements,
262 * because a mandatory node can be:
263 * a) declared in augment body
264 * b) added to augment body also via uses of a grouping and
265 * such sub-statements are stored in effective sub-statements collection.
267 sourceCtx.allSubstatementsStream().forEach(AbstractAugmentStatementSupport::checkForMandatoryNodes);
270 InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
271 sourceCtx.getStatementSourceReference(),
272 "An augment cannot add node '%s' because it is mandatory and in module different than target",
273 sourceCtx.rawStatementArgument());
276 private static boolean reguiredCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
277 Mutable<?, ?, ?> targetCtx) {
279 * If the statement argument is not QName, it cannot be mandatory
280 * statement, therefore return false and skip mandatory nodes validation
282 if (!(sourceCtx.getStatementArgument() instanceof QName)) {
285 final QName sourceStmtQName = (QName) sourceCtx.getStatementArgument();
287 // RootStatementContext, for example
288 final Mutable<?, ?, ?> root = targetCtx.getRoot();
290 Verify.verify(targetCtx.getStatementArgument() instanceof QName,
291 "Argument of augment target statement must be QName.");
292 final QName targetStmtQName = (QName) targetCtx.getStatementArgument();
294 * If target is from another module, return true and perform mandatory nodes validation
296 if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
301 * If target or one of the target's ancestors from the same namespace
302 * is a presence container
303 * or is non-mandatory choice
304 * or is non-mandatory list
305 * return false and skip mandatory nodes validation, because these nodes
306 * are not mandatory node containers according to RFC 6020 section 3.1.
308 if (StmtContextUtils.isPresenceContainer(targetCtx)
309 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
310 || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
313 } while ((targetCtx = targetCtx.getParentContext()) != root);
316 * All target node's parents belong to the same module as source node,
317 * therefore return false and skip mandatory nodes validation.
322 private static final Set<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES,
323 YangStmtMapping.WHEN, YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
325 private static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
326 return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
329 private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
331 private static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
332 return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
335 static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
337 * :TODO Substatement must be allowed augment target type e.g.
338 * Container, etc... and must not be for example grouping, identity etc.
339 * It is problem in case when more than one substatements have the same
340 * QName, for example Grouping and Container are siblings and they have
341 * the same QName. We must find the Container and the Grouping must be
342 * ignored as disallowed augment target.
344 final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
345 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
347 // if no allowed target is returned we consider all targets allowed
348 return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
349 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());