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.namespace.ChildSchemaNodeNamespace;
32 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
33 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
45 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
48 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
49 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 abstract class AbstractDeviateStatementSupport
54 extends BaseStatementSupport<DeviateKind, DeviateStatement, DeviateEffectiveStatement> {
55 private static final Logger LOG = LoggerFactory.getLogger(AbstractDeviateStatementSupport.class);
57 private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
58 SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
60 private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
61 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
62 .addOptional(YangStmtMapping.CONFIG)
63 .addOptional(YangStmtMapping.DEFAULT)
64 .addOptional(YangStmtMapping.MANDATORY)
65 .addOptional(YangStmtMapping.MAX_ELEMENTS)
66 .addOptional(YangStmtMapping.MIN_ELEMENTS)
67 .addAny(YangStmtMapping.MUST)
68 .addAny(YangStmtMapping.UNIQUE)
69 .addOptional(YangStmtMapping.UNITS)
72 private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
73 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
74 .addOptional(YangStmtMapping.CONFIG)
75 .addOptional(YangStmtMapping.DEFAULT)
76 .addOptional(YangStmtMapping.MANDATORY)
77 .addOptional(YangStmtMapping.MAX_ELEMENTS)
78 .addOptional(YangStmtMapping.MIN_ELEMENTS)
79 .addOptional(YangStmtMapping.TYPE)
80 .addOptional(YangStmtMapping.UNITS)
83 private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
84 SubstatementValidator.builder(YangStmtMapping.DEVIATE)
85 .addOptional(YangStmtMapping.DEFAULT)
86 .addAny(YangStmtMapping.MUST)
87 .addAny(YangStmtMapping.UNIQUE)
88 .addOptional(YangStmtMapping.UNITS)
91 private static final ImmutableMap<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP =
92 Maps.uniqueIndex(Arrays.asList(DeviateKind.values()), DeviateKind::getKeyword);
94 private static final ImmutableSet<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
95 YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
96 YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
98 private static final ImmutableSet<YangStmtMapping> IMPLICIT_STATEMENTS = ImmutableSet.of(YangStmtMapping.CONFIG,
99 YangStmtMapping.MANDATORY, YangStmtMapping.MAX_ELEMENTS, YangStmtMapping.MIN_ELEMENTS);
101 AbstractDeviateStatementSupport() {
102 super(YangStmtMapping.DEVIATE);
106 public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
107 return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value),
108 ctx.getStatementSourceReference(), "String '%s' is not valid deviate argument", value);
112 public final void onFullDefinitionDeclared(
113 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx) {
114 final DeviateKind deviateKind = deviateStmtCtx.getStatementArgument();
115 getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
117 final SchemaNodeIdentifier deviationTarget =
118 (SchemaNodeIdentifier) deviateStmtCtx.coerceParentContext().getStatementArgument();
120 if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
124 final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
125 ModelProcessingPhase.EFFECTIVE_MODEL);
127 final Prerequisite<StmtContext<DeviateKind, DeviateStatement,
128 DeviateEffectiveStatement>> sourceCtxPrerequisite =
129 deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
131 final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
132 deviateAction.mutatesEffectiveCtxPath(deviateStmtCtx.getRoot(),
133 ChildSchemaNodeNamespace.class, deviationTarget.getNodeIdentifiers());
135 deviateAction.apply(new InferenceAction() {
137 public void apply(final InferenceContext ctx) {
138 // FIXME once BUG-7760 gets fixed, there will be no need for these dirty casts
139 final StatementContextBase<?, ?, ?> sourceNodeStmtCtx =
140 (StatementContextBase<?, ?, ?>) sourceCtxPrerequisite.resolve(ctx);
141 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
142 (StatementContextBase<?, ?, ?>) targetCtxPrerequisite.resolve(ctx);
144 switch (deviateKind) {
146 targetNodeStmtCtx.setIsSupportedToBuildEffective(false);
149 performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
152 performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
155 performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
158 throw new IllegalStateException("Unsupported deviate " + deviateKind);
163 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
164 throw new InferenceException(deviateStmtCtx.coerceParentContext().getStatementSourceReference(),
165 "Deviation target '%s' not found.", deviationTarget);
171 public String internArgument(final String rawArgument) {
172 if ("add".equals(rawArgument)) {
174 } else if ("delete".equals(rawArgument)) {
176 } else if ("replace".equals(rawArgument)) {
178 } else if ("not-supported".equals(rawArgument)) {
179 return "not-supported";
186 protected final SubstatementValidator getSubstatementValidator() {
191 protected final DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx,
192 final ImmutableList<? extends DeclaredStatement<?>> substatements) {
193 return new DeviateStatementImpl(ctx, substatements);
197 protected final DeviateStatement createEmptyDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx) {
198 // This is exceedingly unlikely, just reuse the implementation
199 return createDeclared(ctx, ImmutableList.of());
203 protected final DeviateEffectiveStatement createEffective(
204 final StmtContext<DeviateKind, DeviateStatement, DeviateEffectiveStatement> ctx,
205 final DeviateStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
206 return new DeviateEffectiveStatementImpl(declared, substatements);
210 protected final DeviateEffectiveStatement createEmptyEffective(
211 final StmtContext<DeviateKind, DeviateStatement, DeviateEffectiveStatement> ctx,
212 final DeviateStatement declared) {
213 // This is exceedingly unlikely, just reuse the implementation
214 return createEffective(ctx, declared, ImmutableList.of());
217 protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
218 switch (deviateKind) {
220 return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
222 return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
224 return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
226 return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
228 throw new IllegalStateException(String.format(
229 "Substatement validator for deviate %s has not been defined.", deviateKind));
233 private static boolean isDeviationSupported(
234 final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx,
235 final SchemaNodeIdentifier deviationTarget) {
236 final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
237 ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES);
238 if (modulesDeviatedByModules == null) {
242 final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ModuleCtxToModuleQName.class,
243 deviateStmtCtx.getRoot());
244 final QNameModule targetModule = Iterables.getLast(deviationTarget.getNodeIdentifiers()).getModule();
246 final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
247 if (deviationModulesSupportedByTargetModule != null) {
248 return deviationModulesSupportedByTargetModule.contains(currentModule);
254 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
255 justification = "https://github.com/spotbugs/spotbugs/issues/811")
256 private static void performDeviateAdd(final StatementContextBase<?, ?, ?> deviateStmtCtx,
257 final StatementContextBase<?, ?, ?> targetCtx) {
258 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
259 validateDeviationTarget(originalStmtCtx, targetCtx);
260 addStatement(originalStmtCtx, targetCtx);
264 private static void addStatement(final Mutable<?, ?, ?> stmtCtxToBeAdded,
265 final StatementContextBase<?, ?, ?> targetCtx) {
266 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
267 final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.getPublicDefinition();
268 if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
269 && YangStmtMapping.LEAF.equals(targetCtx.getPublicDefinition())) {
270 for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
271 InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.getPublicDefinition()),
272 stmtCtxToBeAdded.getStatementSourceReference(),
273 "Deviation cannot add substatement %s to target node %s because it is already defined "
274 + "in target and can appear only once.",
275 stmtToBeAdded.getStatementName(), targetCtx.getStatementArgument());
280 copyStatement(stmtCtxToBeAdded, targetCtx);
283 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
284 justification = "https://github.com/spotbugs/spotbugs/issues/811")
285 private static void performDeviateReplace(final StatementContextBase<?, ?, ?> deviateStmtCtx,
286 final StatementContextBase<?, ?, ?> targetCtx) {
287 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
288 validateDeviationTarget(originalStmtCtx, targetCtx);
289 replaceStatement(originalStmtCtx, targetCtx);
293 private static void replaceStatement(final Mutable<?, ?, ?> stmtCtxToBeReplaced,
294 final StatementContextBase<?, ?, ?> targetCtx) {
295 final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.getPublicDefinition();
297 if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
298 && YangStmtMapping.LEAF_LIST.equals(targetCtx.getPublicDefinition())) {
299 LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can "
300 + "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
301 targetCtx.getStatementArgument(), stmtCtxToBeReplaced.getStatementSourceReference());
305 for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
306 if (stmtToBeReplaced.equals(targetCtxSubstatement.getPublicDefinition())) {
307 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
308 copyStatement(stmtCtxToBeReplaced, targetCtx);
313 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
314 if (stmtToBeReplaced.equals(targetCtxSubstatement.getPublicDefinition())) {
315 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
316 copyStatement(stmtCtxToBeReplaced, targetCtx);
321 // This is a special case when deviate replace of a config/mandatory/max/min-elements substatement targets
322 // a node which does not contain an explicitly declared config/mandatory/max/min-elements.
323 // However, according to RFC6020/RFC7950, these properties are always implicitly present.
324 if (IMPLICIT_STATEMENTS.contains(stmtToBeReplaced)) {
325 addStatement(stmtCtxToBeReplaced, targetCtx);
329 throw new InferenceException(stmtCtxToBeReplaced.getStatementSourceReference(), "Deviation cannot replace "
330 + "substatement %s in target node %s because it does not exist in target node.",
331 stmtToBeReplaced.getStatementName(), targetCtx.getStatementArgument());
334 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
335 justification = "https://github.com/spotbugs/spotbugs/issues/811")
336 private static void performDeviateDelete(final StatementContextBase<?, ?, ?> deviateStmtCtx,
337 final StatementContextBase<?, ?, ?> targetCtx) {
338 for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
339 validateDeviationTarget(originalStmtCtx, targetCtx);
340 deleteStatement(originalStmtCtx, targetCtx);
344 private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
345 final StatementContextBase<?, ?, ?> targetCtx) {
346 final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.getPublicDefinition();
347 final String stmtArgument = stmtCtxToBeDeleted.rawStatementArgument();
349 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
350 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.getPublicDefinition(),
351 targetCtxSubstatement.rawStatementArgument())) {
352 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
357 for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
358 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.getPublicDefinition(),
359 targetCtxSubstatement.rawStatementArgument())) {
360 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
365 LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does "
366 + "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
367 targetCtx.getStatementArgument(), stmtCtxToBeDeleted.getStatementSourceReference());
370 private static void copyStatement(final Mutable<?, ?, ?> stmtCtxToBeCopied,
371 final StatementContextBase<?, ?, ?> targetCtx) {
372 // we need to make a copy of the statement context only if it is an unknown statement, otherwise
373 // we can reuse the original statement context
374 if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeCopied)) {
375 targetCtx.addEffectiveSubstatement(stmtCtxToBeCopied);
377 targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeCopied, CopyType.ORIGINAL));
381 private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
382 final StatementDefinition secondStmtDef, final String secondStmtArg) {
383 return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
386 private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
387 final StmtContext<?, ?, ?> targetCtx) {
388 InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
389 targetCtx.getRootVersion()), deviateSubStmtCtx.getStatementSourceReference(),
390 "%s is not a valid deviation target for substatement %s.",
391 targetCtx.getStatementArgument(), deviateSubStmtCtx.getPublicDefinition().getStatementName());
394 private static boolean isSupportedDeviationTarget(final StmtContext<?, ?, ?> deviateSubstatementCtx,
395 final StmtContext<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
396 Set<StatementDefinition> supportedDeviationTargets =
397 YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(deviateTargetCtx.getRootVersion(),
398 deviateSubstatementCtx.getPublicDefinition());
400 if (supportedDeviationTargets == null) {
401 supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
402 deviateSubstatementCtx.getPublicDefinition());
405 // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
406 return supportedDeviationTargets == null || supportedDeviationTargets.contains(
407 deviateTargetCtx.getPublicDefinition());