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.ImmutableMap;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.collect.Iterables;
14 import com.google.common.collect.Maps;
15 import com.google.common.collect.SetMultimap;
16 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.Objects;
21 import org.opendaylight.yangtools.yang.common.Empty;
22 import org.opendaylight.yangtools.yang.common.QNameModule;
23 import org.opendaylight.yangtools.yang.common.YangVersion;
24 import org.opendaylight.yangtools.yang.model.api.DeviateKind;
25 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
26 import org.opendaylight.yangtools.yang.model.api.meta.DeclarationReference;
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.meta.StatementDefinition;
30 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateEffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
33 import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatementDecorators;
34 import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatements;
35 import org.opendaylight.yangtools.yang.model.ri.stmt.EffectiveStatements;
36 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
38 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.BoundStmtCtx;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
54 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
55 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 abstract class AbstractDeviateStatementSupport
60 extends AbstractStatementSupport<DeviateKind, DeviateStatement, DeviateEffectiveStatement> {
61 private static final Logger LOG = LoggerFactory.getLogger(AbstractDeviateStatementSupport.class);
63 private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
64 SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
66 private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
67 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
68 .addOptional(YangStmtMapping.CONFIG)
69 .addOptional(YangStmtMapping.DEFAULT)
70 .addOptional(YangStmtMapping.MANDATORY)
71 .addOptional(YangStmtMapping.MAX_ELEMENTS)
72 .addOptional(YangStmtMapping.MIN_ELEMENTS)
73 .addAny(YangStmtMapping.MUST)
74 .addAny(YangStmtMapping.UNIQUE)
75 .addOptional(YangStmtMapping.UNITS)
78 private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
79 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
80 .addOptional(YangStmtMapping.CONFIG)
81 .addOptional(YangStmtMapping.DEFAULT)
82 .addOptional(YangStmtMapping.MANDATORY)
83 .addOptional(YangStmtMapping.MAX_ELEMENTS)
84 .addOptional(YangStmtMapping.MIN_ELEMENTS)
85 .addOptional(YangStmtMapping.TYPE)
86 .addOptional(YangStmtMapping.UNITS)
89 private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
90 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
91 .addOptional(YangStmtMapping.DEFAULT)
92 .addAny(YangStmtMapping.MUST)
93 .addAny(YangStmtMapping.UNIQUE)
94 .addOptional(YangStmtMapping.UNITS)
97 private static final ImmutableMap<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP =
98 Maps.uniqueIndex(Arrays.asList(DeviateKind.values()), DeviateKind::getKeyword);
100 private static final ImmutableSet<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
101 YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
102 YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
104 private static final ImmutableSet<YangStmtMapping> IMPLICIT_STATEMENTS = ImmutableSet.of(YangStmtMapping.CONFIG,
105 YangStmtMapping.MANDATORY, YangStmtMapping.MAX_ELEMENTS, YangStmtMapping.MIN_ELEMENTS);
107 AbstractDeviateStatementSupport(final YangParserConfiguration config) {
108 // Note: we are performing our own validation based on deviate kind.
109 // TODO: perhaps we should do argumentSpecificSupport?
110 super(YangStmtMapping.DEVIATE, StatementPolicy.contextIndependent(), config, null);
114 public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
115 return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value), ctx,
116 "String '%s' is not valid deviate argument", value);
120 public final void onFullDefinitionDeclared(
121 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx) {
122 final DeviateKind deviateKind = deviateStmtCtx.argument();
123 getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
125 final SchemaNodeIdentifier deviationTarget =
126 (SchemaNodeIdentifier) deviateStmtCtx.coerceParentContext().argument();
128 if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
132 final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
133 ModelProcessingPhase.EFFECTIVE_MODEL);
135 final Prerequisite<StmtContext<DeviateKind, DeviateStatement,
136 DeviateEffectiveStatement>> sourceCtxPrerequisite =
137 deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
139 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
140 deviateAction.mutatesEffectiveCtxPath(deviateStmtCtx.getRoot(),
141 SchemaTreeNamespace.class, deviationTarget.getNodeIdentifiers());
143 deviateAction.apply(new InferenceAction() {
145 public void apply(final InferenceContext ctx) {
146 final var sourceNodeStmtCtx = sourceCtxPrerequisite.resolve(ctx);
147 final var targetNodeStmtCtx = targetCtxPrerequisite.resolve(ctx);
149 switch (deviateKind) {
151 // FIXME: this can be short-circuited without an inference action
152 targetNodeStmtCtx.setUnsupported();
155 performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
158 performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
161 performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
164 throw new IllegalStateException("Unsupported deviate " + deviateKind);
169 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
170 throw new InferenceException(deviateStmtCtx.coerceParentContext(), "Deviation target '%s' not found.",
177 public String internArgument(final String rawArgument) {
178 if ("add".equals(rawArgument)) {
180 } else if ("delete".equals(rawArgument)) {
182 } else if ("replace".equals(rawArgument)) {
184 } else if ("not-supported".equals(rawArgument)) {
185 return "not-supported";
192 protected final DeviateStatement createDeclared(final BoundStmtCtx<DeviateKind> ctx,
193 final ImmutableList<DeclaredStatement<?>> substatements) {
194 return DeclaredStatements.createDeviate(ctx.getArgument(), substatements);
198 protected final DeviateStatement attachDeclarationReference(final DeviateStatement stmt,
199 final DeclarationReference reference) {
200 return DeclaredStatementDecorators.decorateDeviate(stmt, reference);
204 protected final DeviateEffectiveStatement createEffective(final Current<DeviateKind, DeviateStatement> stmt,
205 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
206 return EffectiveStatements.createDeviate(stmt.declared(), substatements);
209 protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
210 switch (deviateKind) {
212 return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
214 return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
216 return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
218 return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
220 throw new IllegalStateException(String.format(
221 "Substatement validator for deviate %s has not been defined.", deviateKind));
225 private static boolean isDeviationSupported(
226 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx,
227 final SchemaNodeIdentifier deviationTarget) {
228 final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
229 ModulesDeviatedByModules.class, Empty.value());
230 if (modulesDeviatedByModules == null) {
234 final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ModuleCtxToModuleQName.class,
235 deviateStmtCtx.getRoot());
236 final QNameModule targetModule = Iterables.getLast(deviationTarget.getNodeIdentifiers()).getModule();
238 final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
239 if (deviationModulesSupportedByTargetModule != null) {
240 return deviationModulesSupportedByTargetModule.contains(currentModule);
246 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
247 justification = "https://github.com/spotbugs/spotbugs/issues/811")
248 private static void performDeviateAdd(final StmtContext<?, ?, ?> deviateStmtCtx,
249 final Mutable<?, ?, ?> targetCtx) {
250 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
251 validateDeviationTarget(originalStmtCtx, targetCtx);
252 addStatement(originalStmtCtx, targetCtx);
256 private static void addStatement(final StmtContext<?, ?, ?> stmtCtxToBeAdded, final Mutable<?, ?, ?> targetCtx) {
257 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
258 final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.publicDefinition();
259 if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
260 && YangStmtMapping.LEAF.equals(targetCtx.publicDefinition())) {
261 for (StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
262 InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.publicDefinition()),
264 "Deviation cannot add substatement %s to target node %s because it is already defined "
265 + "in target and can appear only once.",
266 stmtToBeAdded.getStatementName(), targetCtx.argument());
271 copyStatement(stmtCtxToBeAdded, targetCtx);
274 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
275 justification = "https://github.com/spotbugs/spotbugs/issues/811")
276 private static void performDeviateReplace(final StmtContext<?, ?, ?> deviateStmtCtx,
277 final Mutable<?, ?, ?> targetCtx) {
278 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
279 validateDeviationTarget(originalStmtCtx, targetCtx);
280 replaceStatement(originalStmtCtx, targetCtx);
284 private static void replaceStatement(final StmtContext<?, ?, ?> stmtCtxToBeReplaced,
285 final Mutable<?, ?, ?> targetCtx) {
286 final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.publicDefinition();
288 if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
289 && YangStmtMapping.LEAF_LIST.equals(targetCtx.publicDefinition())) {
290 LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can "
291 + "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
292 targetCtx.argument(), stmtCtxToBeReplaced.sourceReference());
296 for (StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
297 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
298 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
299 copyStatement(stmtCtxToBeReplaced, targetCtx);
304 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
305 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
306 targetCtxSubstatement.setUnsupported();
307 copyStatement(stmtCtxToBeReplaced, targetCtx);
312 // This is a special case when deviate replace of a config/mandatory/max/min-elements substatement targets
313 // a node which does not contain an explicitly declared config/mandatory/max/min-elements.
314 // However, according to RFC6020/RFC7950, these properties are always implicitly present.
315 if (IMPLICIT_STATEMENTS.contains(stmtToBeReplaced)) {
316 addStatement(stmtCtxToBeReplaced, targetCtx);
320 throw new InferenceException(stmtCtxToBeReplaced,
321 "Deviation cannot replace substatement %s in target node %s because it does not exist in target node.",
322 stmtToBeReplaced.getStatementName(), targetCtx.argument());
325 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
326 justification = "https://github.com/spotbugs/spotbugs/issues/811")
327 private static void performDeviateDelete(final StmtContext<?, ?, ?> deviateStmtCtx,
328 final Mutable<?, ?, ?> targetCtx) {
329 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
330 validateDeviationTarget(originalStmtCtx, targetCtx);
331 deleteStatement(originalStmtCtx, targetCtx);
335 private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
336 final Mutable<?, ?, ?> targetCtx) {
337 final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.publicDefinition();
338 final String stmtArgument = stmtCtxToBeDeleted.rawArgument();
340 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
341 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
342 targetCtxSubstatement.rawArgument())) {
343 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
348 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
349 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
350 targetCtxSubstatement.rawArgument())) {
351 targetCtxSubstatement.setUnsupported();
356 LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does "
357 + "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
358 targetCtx.argument(), stmtCtxToBeDeleted.sourceReference());
361 private static void copyStatement(final StmtContext<?, ?, ?> stmtCtxToBeCopied, final Mutable<?, ?, ?> targetCtx) {
362 // we need to make a copy of the statement context only if it is an unknown statement, otherwise
363 // we can reuse the original statement context
364 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeCopied)) {
365 // FIXME: I think this should be handled by the corresponding support's copy policy
366 targetCtx.addEffectiveSubstatement(stmtCtxToBeCopied.replicaAsChildOf(targetCtx));
368 targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeCopied, CopyType.ORIGINAL));
372 private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
373 final StatementDefinition secondStmtDef, final String secondStmtArg) {
374 return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
377 private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
378 final StmtContext<?, ?, ?> targetCtx) {
379 InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
380 targetCtx.yangVersion()), deviateSubStmtCtx,
381 "%s is not a valid deviation target for substatement %s.", targetCtx.argument(),
382 deviateSubStmtCtx.publicDefinition().getStatementName());
385 private static boolean isSupportedDeviationTarget(final StmtContext<?, ?, ?> deviateSubstatementCtx,
386 final StmtContext<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
387 Set<StatementDefinition> supportedDeviationTargets =
388 YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(yangVersion,
389 deviateSubstatementCtx.publicDefinition());
391 if (supportedDeviationTargets == null) {
392 supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
393 deviateSubstatementCtx.publicDefinition());
396 // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
397 return supportedDeviationTargets == null || supportedDeviationTargets.contains(
398 deviateTargetCtx.publicDefinition());