Move DeviateKind parsing
[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.Prerequisite;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
38 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
39 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
40 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
41 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
42 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
43 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.DeviateEffectiveStatementImpl;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class DeviateStatementImpl extends AbstractDeclaredStatement<DeviateKind> implements DeviateStatement {
48     private static final Logger LOG = LoggerFactory.getLogger(DeviateStatementImpl.class);
49
50     private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
51             SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
52
53     private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
54             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
55                 .addOptional(YangStmtMapping.CONFIG)
56                 .addOptional(YangStmtMapping.DEFAULT)
57                 .addOptional(YangStmtMapping.MANDATORY)
58                 .addOptional(YangStmtMapping.MAX_ELEMENTS)
59                 .addOptional(YangStmtMapping.MIN_ELEMENTS)
60                 .addAny(YangStmtMapping.MUST)
61                 .addAny(YangStmtMapping.UNIQUE)
62                 .addOptional(YangStmtMapping.UNITS)
63                 .build();
64
65     private static final SubstatementValidator DEVIATE_REPLACE_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                 .addOptional(YangStmtMapping.TYPE)
73                 .addOptional(YangStmtMapping.UNITS)
74                 .build();
75
76     private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
77             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
78                 .addOptional(YangStmtMapping.DEFAULT)
79                 .addAny(YangStmtMapping.MUST)
80                 .addAny(YangStmtMapping.UNIQUE)
81                 .addOptional(YangStmtMapping.UNITS)
82                 .build();
83
84     protected DeviateStatementImpl(final StmtContext<DeviateKind, DeviateStatement, ?> context) {
85         super(context);
86     }
87
88     public static class Definition extends AbstractStatementSupport<DeviateKind, DeviateStatement,
89             EffectiveStatement<DeviateKind, DeviateStatement>> {
90         private static final Map<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP;
91         static {
92             final Builder<String, DeviateKind> keywordToDeviateMapBuilder = ImmutableMap.builder();
93             for (final DeviateKind deviate : DeviateKind.values()) {
94                 keywordToDeviateMapBuilder.put(deviate.getKeyword(), deviate);
95             }
96             KEYWORD_TO_DEVIATE_MAP = keywordToDeviateMapBuilder.build();
97         }
98
99         private static final Set<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
100                 YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
101                 YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
102
103         public Definition() {
104             super(YangStmtMapping.DEVIATE);
105         }
106
107         @Override
108         public DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
109             return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value),
110                 ctx.getStatementSourceReference(), "String '%s' is not valid deviate argument", value);
111         }
112
113         @Override
114         public DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx) {
115             return new DeviateStatementImpl(ctx);
116         }
117
118         @Override
119         public EffectiveStatement<DeviateKind, DeviateStatement> createEffective(
120                 final StmtContext<DeviateKind, DeviateStatement, EffectiveStatement<DeviateKind,
121                         DeviateStatement>> ctx) {
122             return new DeviateEffectiveStatementImpl(ctx);
123         }
124
125         @Override
126         public void onFullDefinitionDeclared(final StmtContext.Mutable<DeviateKind, DeviateStatement,
127                 EffectiveStatement<DeviateKind, DeviateStatement>> deviateStmtCtx) {
128             final DeviateKind deviateKind = deviateStmtCtx.getStatementArgument();
129             getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
130
131             final SchemaNodeIdentifier deviationTarget =
132                     (SchemaNodeIdentifier) deviateStmtCtx.getParentContext().getStatementArgument();
133
134             if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
135                 return;
136             }
137
138             final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
139                     ModelProcessingPhase.EFFECTIVE_MODEL);
140
141             final Prerequisite<StmtContext<DeviateKind, DeviateStatement, EffectiveStatement<DeviateKind,
142                     DeviateStatement>>> sourceCtxPrerequisite =
143                     deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
144
145             final Prerequisite<StmtContext.Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
146                     deviateAction
147             .mutatesEffectiveCtx(deviateStmtCtx.getRoot(), SchemaNodeIdentifierBuildNamespace.class,
148                     deviationTarget);
149
150                     deviateAction.apply(new InferenceAction() {
151                         @Override
152                         public void apply() 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.get();
156                             final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
157                                     (StatementContextBase<?, ?, ?>) targetCtxPrerequisite.get();
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 StatementContextBase<?, ?, ?> 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 StatementContextBase<?, ?, ?> deviateSubStmtCtx,
317                 final StatementContextBase<?, ?, ?> 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 StatementContextBase<?, ?, ?> deviateSubstatementCtx,
325                 final StatementContextBase<?, ?, ?> 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 }