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.SchemaNodeIdentifier;
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.ri.stmt.DeclaredStatementDecorators;
33 import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatements;
34 import org.opendaylight.yangtools.yang.model.ri.stmt.EffectiveStatements;
35 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
36 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
37 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
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.ModuleCtxToModuleQName;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
54 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
55 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
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 // FIXME once BUG-7760 gets fixed, there will be no need for these dirty casts
147 final StatementContextBase<?, ?, ?> sourceNodeStmtCtx =
148 (StatementContextBase<?, ?, ?>) sourceCtxPrerequisite.resolve(ctx);
149 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
150 (StatementContextBase<?, ?, ?>) targetCtxPrerequisite.resolve(ctx);
152 switch (deviateKind) {
154 targetNodeStmtCtx.setIsSupportedToBuildEffective(false);
157 performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
160 performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
163 performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
166 throw new IllegalStateException("Unsupported deviate " + deviateKind);
171 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
172 throw new InferenceException(deviateStmtCtx.coerceParentContext(), "Deviation target '%s' not found.",
179 public String internArgument(final String rawArgument) {
180 if ("add".equals(rawArgument)) {
182 } else if ("delete".equals(rawArgument)) {
184 } else if ("replace".equals(rawArgument)) {
186 } else if ("not-supported".equals(rawArgument)) {
187 return "not-supported";
194 protected final DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx,
195 final ImmutableList<? extends DeclaredStatement<?>> substatements) {
196 return DeclaredStatements.createDeviate(ctx.getArgument(), substatements);
200 protected final DeviateStatement attachDeclarationReference(final DeviateStatement stmt,
201 final DeclarationReference reference) {
202 return DeclaredStatementDecorators.decorateDeviate(stmt, reference);
206 protected final DeviateEffectiveStatement createEffective(final Current<DeviateKind, DeviateStatement> stmt,
207 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
208 return EffectiveStatements.createDeviate(stmt.declared(), substatements);
211 protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
212 switch (deviateKind) {
214 return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
216 return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
218 return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
220 return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
222 throw new IllegalStateException(String.format(
223 "Substatement validator for deviate %s has not been defined.", deviateKind));
227 private static boolean isDeviationSupported(
228 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx,
229 final SchemaNodeIdentifier deviationTarget) {
230 final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
231 ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES);
232 if (modulesDeviatedByModules == null) {
236 final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ModuleCtxToModuleQName.class,
237 deviateStmtCtx.getRoot());
238 final QNameModule targetModule = Iterables.getLast(deviationTarget.getNodeIdentifiers()).getModule();
240 final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
241 if (deviationModulesSupportedByTargetModule != null) {
242 return deviationModulesSupportedByTargetModule.contains(currentModule);
248 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
249 justification = "https://github.com/spotbugs/spotbugs/issues/811")
250 private static void performDeviateAdd(final StatementContextBase<?, ?, ?> deviateStmtCtx,
251 final StatementContextBase<?, ?, ?> targetCtx) {
252 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
253 validateDeviationTarget(originalStmtCtx, targetCtx);
254 addStatement(originalStmtCtx, targetCtx);
258 private static void addStatement(final Mutable<?, ?, ?> stmtCtxToBeAdded,
259 final StatementContextBase<?, ?, ?> targetCtx) {
260 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
261 final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.publicDefinition();
262 if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
263 && YangStmtMapping.LEAF.equals(targetCtx.publicDefinition())) {
264 for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
265 InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.publicDefinition()),
267 "Deviation cannot add substatement %s to target node %s because it is already defined "
268 + "in target and can appear only once.",
269 stmtToBeAdded.getStatementName(), targetCtx.argument());
274 copyStatement(stmtCtxToBeAdded, targetCtx);
277 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
278 justification = "https://github.com/spotbugs/spotbugs/issues/811")
279 private static void performDeviateReplace(final StatementContextBase<?, ?, ?> deviateStmtCtx,
280 final StatementContextBase<?, ?, ?> targetCtx) {
281 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
282 validateDeviationTarget(originalStmtCtx, targetCtx);
283 replaceStatement(originalStmtCtx, targetCtx);
287 private static void replaceStatement(final Mutable<?, ?, ?> stmtCtxToBeReplaced,
288 final StatementContextBase<?, ?, ?> 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 (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
300 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
301 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
302 copyStatement(stmtCtxToBeReplaced, targetCtx);
307 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
308 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
309 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
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 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
329 justification = "https://github.com/spotbugs/spotbugs/issues/811")
330 private static void performDeviateDelete(final StatementContextBase<?, ?, ?> deviateStmtCtx,
331 final StatementContextBase<?, ?, ?> targetCtx) {
332 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
333 validateDeviationTarget(originalStmtCtx, targetCtx);
334 deleteStatement(originalStmtCtx, targetCtx);
338 private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
339 final StatementContextBase<?, ?, ?> targetCtx) {
340 final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.publicDefinition();
341 final String stmtArgument = stmtCtxToBeDeleted.rawArgument();
343 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
344 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
345 targetCtxSubstatement.rawArgument())) {
346 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
351 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
352 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
353 targetCtxSubstatement.rawArgument())) {
354 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
359 LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does "
360 + "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
361 targetCtx.argument(), stmtCtxToBeDeleted.sourceReference());
364 private static void copyStatement(final Mutable<?, ?, ?> stmtCtxToBeCopied,
365 final StatementContextBase<?, ?, ?> targetCtx) {
366 // we need to make a copy of the statement context only if it is an unknown statement, otherwise
367 // we can reuse the original statement context
368 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeCopied)) {
369 targetCtx.addEffectiveSubstatement(stmtCtxToBeCopied.replicaAsChildOf(targetCtx));
371 targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeCopied, CopyType.ORIGINAL));
375 private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
376 final StatementDefinition secondStmtDef, final String secondStmtArg) {
377 return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
380 private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
381 final StmtContext<?, ?, ?> targetCtx) {
382 InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
383 targetCtx.yangVersion()), deviateSubStmtCtx,
384 "%s is not a valid deviation target for substatement %s.", targetCtx.argument(),
385 deviateSubStmtCtx.publicDefinition().getStatementName());
388 private static boolean isSupportedDeviationTarget(final StmtContext<?, ?, ?> deviateSubstatementCtx,
389 final StmtContext<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
390 Set<StatementDefinition> supportedDeviationTargets =
391 YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(yangVersion,
392 deviateSubstatementCtx.publicDefinition());
394 if (supportedDeviationTargets == null) {
395 supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
396 deviateSubstatementCtx.publicDefinition());
399 // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
400 return supportedDeviationTargets == null || supportedDeviationTargets.contains(
401 deviateTargetCtx.publicDefinition());