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