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.deviate;
10 import com.google.common.collect.ImmutableList;
11 import com.google.common.collect.ImmutableSet;
12 import com.google.common.collect.Iterables;
13 import com.google.common.collect.SetMultimap;
14 import java.util.Collection;
15 import java.util.List;
16 import java.util.Objects;
18 import org.opendaylight.yangtools.yang.common.Empty;
19 import org.opendaylight.yangtools.yang.common.QNameModule;
20 import org.opendaylight.yangtools.yang.common.YangVersion;
21 import org.opendaylight.yangtools.yang.model.api.DeviateKind;
22 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
23 import org.opendaylight.yangtools.yang.model.api.meta.DeclarationReference;
24 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
27 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateEffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
30 import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatementDecorators;
31 import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatements;
32 import org.opendaylight.yangtools.yang.model.ri.stmt.EffectiveStatements;
33 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
34 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
35 import org.opendaylight.yangtools.yang.parser.spi.ParserNamespaces;
36 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.BoundStmtCtx;
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.meta.SubstatementValidator;
51 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 abstract class AbstractDeviateStatementSupport
56 extends AbstractStatementSupport<DeviateKind, DeviateStatement, DeviateEffectiveStatement> {
57 private static final Logger LOG = LoggerFactory.getLogger(AbstractDeviateStatementSupport.class);
59 private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
60 SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
62 private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
63 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
64 .addOptional(YangStmtMapping.CONFIG)
65 .addOptional(YangStmtMapping.DEFAULT)
66 .addOptional(YangStmtMapping.MANDATORY)
67 .addOptional(YangStmtMapping.MAX_ELEMENTS)
68 .addOptional(YangStmtMapping.MIN_ELEMENTS)
69 .addAny(YangStmtMapping.MUST)
70 .addAny(YangStmtMapping.UNIQUE)
71 .addOptional(YangStmtMapping.UNITS)
74 private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
75 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
76 .addOptional(YangStmtMapping.CONFIG)
77 .addOptional(YangStmtMapping.DEFAULT)
78 .addOptional(YangStmtMapping.MANDATORY)
79 .addOptional(YangStmtMapping.MAX_ELEMENTS)
80 .addOptional(YangStmtMapping.MIN_ELEMENTS)
81 .addOptional(YangStmtMapping.TYPE)
82 .addOptional(YangStmtMapping.UNITS)
85 private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
86 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
87 .addOptional(YangStmtMapping.DEFAULT)
88 .addAny(YangStmtMapping.MUST)
89 .addAny(YangStmtMapping.UNIQUE)
90 .addOptional(YangStmtMapping.UNITS)
93 private static final ImmutableSet<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
94 YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
95 YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
97 private static final ImmutableSet<YangStmtMapping> IMPLICIT_STATEMENTS = ImmutableSet.of(YangStmtMapping.CONFIG,
98 YangStmtMapping.MANDATORY, YangStmtMapping.MAX_ELEMENTS, YangStmtMapping.MIN_ELEMENTS);
100 AbstractDeviateStatementSupport(final YangParserConfiguration config) {
101 // Note: we are performing our own validation based on deviate kind.
102 // TODO: perhaps we should do argumentSpecificSupport?
103 super(YangStmtMapping.DEVIATE, StatementPolicy.contextIndependent(), config, null);
107 public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
108 return SourceException.throwIfNull(DeviateKind.forArgument(value), ctx,
109 "String '%s' is not valid deviate argument", value);
113 public final void onFullDefinitionDeclared(
114 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx) {
115 final DeviateKind deviateKind = deviateStmtCtx.argument();
116 getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
118 final SchemaNodeIdentifier deviationTarget =
119 (SchemaNodeIdentifier) deviateStmtCtx.coerceParentContext().argument();
121 if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
125 final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
126 ModelProcessingPhase.EFFECTIVE_MODEL);
128 final Prerequisite<StmtContext<DeviateKind, DeviateStatement,
129 DeviateEffectiveStatement>> sourceCtxPrerequisite =
130 deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
132 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
133 deviateAction.mutatesEffectiveCtxPath(deviateStmtCtx.getRoot(),
134 SchemaTreeNamespace.instance(), deviationTarget.getNodeIdentifiers());
136 deviateAction.apply(new InferenceAction() {
138 public void apply(final InferenceContext ctx) {
139 if (!deviateStmtCtx.isSupportedToBuildEffective()) {
140 // We are not building effective model, hence we should not be performing any effects
144 final var sourceNodeStmtCtx = sourceCtxPrerequisite.resolve(ctx);
145 final var targetNodeStmtCtx = targetCtxPrerequisite.resolve(ctx);
147 switch (deviateKind) {
149 // FIXME: this can be short-circuited without an inference action
150 targetNodeStmtCtx.setUnsupported();
153 performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
156 performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
159 performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
162 throw new IllegalStateException("Unsupported deviate " + deviateKind);
167 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
168 throw new InferenceException(deviateStmtCtx.coerceParentContext(), "Deviation target '%s' not found.",
173 public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
174 if (targetCtxPrerequisite.equals(unavail)) {
175 deviateStmtCtx.setUnsupported();
177 prerequisiteFailed(List.of(unavail));
184 public String internArgument(final String rawArgument) {
185 if ("add".equals(rawArgument)) {
187 } else if ("delete".equals(rawArgument)) {
189 } else if ("replace".equals(rawArgument)) {
191 } else if ("not-supported".equals(rawArgument)) {
192 return "not-supported";
199 protected final DeviateStatement createDeclared(final BoundStmtCtx<DeviateKind> ctx,
200 final ImmutableList<DeclaredStatement<?>> substatements) {
201 return DeclaredStatements.createDeviate(ctx.getArgument(), substatements);
205 protected final DeviateStatement attachDeclarationReference(final DeviateStatement stmt,
206 final DeclarationReference reference) {
207 return DeclaredStatementDecorators.decorateDeviate(stmt, reference);
211 protected final DeviateEffectiveStatement createEffective(final Current<DeviateKind, DeviateStatement> stmt,
212 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
213 return EffectiveStatements.createDeviate(stmt.declared(), substatements);
216 protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
217 switch (deviateKind) {
219 return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
221 return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
223 return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
225 return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
227 throw new IllegalStateException(String.format(
228 "Substatement validator for deviate %s has not been defined.", deviateKind));
232 private static boolean isDeviationSupported(
233 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx,
234 final SchemaNodeIdentifier deviationTarget) {
235 final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
236 ParserNamespaces.MODULES_DEVIATED_BY, Empty.value());
237 if (modulesDeviatedByModules == null) {
241 final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ParserNamespaces.MODULECTX_TO_QNAME,
242 deviateStmtCtx.getRoot());
243 final QNameModule targetModule = Iterables.getLast(deviationTarget.getNodeIdentifiers()).getModule();
245 final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
246 if (deviationModulesSupportedByTargetModule != null) {
247 return deviationModulesSupportedByTargetModule.contains(currentModule);
253 private static void performDeviateAdd(final StmtContext<?, ?, ?> deviateStmtCtx,
254 final Mutable<?, ?, ?> targetCtx) {
255 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
256 validateDeviationTarget(originalStmtCtx, targetCtx);
257 addStatement(originalStmtCtx, targetCtx);
261 private static void addStatement(final StmtContext<?, ?, ?> stmtCtxToBeAdded, final Mutable<?, ?, ?> targetCtx) {
262 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
263 final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.publicDefinition();
264 if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
265 && YangStmtMapping.LEAF.equals(targetCtx.publicDefinition())) {
266 for (StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
267 InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.publicDefinition()),
269 "Deviation cannot add substatement %s to target node %s because it is already defined "
270 + "in target and can appear only once.",
271 stmtToBeAdded.getStatementName(), targetCtx.argument());
276 copyStatement(stmtCtxToBeAdded, targetCtx);
279 private static void performDeviateReplace(final StmtContext<?, ?, ?> deviateStmtCtx,
280 final Mutable<?, ?, ?> targetCtx) {
281 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
282 validateDeviationTarget(originalStmtCtx, targetCtx);
283 replaceStatement(originalStmtCtx, targetCtx);
287 private static void replaceStatement(final StmtContext<?, ?, ?> stmtCtxToBeReplaced,
288 final Mutable<?, ?, ?> targetCtx) {
289 final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.publicDefinition();
291 if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
292 && YangStmtMapping.LEAF_LIST.equals(targetCtx.publicDefinition())) {
293 LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can "
294 + "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
295 targetCtx.argument(), stmtCtxToBeReplaced.sourceReference());
299 for (StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
300 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
301 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
302 copyStatement(stmtCtxToBeReplaced, targetCtx);
307 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
308 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
309 targetCtxSubstatement.setUnsupported();
310 copyStatement(stmtCtxToBeReplaced, targetCtx);
315 // This is a special case when deviate replace of a config/mandatory/max/min-elements substatement targets
316 // a node which does not contain an explicitly declared config/mandatory/max/min-elements.
317 // However, according to RFC6020/RFC7950, these properties are always implicitly present.
318 if (IMPLICIT_STATEMENTS.contains(stmtToBeReplaced)) {
319 addStatement(stmtCtxToBeReplaced, targetCtx);
323 throw new InferenceException(stmtCtxToBeReplaced,
324 "Deviation cannot replace substatement %s in target node %s because it does not exist in target node.",
325 stmtToBeReplaced.getStatementName(), targetCtx.argument());
328 private static void performDeviateDelete(final StmtContext<?, ?, ?> deviateStmtCtx,
329 final Mutable<?, ?, ?> targetCtx) {
330 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
331 validateDeviationTarget(originalStmtCtx, targetCtx);
332 deleteStatement(originalStmtCtx, targetCtx);
336 private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
337 final Mutable<?, ?, ?> targetCtx) {
338 final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.publicDefinition();
339 final String stmtArgument = stmtCtxToBeDeleted.rawArgument();
341 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
342 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
343 targetCtxSubstatement.rawArgument())) {
344 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
349 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
350 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
351 targetCtxSubstatement.rawArgument())) {
352 targetCtxSubstatement.setUnsupported();
357 LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does "
358 + "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
359 targetCtx.argument(), stmtCtxToBeDeleted.sourceReference());
362 private static void copyStatement(final StmtContext<?, ?, ?> stmtCtxToBeCopied, final Mutable<?, ?, ?> targetCtx) {
363 // we need to make a copy of the statement context only if it is an unknown statement, otherwise
364 // we can reuse the original statement context
365 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeCopied)) {
366 // FIXME: I think this should be handled by the corresponding support's copy policy
367 targetCtx.addEffectiveSubstatement(stmtCtxToBeCopied.replicaAsChildOf(targetCtx));
369 targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeCopied, CopyType.ORIGINAL));
373 private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
374 final StatementDefinition secondStmtDef, final String secondStmtArg) {
375 return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
378 private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
379 final StmtContext<?, ?, ?> targetCtx) {
380 InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
381 targetCtx.yangVersion()), deviateSubStmtCtx,
382 "%s is not a valid deviation target for substatement %s.", targetCtx.argument(),
383 deviateSubStmtCtx.publicDefinition().getStatementName());
386 private static boolean isSupportedDeviationTarget(final StmtContext<?, ?, ?> deviateSubstatementCtx,
387 final StmtContext<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
388 Set<StatementDefinition> supportedDeviationTargets =
389 YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(yangVersion,
390 deviateSubstatementCtx.publicDefinition());
392 if (supportedDeviationTargets == null) {
393 supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
394 deviateSubstatementCtx.publicDefinition());
397 // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
398 return supportedDeviationTargets == null || supportedDeviationTargets.contains(
399 deviateTargetCtx.publicDefinition());