Bug 8307: Add the option for activating deviation statements
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / rfc6020 / DeviateStatementImpl.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
9
10 import com.google.common.collect.ImmutableSet;
11 import com.google.common.collect.Iterables;
12 import java.util.Collection;
13 import java.util.Map;
14 import java.util.Objects;
15 import java.util.Set;
16 import javax.annotation.Nonnull;
17 import org.opendaylight.yangtools.yang.common.QNameModule;
18 import org.opendaylight.yangtools.yang.common.YangVersion;
19 import org.opendaylight.yangtools.yang.model.api.DeviateKind;
20 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
21 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
22 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
23 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
25 import org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator;
26 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractDeclaredStatement;
27 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
28 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
36 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
37 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
38 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
39 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
40 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.DeviateEffectiveStatementImpl;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class DeviateStatementImpl extends AbstractDeclaredStatement<DeviateKind> implements DeviateStatement {
45     private static final Logger LOG = LoggerFactory.getLogger(DeviateStatementImpl.class);
46
47     private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
48             SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
49
50     private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
51             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
52                 .addOptional(YangStmtMapping.CONFIG)
53                 .addOptional(YangStmtMapping.DEFAULT)
54                 .addOptional(YangStmtMapping.MANDATORY)
55                 .addOptional(YangStmtMapping.MAX_ELEMENTS)
56                 .addOptional(YangStmtMapping.MIN_ELEMENTS)
57                 .addAny(YangStmtMapping.MUST)
58                 .addAny(YangStmtMapping.UNIQUE)
59                 .addOptional(YangStmtMapping.UNITS)
60                 .build();
61
62     private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
63             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
64                 .addOptional(YangStmtMapping.CONFIG)
65                 .addOptional(YangStmtMapping.DEFAULT)
66                 .addOptional(YangStmtMapping.MANDATORY)
67                 .addOptional(YangStmtMapping.MAX_ELEMENTS)
68                 .addOptional(YangStmtMapping.MIN_ELEMENTS)
69                 .addOptional(YangStmtMapping.TYPE)
70                 .addOptional(YangStmtMapping.UNITS)
71                 .build();
72
73     private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
74             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
75                 .addOptional(YangStmtMapping.DEFAULT)
76                 .addAny(YangStmtMapping.MUST)
77                 .addAny(YangStmtMapping.UNIQUE)
78                 .addOptional(YangStmtMapping.UNITS)
79                 .build();
80
81     protected DeviateStatementImpl(final StmtContext<DeviateKind, DeviateStatement, ?> context) {
82         super(context);
83     }
84
85     public static class Definition extends AbstractStatementSupport<DeviateKind, DeviateStatement,
86             EffectiveStatement<DeviateKind, DeviateStatement>> {
87
88         private static final Set<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
89                 YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
90                 YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
91
92         public Definition() {
93             super(YangStmtMapping.DEVIATE);
94         }
95
96         @Override public DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
97             return Utils.parseDeviateFromString(ctx, value);
98         }
99
100         @Override public DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx) {
101             return new DeviateStatementImpl(ctx);
102         }
103
104         @Override public EffectiveStatement<DeviateKind, DeviateStatement> createEffective(
105                 final StmtContext<DeviateKind, DeviateStatement, EffectiveStatement<DeviateKind,
106                         DeviateStatement>> ctx) {
107             return new DeviateEffectiveStatementImpl(ctx);
108         }
109
110         @Override
111         public void onFullDefinitionDeclared(final StmtContext.Mutable<DeviateKind, DeviateStatement,
112                 EffectiveStatement<DeviateKind, DeviateStatement>> deviateStmtCtx) {
113             final DeviateKind deviateKind = deviateStmtCtx.getStatementArgument();
114             getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
115
116             final SchemaNodeIdentifier deviationTarget =
117                     (SchemaNodeIdentifier) deviateStmtCtx.getParentContext().getStatementArgument();
118
119             if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
120                 return;
121             }
122
123             final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
124                     ModelProcessingPhase.EFFECTIVE_MODEL);
125
126             final Prerequisite<StmtContext<DeviateKind, DeviateStatement, EffectiveStatement<DeviateKind,
127                     DeviateStatement>>> sourceCtxPrerequisite =
128                     deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
129
130             final Prerequisite<StmtContext.Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
131                     (Prerequisite<StmtContext.Mutable<?, ?, EffectiveStatement<?, ?>>>) deviateAction
132                     .mutatesEffectiveCtx(deviateStmtCtx.getRoot(), SchemaNodeIdentifierBuildNamespace.class,
133                             deviationTarget);
134
135                     deviateAction.apply(new InferenceAction() {
136                         @Override
137                         public void apply() throws InferenceException {
138                             // FIXME once BUG-7760 gets fixed, there will be no need for these dirty casts
139                             final StatementContextBase<?, ?, ?> sourceNodeStmtCtx =
140                                     (StatementContextBase<?, ?, ?>) sourceCtxPrerequisite.get();
141                             final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
142                                     (StatementContextBase<?, ?, ?>) targetCtxPrerequisite.get();
143
144                             switch (deviateKind) {
145                                 case NOT_SUPPORTED:
146                                     targetNodeStmtCtx.setIsSupportedToBuildEffective(false);
147                                     break;
148                                 case ADD:
149                                     performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
150                                     break;
151                                 case REPLACE:
152                                     performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
153                                     break;
154                                 case DELETE:
155                                     performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
156                             }
157                         }
158
159                         @Override
160                         public void prerequisiteFailed(Collection<? extends Prerequisite<?>> failed) {
161                             throw new InferenceException(deviateStmtCtx.getParentContext().getStatementSourceReference(),
162                                     "Deviation target '%s' not found.", deviationTarget);
163                         }
164                     });
165         }
166
167         private static boolean isDeviationSupported(final StmtContext.Mutable<DeviateKind, DeviateStatement,
168                 EffectiveStatement<DeviateKind, DeviateStatement>> deviateStmtCtx,
169                 final SchemaNodeIdentifier deviationTarget) {
170             final Map<QNameModule, Set<QNameModule>> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
171                     ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES);
172             if (modulesDeviatedByModules == null) {
173                 return true;
174             }
175
176             final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ModuleCtxToModuleQName.class,
177                     deviateStmtCtx.getRoot());
178             final QNameModule targetModule = deviationTarget.getLastComponent().getModule();
179
180             final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
181             if (deviationModulesSupportedByTargetModule != null) {
182                 return deviationModulesSupportedByTargetModule.contains(currentModule);
183             }
184
185             return false;
186         }
187
188         private static void performDeviateAdd(final StatementContextBase<?, ?, ?> deviateStmtCtx,
189                 final StatementContextBase<?, ?, ?> targetCtx) {
190             for (StatementContextBase<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
191                 validateDeviationTarget(originalStmtCtx, targetCtx);
192                 addStatement(originalStmtCtx, targetCtx);
193             }
194         }
195
196         private static void addStatement(final StatementContextBase<?, ?, ?> stmtCtxToBeAdded,
197                 final StatementContextBase<?, ?, ?> targetCtx) {
198             if (StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
199                 targetCtx.addEffectiveSubstatement(stmtCtxToBeAdded.createCopy(targetCtx, CopyType.ORIGINAL));
200                 return;
201             }
202
203             final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.getPublicDefinition();
204
205             if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || (YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
206                     && YangStmtMapping.LEAF.equals(targetCtx.getPublicDefinition()))) {
207                 final Iterable<StatementContextBase<?, ?, ?>> targetCtxSubstatements = Iterables.concat(
208                         targetCtx.declaredSubstatements(), targetCtx.effectiveSubstatements());
209
210                 for (final StatementContextBase<?, ?, ?> targetCtxSubstatement : targetCtxSubstatements) {
211                     InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.getPublicDefinition()),
212                             stmtCtxToBeAdded.getStatementSourceReference(), "Deviation cannot add substatement %s " +
213                             "to target node %s because it is already defined in target and can appear only once.",
214                             stmtToBeAdded.getStatementName(), targetCtx.getStatementArgument());
215                 }
216             }
217
218             targetCtx.addEffectiveSubstatement(stmtCtxToBeAdded.createCopy(targetCtx, CopyType.ORIGINAL));
219         }
220
221         private static void performDeviateReplace(final StatementContextBase<?, ?, ?> deviateStmtCtx,
222                 final StatementContextBase<?, ?, ?> targetCtx) {
223             for (StatementContextBase<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
224                 validateDeviationTarget(originalStmtCtx, targetCtx);
225                 replaceStatement(originalStmtCtx, targetCtx);
226             }
227         }
228
229         private static void replaceStatement(final StatementContextBase<?, ?, ?> stmtCtxToBeReplaced,
230                 final StatementContextBase<?, ?, ?> targetCtx) {
231             final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.getPublicDefinition();
232
233             if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
234                     && YangStmtMapping.LEAF_LIST.equals(targetCtx.getPublicDefinition())) {
235                 LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can " +
236                         "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
237                         targetCtx.getStatementArgument(), stmtCtxToBeReplaced.getStatementSourceReference());
238                 return;
239             }
240
241             for (final StatementContextBase<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
242                 if (stmtToBeReplaced.equals(targetCtxSubstatement.getPublicDefinition())) {
243                     targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
244                     targetCtx.addEffectiveSubstatement(stmtCtxToBeReplaced.createCopy(targetCtx, CopyType.ORIGINAL));
245                     return;
246                 }
247             }
248
249             for (final StatementContextBase<?, ?, ?> targetCtxSubstatement : targetCtx.declaredSubstatements()) {
250                 if (stmtToBeReplaced.equals(targetCtxSubstatement.getPublicDefinition())) {
251                     targetCtxSubstatement.setIsSupportedToBuildEffective(false);
252                     targetCtx.addEffectiveSubstatement(stmtCtxToBeReplaced.createCopy(targetCtx, CopyType.ORIGINAL));
253                     return;
254                 }
255             }
256
257             throw new InferenceException(stmtCtxToBeReplaced.getStatementSourceReference(), "Deviation cannot " +
258                     "replace substatement %s in target node %s because it does not exist in target node.",
259                     stmtToBeReplaced.getStatementName(), targetCtx.getStatementArgument());
260         }
261
262         private static void performDeviateDelete(final StatementContextBase<?, ?, ?> deviateStmtCtx,
263                 final StatementContextBase<?, ?, ?> targetCtx) {
264             for (StatementContextBase<?, ?, ?> originalStmtCtx : deviateStmtCtx.declaredSubstatements()) {
265                 validateDeviationTarget(originalStmtCtx, targetCtx);
266                 deleteStatement(originalStmtCtx, targetCtx);
267             }
268         }
269
270         private static void deleteStatement(final StatementContextBase<?, ?, ?> stmtCtxToBeDeleted,
271                 final StatementContextBase<?, ?, ?> targetCtx) {
272             final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.getPublicDefinition();
273             final String stmtArgument = stmtCtxToBeDeleted.rawStatementArgument();
274
275             for (final StatementContextBase<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
276                 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.getPublicDefinition(),
277                         targetCtxSubstatement.rawStatementArgument())) {
278                     targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
279                     return;
280                 }
281             }
282
283             for (final StatementContextBase<?, ?, ?> targetCtxSubstatement : targetCtx.declaredSubstatements()) {
284                 if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.getPublicDefinition(),
285                         targetCtxSubstatement.rawStatementArgument())) {
286                     targetCtxSubstatement.setIsSupportedToBuildEffective(false);
287                     return;
288                 }
289             }
290
291             LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does " +
292                     "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
293                     targetCtx.getStatementArgument(), stmtCtxToBeDeleted.getStatementSourceReference());
294         }
295
296         private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
297                 final StatementDefinition secondStmtDef, final String secondStmtArg) {
298             return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
299         }
300
301         private static void validateDeviationTarget(final StatementContextBase<?, ?, ?> deviateSubStmtCtx,
302                 final StatementContextBase<?, ?, ?> targetCtx) {
303             InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
304                     targetCtx.getRootVersion()), deviateSubStmtCtx.getStatementSourceReference(),
305                     "%s is not a valid deviation target for substatement %s.",
306                     targetCtx.getStatementArgument(), deviateSubStmtCtx.getPublicDefinition().getStatementName());
307         }
308
309         private static boolean isSupportedDeviationTarget(final StatementContextBase<?, ?, ?> deviateSubstatementCtx,
310                 final StatementContextBase<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
311             Set<StatementDefinition> supportedDeviationTargets =
312                     YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(deviateTargetCtx.getRootVersion(),
313                             deviateSubstatementCtx.getPublicDefinition());
314
315             if (supportedDeviationTargets == null) {
316                 supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
317                         deviateSubstatementCtx.getPublicDefinition());
318             }
319
320             // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
321             return supportedDeviationTargets == null || supportedDeviationTargets.contains(
322                     deviateTargetCtx.getPublicDefinition());
323         }
324
325         protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
326             switch (deviateKind) {
327                 case NOT_SUPPORTED:
328                     return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
329                 case ADD:
330                     return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
331                 case REPLACE:
332                     return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
333                 case DELETE:
334                     return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
335                 default:
336                     throw new IllegalStateException(String.format(
337                             "Substatement validator for deviate %s has not been defined.", deviateKind));
338             }
339         }
340
341         @Override
342         protected SubstatementValidator getSubstatementValidator() {
343             return null;
344         }
345     }
346
347     @Nonnull @Override
348     public DeviateKind getValue() {
349         return argument();
350     }
351 }