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.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.SourceException;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 abstract class AbstractDeviateStatementSupport
59 extends AbstractStatementSupport<DeviateKind, DeviateStatement, DeviateEffectiveStatement> {
60 private static final Logger LOG = LoggerFactory.getLogger(AbstractDeviateStatementSupport.class);
62 private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
63 SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
65 private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
66 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
67 .addOptional(YangStmtMapping.CONFIG)
68 .addOptional(YangStmtMapping.DEFAULT)
69 .addOptional(YangStmtMapping.MANDATORY)
70 .addOptional(YangStmtMapping.MAX_ELEMENTS)
71 .addOptional(YangStmtMapping.MIN_ELEMENTS)
72 .addAny(YangStmtMapping.MUST)
73 .addAny(YangStmtMapping.UNIQUE)
74 .addOptional(YangStmtMapping.UNITS)
77 private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
78 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
79 .addOptional(YangStmtMapping.CONFIG)
80 .addOptional(YangStmtMapping.DEFAULT)
81 .addOptional(YangStmtMapping.MANDATORY)
82 .addOptional(YangStmtMapping.MAX_ELEMENTS)
83 .addOptional(YangStmtMapping.MIN_ELEMENTS)
84 .addOptional(YangStmtMapping.TYPE)
85 .addOptional(YangStmtMapping.UNITS)
88 private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
89 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
90 .addOptional(YangStmtMapping.DEFAULT)
91 .addAny(YangStmtMapping.MUST)
92 .addAny(YangStmtMapping.UNIQUE)
93 .addOptional(YangStmtMapping.UNITS)
96 private static final ImmutableMap<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP =
97 Maps.uniqueIndex(Arrays.asList(DeviateKind.values()), DeviateKind::getKeyword);
99 private static final ImmutableSet<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
100 YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
101 YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
103 private static final ImmutableSet<YangStmtMapping> IMPLICIT_STATEMENTS = ImmutableSet.of(YangStmtMapping.CONFIG,
104 YangStmtMapping.MANDATORY, YangStmtMapping.MAX_ELEMENTS, YangStmtMapping.MIN_ELEMENTS);
106 AbstractDeviateStatementSupport(final YangParserConfiguration config) {
107 // Note: we are performing our own validation based on deviate kind.
108 // TODO: perhaps we should do argumentSpecificSupport?
109 super(YangStmtMapping.DEVIATE, StatementPolicy.contextIndependent(), config, null);
113 public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
114 return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value), ctx,
115 "String '%s' is not valid deviate argument", value);
119 public final void onFullDefinitionDeclared(
120 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx) {
121 final DeviateKind deviateKind = deviateStmtCtx.argument();
122 getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
124 final SchemaNodeIdentifier deviationTarget =
125 (SchemaNodeIdentifier) deviateStmtCtx.coerceParentContext().argument();
127 if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
131 final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
132 ModelProcessingPhase.EFFECTIVE_MODEL);
134 final Prerequisite<StmtContext<DeviateKind, DeviateStatement,
135 DeviateEffectiveStatement>> sourceCtxPrerequisite =
136 deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
138 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
139 deviateAction.mutatesEffectiveCtxPath(deviateStmtCtx.getRoot(),
140 SchemaTreeNamespace.class, deviationTarget.getNodeIdentifiers());
142 deviateAction.apply(new InferenceAction() {
144 public void apply(final InferenceContext ctx) {
145 final var sourceNodeStmtCtx = sourceCtxPrerequisite.resolve(ctx);
146 final var targetNodeStmtCtx = targetCtxPrerequisite.resolve(ctx);
148 switch (deviateKind) {
150 // FIXME: this can be short-circuited without an inference action
151 targetNodeStmtCtx.setUnsupported();
154 performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
157 performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
160 performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
163 throw new IllegalStateException("Unsupported deviate " + deviateKind);
168 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
169 throw new InferenceException(deviateStmtCtx.coerceParentContext(), "Deviation target '%s' not found.",
176 public String internArgument(final String rawArgument) {
177 if ("add".equals(rawArgument)) {
179 } else if ("delete".equals(rawArgument)) {
181 } else if ("replace".equals(rawArgument)) {
183 } else if ("not-supported".equals(rawArgument)) {
184 return "not-supported";
191 protected final DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx,
192 final ImmutableList<? extends DeclaredStatement<?>> substatements) {
193 return DeclaredStatements.createDeviate(ctx.getArgument(), substatements);
197 protected final DeviateStatement attachDeclarationReference(final DeviateStatement stmt,
198 final DeclarationReference reference) {
199 return DeclaredStatementDecorators.decorateDeviate(stmt, reference);
203 protected final DeviateEffectiveStatement createEffective(final Current<DeviateKind, DeviateStatement> stmt,
204 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
205 return EffectiveStatements.createDeviate(stmt.declared(), substatements);
208 protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
209 switch (deviateKind) {
211 return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
213 return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
215 return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
217 return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
219 throw new IllegalStateException(String.format(
220 "Substatement validator for deviate %s has not been defined.", deviateKind));
224 private static boolean isDeviationSupported(
225 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx,
226 final SchemaNodeIdentifier deviationTarget) {
227 final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
228 ModulesDeviatedByModules.class, Empty.value());
229 if (modulesDeviatedByModules == null) {
233 final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ModuleCtxToModuleQName.class,
234 deviateStmtCtx.getRoot());
235 final QNameModule targetModule = Iterables.getLast(deviationTarget.getNodeIdentifiers()).getModule();
237 final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
238 if (deviationModulesSupportedByTargetModule != null) {
239 return deviationModulesSupportedByTargetModule.contains(currentModule);
245 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
246 justification = "https://github.com/spotbugs/spotbugs/issues/811")
247 private static void performDeviateAdd(final StmtContext<?, ?, ?> deviateStmtCtx,
248 final Mutable<?, ?, ?> targetCtx) {
249 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
250 validateDeviationTarget(originalStmtCtx, targetCtx);
251 addStatement(originalStmtCtx, targetCtx);
255 private static void addStatement(final StmtContext<?, ?, ?> stmtCtxToBeAdded, final Mutable<?, ?, ?> targetCtx) {
256 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
257 final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.publicDefinition();
258 if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
259 && YangStmtMapping.LEAF.equals(targetCtx.publicDefinition())) {
260 for (StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
261 InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.publicDefinition()),
263 "Deviation cannot add substatement %s to target node %s because it is already defined "
264 + "in target and can appear only once.",
265 stmtToBeAdded.getStatementName(), targetCtx.argument());
270 copyStatement(stmtCtxToBeAdded, targetCtx);
273 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
274 justification = "https://github.com/spotbugs/spotbugs/issues/811")
275 private static void performDeviateReplace(final StmtContext<?, ?, ?> deviateStmtCtx,
276 final Mutable<?, ?, ?> targetCtx) {
277 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
278 validateDeviationTarget(originalStmtCtx, targetCtx);
279 replaceStatement(originalStmtCtx, targetCtx);
283 private static void replaceStatement(final StmtContext<?, ?, ?> stmtCtxToBeReplaced,
284 final Mutable<?, ?, ?> targetCtx) {
285 final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.publicDefinition();
287 if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
288 && YangStmtMapping.LEAF_LIST.equals(targetCtx.publicDefinition())) {
289 LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can "
290 + "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
291 targetCtx.argument(), stmtCtxToBeReplaced.sourceReference());
295 for (StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
296 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
297 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
298 copyStatement(stmtCtxToBeReplaced, targetCtx);
303 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
304 if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
305 targetCtxSubstatement.setUnsupported();
306 copyStatement(stmtCtxToBeReplaced, targetCtx);
311 // This is a special case when deviate replace of a config/mandatory/max/min-elements substatement targets
312 // a node which does not contain an explicitly declared config/mandatory/max/min-elements.
313 // However, according to RFC6020/RFC7950, these properties are always implicitly present.
314 if (IMPLICIT_STATEMENTS.contains(stmtToBeReplaced)) {
315 addStatement(stmtCtxToBeReplaced, targetCtx);
319 throw new InferenceException(stmtCtxToBeReplaced,
320 "Deviation cannot replace substatement %s in target node %s because it does not exist in target node.",
321 stmtToBeReplaced.getStatementName(), targetCtx.argument());
324 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
325 justification = "https://github.com/spotbugs/spotbugs/issues/811")
326 private static void performDeviateDelete(final StmtContext<?, ?, ?> deviateStmtCtx,
327 final Mutable<?, ?, ?> targetCtx) {
328 for (StmtContext<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
329 validateDeviationTarget(originalStmtCtx, targetCtx);
330 deleteStatement(originalStmtCtx, targetCtx);
334 private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
335 final Mutable<?, ?, ?> targetCtx) {
336 final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.publicDefinition();
337 final String stmtArgument = stmtCtxToBeDeleted.rawArgument();
339 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
340 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
341 targetCtxSubstatement.rawArgument())) {
342 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
347 for (Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
348 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
349 targetCtxSubstatement.rawArgument())) {
350 targetCtxSubstatement.setUnsupported();
355 LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does "
356 + "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
357 targetCtx.argument(), stmtCtxToBeDeleted.sourceReference());
360 private static void copyStatement(final StmtContext<?, ?, ?> stmtCtxToBeCopied, final Mutable<?, ?, ?> targetCtx) {
361 // we need to make a copy of the statement context only if it is an unknown statement, otherwise
362 // we can reuse the original statement context
363 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeCopied)) {
364 // FIXME: I think this should be handled by the corresponding support's copy policy
365 targetCtx.addEffectiveSubstatement(stmtCtxToBeCopied.replicaAsChildOf(targetCtx));
367 targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeCopied, CopyType.ORIGINAL));
371 private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
372 final StatementDefinition secondStmtDef, final String secondStmtArg) {
373 return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
376 private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
377 final StmtContext<?, ?, ?> targetCtx) {
378 InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
379 targetCtx.yangVersion()), deviateSubStmtCtx,
380 "%s is not a valid deviation target for substatement %s.", targetCtx.argument(),
381 deviateSubStmtCtx.publicDefinition().getStatementName());
384 private static boolean isSupportedDeviationTarget(final StmtContext<?, ?, ?> deviateSubstatementCtx,
385 final StmtContext<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
386 Set<StatementDefinition> supportedDeviationTargets =
387 YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(yangVersion,
388 deviateSubstatementCtx.publicDefinition());
390 if (supportedDeviationTargets == null) {
391 supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
392 deviateSubstatementCtx.publicDefinition());
395 // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
396 return supportedDeviationTargets == null || supportedDeviationTargets.contains(
397 deviateTargetCtx.publicDefinition());