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