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.List;
20 import java.util.Objects;
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.CopyType;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
54 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
55 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
56 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 abstract class AbstractDeviateStatementSupport
61 extends AbstractStatementSupport<DeviateKind, DeviateStatement, DeviateEffectiveStatement> {
62 private static final Logger LOG = LoggerFactory.getLogger(AbstractDeviateStatementSupport.class);
64 private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
65 SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
67 private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
68 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
69 .addOptional(YangStmtMapping.CONFIG)
70 .addOptional(YangStmtMapping.DEFAULT)
71 .addOptional(YangStmtMapping.MANDATORY)
72 .addOptional(YangStmtMapping.MAX_ELEMENTS)
73 .addOptional(YangStmtMapping.MIN_ELEMENTS)
74 .addAny(YangStmtMapping.MUST)
75 .addAny(YangStmtMapping.UNIQUE)
76 .addOptional(YangStmtMapping.UNITS)
79 private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
80 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
81 .addOptional(YangStmtMapping.CONFIG)
82 .addOptional(YangStmtMapping.DEFAULT)
83 .addOptional(YangStmtMapping.MANDATORY)
84 .addOptional(YangStmtMapping.MAX_ELEMENTS)
85 .addOptional(YangStmtMapping.MIN_ELEMENTS)
86 .addOptional(YangStmtMapping.TYPE)
87 .addOptional(YangStmtMapping.UNITS)
90 private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
91 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
92 .addOptional(YangStmtMapping.DEFAULT)
93 .addAny(YangStmtMapping.MUST)
94 .addAny(YangStmtMapping.UNIQUE)
95 .addOptional(YangStmtMapping.UNITS)
98 private static final ImmutableMap<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP =
99 Maps.uniqueIndex(Arrays.asList(DeviateKind.values()), DeviateKind::getKeyword);
101 private static final ImmutableSet<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
102 YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
103 YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
105 private static final ImmutableSet<YangStmtMapping> IMPLICIT_STATEMENTS = ImmutableSet.of(YangStmtMapping.CONFIG,
106 YangStmtMapping.MANDATORY, YangStmtMapping.MAX_ELEMENTS, YangStmtMapping.MIN_ELEMENTS);
108 AbstractDeviateStatementSupport(final YangParserConfiguration config) {
109 // Note: we are performing our own validation based on deviate kind.
110 // TODO: perhaps we should do argumentSpecificSupport?
111 super(YangStmtMapping.DEVIATE, StatementPolicy.contextIndependent(), config, null);
115 public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
116 return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value), ctx,
117 "String '%s' is not valid deviate argument", value);
121 public final void onFullDefinitionDeclared(
122 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx) {
123 final DeviateKind deviateKind = deviateStmtCtx.argument();
124 getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
126 final SchemaNodeIdentifier deviationTarget =
127 (SchemaNodeIdentifier) deviateStmtCtx.coerceParentContext().argument();
129 if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
133 final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
134 ModelProcessingPhase.EFFECTIVE_MODEL);
136 final Prerequisite<StmtContext<DeviateKind, DeviateStatement,
137 DeviateEffectiveStatement>> sourceCtxPrerequisite =
138 deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
140 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
141 deviateAction.mutatesEffectiveCtxPath(deviateStmtCtx.getRoot(),
142 SchemaTreeNamespace.class, deviationTarget.getNodeIdentifiers());
144 deviateAction.apply(new InferenceAction() {
146 public void apply(final InferenceContext ctx) {
147 if (!deviateStmtCtx.isSupportedToBuildEffective()) {
148 // We are not building effective model, hence we should not be performing any effects
152 // FIXME once BUG-7760 gets fixed, there will be no need for these dirty casts
153 final StatementContextBase<?, ?, ?> sourceNodeStmtCtx =
154 (StatementContextBase<?, ?, ?>) sourceCtxPrerequisite.resolve(ctx);
155 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
156 (StatementContextBase<?, ?, ?>) targetCtxPrerequisite.resolve(ctx);
158 switch (deviateKind) {
160 targetNodeStmtCtx.setIsSupportedToBuildEffective(false);
163 performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
166 performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
169 performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
172 throw new IllegalStateException("Unsupported deviate " + deviateKind);
177 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
178 throw new InferenceException(deviateStmtCtx.coerceParentContext(), "Deviation target '%s' not found.",
183 public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
184 if (targetCtxPrerequisite.equals(unavail)) {
185 deviateStmtCtx.setIsSupportedToBuildEffective(false);
187 prerequisiteFailed(List.of(unavail));
194 public String internArgument(final String rawArgument) {
195 if ("add".equals(rawArgument)) {
197 } else if ("delete".equals(rawArgument)) {
199 } else if ("replace".equals(rawArgument)) {
201 } else if ("not-supported".equals(rawArgument)) {
202 return "not-supported";
209 protected final DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx,
210 final ImmutableList<? extends DeclaredStatement<?>> substatements) {
211 return DeclaredStatements.createDeviate(ctx.getArgument(), substatements);
215 protected final DeviateStatement attachDeclarationReference(final DeviateStatement stmt,
216 final DeclarationReference reference) {
217 return DeclaredStatementDecorators.decorateDeviate(stmt, reference);
221 protected final DeviateEffectiveStatement createEffective(final Current<DeviateKind, DeviateStatement> stmt,
222 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
223 return EffectiveStatements.createDeviate(stmt.declared(), substatements);
226 protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
227 switch (deviateKind) {
229 return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
231 return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
233 return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
235 return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
237 throw new IllegalStateException(String.format(
238 "Substatement validator for deviate %s has not been defined.", deviateKind));
242 private static boolean isDeviationSupported(
243 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx,
244 final SchemaNodeIdentifier deviationTarget) {
245 final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
246 ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES);
247 if (modulesDeviatedByModules == null) {
251 final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ModuleCtxToModuleQName.class,
252 deviateStmtCtx.getRoot());
253 final QNameModule targetModule = Iterables.getLast(deviationTarget.getNodeIdentifiers()).getModule();
255 final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
256 if (deviationModulesSupportedByTargetModule != null) {
257 return deviationModulesSupportedByTargetModule.contains(currentModule);
263 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
264 justification = "https://github.com/spotbugs/spotbugs/issues/811")
265 private static void performDeviateAdd(final StatementContextBase<?, ?, ?> deviateStmtCtx,
266 final StatementContextBase<?, ?, ?> targetCtx) {
267 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
268 validateDeviationTarget(originalStmtCtx, targetCtx);
269 addStatement(originalStmtCtx, targetCtx);
273 private static void addStatement(final Mutable<?, ?, ?> stmtCtxToBeAdded,
274 final StatementContextBase<?, ?, ?> targetCtx) {
275 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
276 final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.publicDefinition();
277 if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
278 && YangStmtMapping.LEAF.equals(targetCtx.publicDefinition())) {
279 for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
280 InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.publicDefinition()),
282 "Deviation cannot add substatement %s to target node %s because it is already defined "
283 + "in target and can appear only once.",
284 stmtToBeAdded.getStatementName(), targetCtx.argument());
289 copyStatement(stmtCtxToBeAdded, targetCtx);
292 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
293 justification = "https://github.com/spotbugs/spotbugs/issues/811")
294 private static void performDeviateReplace(final StatementContextBase<?, ?, ?> deviateStmtCtx,
295 final StatementContextBase<?, ?, ?> targetCtx) {
296 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
297 validateDeviationTarget(originalStmtCtx, targetCtx);
298 replaceStatement(originalStmtCtx, targetCtx);
302 private static void replaceStatement(final Mutable<?, ?, ?> stmtCtxToBeReplaced,
303 final StatementContextBase<?, ?, ?> targetCtx) {
304 final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.publicDefinition();
306 if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
307 && YangStmtMapping.LEAF_LIST.equals(targetCtx.publicDefinition())) {
308 LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can "
309 + "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
310 targetCtx.argument(), stmtCtxToBeReplaced.sourceReference());
314 for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
315 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
316 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
317 copyStatement(stmtCtxToBeReplaced, targetCtx);
322 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
323 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
324 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
325 copyStatement(stmtCtxToBeReplaced, targetCtx);
330 // This is a special case when deviate replace of a config/mandatory/max/min-elements substatement targets
331 // a node which does not contain an explicitly declared config/mandatory/max/min-elements.
332 // However, according to RFC6020/RFC7950, these properties are always implicitly present.
333 if (IMPLICIT_STATEMENTS.contains(stmtToBeReplaced)) {
334 addStatement(stmtCtxToBeReplaced, targetCtx);
338 throw new InferenceException(stmtCtxToBeReplaced,
339 "Deviation cannot replace substatement %s in target node %s because it does not exist in target node.",
340 stmtToBeReplaced.getStatementName(), targetCtx.argument());
343 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
344 justification = "https://github.com/spotbugs/spotbugs/issues/811")
345 private static void performDeviateDelete(final StatementContextBase<?, ?, ?> deviateStmtCtx,
346 final StatementContextBase<?, ?, ?> targetCtx) {
347 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
348 validateDeviationTarget(originalStmtCtx, targetCtx);
349 deleteStatement(originalStmtCtx, targetCtx);
353 private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
354 final StatementContextBase<?, ?, ?> targetCtx) {
355 final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.publicDefinition();
356 final String stmtArgument = stmtCtxToBeDeleted.rawArgument();
358 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
359 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
360 targetCtxSubstatement.rawArgument())) {
361 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
366 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
367 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
368 targetCtxSubstatement.rawArgument())) {
369 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
374 LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does "
375 + "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
376 targetCtx.argument(), stmtCtxToBeDeleted.sourceReference());
379 private static void copyStatement(final Mutable<?, ?, ?> stmtCtxToBeCopied,
380 final StatementContextBase<?, ?, ?> targetCtx) {
381 // we need to make a copy of the statement context only if it is an unknown statement, otherwise
382 // we can reuse the original statement context
383 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeCopied)) {
384 targetCtx.addEffectiveSubstatement(stmtCtxToBeCopied.replicaAsChildOf(targetCtx));
386 targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeCopied, CopyType.ORIGINAL));
390 private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
391 final StatementDefinition secondStmtDef, final String secondStmtArg) {
392 return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
395 private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
396 final StmtContext<?, ?, ?> targetCtx) {
397 InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
398 targetCtx.yangVersion()), deviateSubStmtCtx,
399 "%s is not a valid deviation target for substatement %s.", targetCtx.argument(),
400 deviateSubStmtCtx.publicDefinition().getStatementName());
403 private static boolean isSupportedDeviationTarget(final StmtContext<?, ?, ?> deviateSubstatementCtx,
404 final StmtContext<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
405 Set<StatementDefinition> supportedDeviationTargets =
406 YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(yangVersion,
407 deviateSubstatementCtx.publicDefinition());
409 if (supportedDeviationTargets == null) {
410 supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
411 deviateSubstatementCtx.publicDefinition());
414 // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
415 return supportedDeviationTargets == null || supportedDeviationTargets.contains(
416 deviateTargetCtx.publicDefinition());