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.QNameModule;
22 import org.opendaylight.yangtools.yang.common.YangVersion;
23 import org.opendaylight.yangtools.yang.model.api.DeviateKind;
24 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
25 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
28 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateEffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
31 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
32 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
33 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
49 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
50 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 abstract class AbstractDeviateStatementSupport
55 extends BaseStatementSupport<DeviateKind, DeviateStatement, DeviateEffectiveStatement> {
56 private static final Logger LOG = LoggerFactory.getLogger(AbstractDeviateStatementSupport.class);
58 private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
59 SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
61 private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
62 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
63 .addOptional(YangStmtMapping.CONFIG)
64 .addOptional(YangStmtMapping.DEFAULT)
65 .addOptional(YangStmtMapping.MANDATORY)
66 .addOptional(YangStmtMapping.MAX_ELEMENTS)
67 .addOptional(YangStmtMapping.MIN_ELEMENTS)
68 .addAny(YangStmtMapping.MUST)
69 .addAny(YangStmtMapping.UNIQUE)
70 .addOptional(YangStmtMapping.UNITS)
73 private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
74 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
75 .addOptional(YangStmtMapping.CONFIG)
76 .addOptional(YangStmtMapping.DEFAULT)
77 .addOptional(YangStmtMapping.MANDATORY)
78 .addOptional(YangStmtMapping.MAX_ELEMENTS)
79 .addOptional(YangStmtMapping.MIN_ELEMENTS)
80 .addOptional(YangStmtMapping.TYPE)
81 .addOptional(YangStmtMapping.UNITS)
84 private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
85 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
86 .addOptional(YangStmtMapping.DEFAULT)
87 .addAny(YangStmtMapping.MUST)
88 .addAny(YangStmtMapping.UNIQUE)
89 .addOptional(YangStmtMapping.UNITS)
92 private static final ImmutableMap<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP =
93 Maps.uniqueIndex(Arrays.asList(DeviateKind.values()), DeviateKind::getKeyword);
95 private static final ImmutableSet<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
96 YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
97 YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
99 private static final ImmutableSet<YangStmtMapping> IMPLICIT_STATEMENTS = ImmutableSet.of(YangStmtMapping.CONFIG,
100 YangStmtMapping.MANDATORY, YangStmtMapping.MAX_ELEMENTS, YangStmtMapping.MIN_ELEMENTS);
102 AbstractDeviateStatementSupport() {
103 super(YangStmtMapping.DEVIATE);
107 public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
108 return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value), ctx.sourceReference(),
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.class, deviationTarget.getNodeIdentifiers());
136 deviateAction.apply(new InferenceAction() {
138 public void apply(final InferenceContext ctx) {
139 // FIXME once BUG-7760 gets fixed, there will be no need for these dirty casts
140 final StatementContextBase<?, ?, ?> sourceNodeStmtCtx =
141 (StatementContextBase<?, ?, ?>) sourceCtxPrerequisite.resolve(ctx);
142 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
143 (StatementContextBase<?, ?, ?>) targetCtxPrerequisite.resolve(ctx);
145 switch (deviateKind) {
147 targetNodeStmtCtx.setIsSupportedToBuildEffective(false);
150 performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
153 performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
156 performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
159 throw new IllegalStateException("Unsupported deviate " + deviateKind);
164 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
165 throw new InferenceException(deviateStmtCtx.coerceParentContext().sourceReference(),
166 "Deviation target '%s' not found.", deviationTarget);
172 public String internArgument(final String rawArgument) {
173 if ("add".equals(rawArgument)) {
175 } else if ("delete".equals(rawArgument)) {
177 } else if ("replace".equals(rawArgument)) {
179 } else if ("not-supported".equals(rawArgument)) {
180 return "not-supported";
187 protected final SubstatementValidator getSubstatementValidator() {
192 protected final DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx,
193 final ImmutableList<? extends DeclaredStatement<?>> substatements) {
194 return new DeviateStatementImpl(ctx.getRawArgument(), ctx.getArgument(), substatements);
198 protected final DeviateStatement createEmptyDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx) {
199 // This is exceedingly unlikely, just reuse the implementation
200 return createDeclared(ctx, ImmutableList.of());
204 protected DeviateEffectiveStatement createEffective(final Current<DeviateKind, DeviateStatement> stmt,
205 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
206 return new DeviateEffectiveStatementImpl(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, SupportedModules.SUPPORTED_MODULES);
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 StatementContextBase<?, ?, ?> deviateStmtCtx,
249 final StatementContextBase<?, ?, ?> targetCtx) {
250 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
251 validateDeviationTarget(originalStmtCtx, targetCtx);
252 addStatement(originalStmtCtx, targetCtx);
256 private static void addStatement(final Mutable<?, ?, ?> stmtCtxToBeAdded,
257 final StatementContextBase<?, ?, ?> targetCtx) {
258 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
259 final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.publicDefinition();
260 if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
261 && YangStmtMapping.LEAF.equals(targetCtx.publicDefinition())) {
262 for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
263 InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.publicDefinition()),
264 stmtCtxToBeAdded.sourceReference(),
265 "Deviation cannot add substatement %s to target node %s because it is already defined "
266 + "in target and can appear only once.",
267 stmtToBeAdded.getStatementName(), targetCtx.argument());
272 copyStatement(stmtCtxToBeAdded, targetCtx);
275 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
276 justification = "https://github.com/spotbugs/spotbugs/issues/811")
277 private static void performDeviateReplace(final StatementContextBase<?, ?, ?> deviateStmtCtx,
278 final StatementContextBase<?, ?, ?> targetCtx) {
279 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
280 validateDeviationTarget(originalStmtCtx, targetCtx);
281 replaceStatement(originalStmtCtx, targetCtx);
285 private static void replaceStatement(final Mutable<?, ?, ?> stmtCtxToBeReplaced,
286 final StatementContextBase<?, ?, ?> targetCtx) {
287 final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.publicDefinition();
289 if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
290 && YangStmtMapping.LEAF_LIST.equals(targetCtx.publicDefinition())) {
291 LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can "
292 + "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
293 targetCtx.argument(), stmtCtxToBeReplaced.sourceReference());
297 for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
298 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
299 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
300 copyStatement(stmtCtxToBeReplaced, targetCtx);
305 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
306 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
307 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
308 copyStatement(stmtCtxToBeReplaced, targetCtx);
313 // This is a special case when deviate replace of a config/mandatory/max/min-elements substatement targets
314 // a node which does not contain an explicitly declared config/mandatory/max/min-elements.
315 // However, according to RFC6020/RFC7950, these properties are always implicitly present.
316 if (IMPLICIT_STATEMENTS.contains(stmtToBeReplaced)) {
317 addStatement(stmtCtxToBeReplaced, targetCtx);
321 throw new InferenceException(stmtCtxToBeReplaced.sourceReference(), "Deviation cannot replace "
322 + "substatement %s in target node %s because it does not exist in target node.",
323 stmtToBeReplaced.getStatementName(), targetCtx.argument());
326 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
327 justification = "https://github.com/spotbugs/spotbugs/issues/811")
328 private static void performDeviateDelete(final StatementContextBase<?, ?, ?> deviateStmtCtx,
329 final StatementContextBase<?, ?, ?> targetCtx) {
330 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
331 validateDeviationTarget(originalStmtCtx, targetCtx);
332 deleteStatement(originalStmtCtx, targetCtx);
336 private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
337 final StatementContextBase<?, ?, ?> targetCtx) {
338 final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.publicDefinition();
339 final String stmtArgument = stmtCtxToBeDeleted.rawArgument();
341 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
342 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
343 targetCtxSubstatement.rawArgument())) {
344 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
349 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
350 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
351 targetCtxSubstatement.rawArgument())) {
352 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
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 Mutable<?, ?, ?> stmtCtxToBeCopied,
363 final StatementContextBase<?, ?, ?> targetCtx) {
364 // we need to make a copy of the statement context only if it is an unknown statement, otherwise
365 // we can reuse the original statement context
366 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeCopied)) {
367 targetCtx.addEffectiveSubstatement(stmtCtxToBeCopied);
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.getRootVersion()), deviateSubStmtCtx.sourceReference(),
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(deviateTargetCtx.getRootVersion(),
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());