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