Promote more declared statements to yang-parser-spi
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / deviate / AbstractDeviateStatementSupport.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. 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.rfc7950.stmt.deviate;
9
10 import com.google.common.collect.ImmutableList;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.collect.Iterables;
14 import com.google.common.collect.Maps;
15 import com.google.common.collect.SetMultimap;
16 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.Objects;
20 import java.util.Set;
21 import org.opendaylight.yangtools.yang.common.QNameModule;
22 import org.opendaylight.yangtools.yang.common.YangVersion;
23 import org.opendaylight.yangtools.yang.model.api.DeviateKind;
24 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
25 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
28 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateEffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.DeviateStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
31 import org.opendaylight.yangtools.yang.model.spi.stmt.DeclaredStatements;
32 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
33 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
50 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
51 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 abstract class AbstractDeviateStatementSupport
56         extends AbstractStatementSupport<DeviateKind, DeviateStatement, DeviateEffectiveStatement> {
57     private static final Logger LOG = LoggerFactory.getLogger(AbstractDeviateStatementSupport.class);
58
59     private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
60             SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
61
62     private static final SubstatementValidator DEVIATE_ADD_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                 .addAny(YangStmtMapping.MUST)
70                 .addAny(YangStmtMapping.UNIQUE)
71                 .addOptional(YangStmtMapping.UNITS)
72                 .build();
73
74     private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
75             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
76                 .addOptional(YangStmtMapping.CONFIG)
77                 .addOptional(YangStmtMapping.DEFAULT)
78                 .addOptional(YangStmtMapping.MANDATORY)
79                 .addOptional(YangStmtMapping.MAX_ELEMENTS)
80                 .addOptional(YangStmtMapping.MIN_ELEMENTS)
81                 .addOptional(YangStmtMapping.TYPE)
82                 .addOptional(YangStmtMapping.UNITS)
83                 .build();
84
85     private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
86             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
87                 .addOptional(YangStmtMapping.DEFAULT)
88                 .addAny(YangStmtMapping.MUST)
89                 .addAny(YangStmtMapping.UNIQUE)
90                 .addOptional(YangStmtMapping.UNITS)
91                 .build();
92
93     private static final ImmutableMap<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP =
94             Maps.uniqueIndex(Arrays.asList(DeviateKind.values()), DeviateKind::getKeyword);
95
96     private static final ImmutableSet<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
97             YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
98             YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
99
100     private static final ImmutableSet<YangStmtMapping> IMPLICIT_STATEMENTS = ImmutableSet.of(YangStmtMapping.CONFIG,
101             YangStmtMapping.MANDATORY, YangStmtMapping.MAX_ELEMENTS, YangStmtMapping.MIN_ELEMENTS);
102
103     AbstractDeviateStatementSupport() {
104         super(YangStmtMapping.DEVIATE, StatementPolicy.contextIndependent());
105     }
106
107     @Override
108     public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
109         return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value), ctx,
110             "String '%s' is not valid deviate argument", value);
111     }
112
113     @Override
114     public final void onFullDefinitionDeclared(
115             final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx) {
116         final DeviateKind deviateKind = deviateStmtCtx.argument();
117         getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
118
119         final SchemaNodeIdentifier deviationTarget =
120                 (SchemaNodeIdentifier) deviateStmtCtx.coerceParentContext().argument();
121
122         if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
123             return;
124         }
125
126         final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
127                 ModelProcessingPhase.EFFECTIVE_MODEL);
128
129         final Prerequisite<StmtContext<DeviateKind, DeviateStatement,
130             DeviateEffectiveStatement>> sourceCtxPrerequisite =
131                 deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
132
133         final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
134                 deviateAction.mutatesEffectiveCtxPath(deviateStmtCtx.getRoot(),
135                     SchemaTreeNamespace.class, deviationTarget.getNodeIdentifiers());
136
137         deviateAction.apply(new InferenceAction() {
138             @Override
139             public void apply(final InferenceContext ctx) {
140                 // FIXME once BUG-7760 gets fixed, there will be no need for these dirty casts
141                 final StatementContextBase<?, ?, ?> sourceNodeStmtCtx =
142                         (StatementContextBase<?, ?, ?>) sourceCtxPrerequisite.resolve(ctx);
143                 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
144                         (StatementContextBase<?, ?, ?>) targetCtxPrerequisite.resolve(ctx);
145
146                 switch (deviateKind) {
147                     case NOT_SUPPORTED:
148                         targetNodeStmtCtx.setIsSupportedToBuildEffective(false);
149                         break;
150                     case ADD:
151                         performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
152                         break;
153                     case REPLACE:
154                         performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
155                         break;
156                     case DELETE:
157                         performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
158                         break;
159                     default:
160                         throw new IllegalStateException("Unsupported deviate " + deviateKind);
161                 }
162             }
163
164             @Override
165             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
166                 throw new InferenceException(deviateStmtCtx.coerceParentContext(), "Deviation target '%s' not found.",
167                     deviationTarget);
168             }
169         });
170     }
171
172     @Override
173     public String internArgument(final String rawArgument) {
174         if ("add".equals(rawArgument)) {
175             return "add";
176         } else if ("delete".equals(rawArgument)) {
177             return "delete";
178         } else if ("replace".equals(rawArgument)) {
179             return "replace";
180         } else if ("not-supported".equals(rawArgument)) {
181             return "not-supported";
182         } else {
183             return rawArgument;
184         }
185     }
186
187     @Override
188     protected final SubstatementValidator getSubstatementValidator() {
189         return null;
190     }
191
192     @Override
193     protected final DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx,
194             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
195         return DeclaredStatements.createDeviate(ctx.getArgument(), substatements);
196     }
197
198     @Override
199     protected final DeviateStatement createEmptyDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx) {
200         return DeclaredStatements.createDeviate(ctx.getArgument());
201     }
202
203     @Override
204     protected DeviateEffectiveStatement createEffective(final Current<DeviateKind, DeviateStatement> stmt,
205             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
206         return new DeviateEffectiveStatementImpl(stmt.declared(), substatements);
207     }
208
209     protected SubstatementValidator getSubstatementValidatorForDeviate(final DeviateKind deviateKind) {
210         switch (deviateKind) {
211             case NOT_SUPPORTED:
212                 return DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR;
213             case ADD:
214                 return DEVIATE_ADD_SUBSTATEMENT_VALIDATOR;
215             case REPLACE:
216                 return DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR;
217             case DELETE:
218                 return DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR;
219             default:
220                 throw new IllegalStateException(String.format(
221                         "Substatement validator for deviate %s has not been defined.", deviateKind));
222         }
223     }
224
225     private static boolean isDeviationSupported(
226             final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx,
227             final SchemaNodeIdentifier deviationTarget) {
228         final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules = deviateStmtCtx.getFromNamespace(
229                 ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES);
230         if (modulesDeviatedByModules == null) {
231             return true;
232         }
233
234         final QNameModule currentModule = deviateStmtCtx.getFromNamespace(ModuleCtxToModuleQName.class,
235                 deviateStmtCtx.getRoot());
236         final QNameModule targetModule = Iterables.getLast(deviationTarget.getNodeIdentifiers()).getModule();
237
238         final Set<QNameModule> deviationModulesSupportedByTargetModule = modulesDeviatedByModules.get(targetModule);
239         if (deviationModulesSupportedByTargetModule != null) {
240             return deviationModulesSupportedByTargetModule.contains(currentModule);
241         }
242
243         return false;
244     }
245
246     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
247             justification = "https://github.com/spotbugs/spotbugs/issues/811")
248     private static void performDeviateAdd(final StatementContextBase<?, ?, ?> deviateStmtCtx,
249             final StatementContextBase<?, ?, ?> targetCtx) {
250         for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
251             validateDeviationTarget(originalStmtCtx, targetCtx);
252             addStatement(originalStmtCtx, targetCtx);
253         }
254     }
255
256     private static void addStatement(final Mutable<?, ?, ?> stmtCtxToBeAdded,
257             final StatementContextBase<?, ?, ?> targetCtx) {
258         if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeAdded)) {
259             final StatementDefinition stmtToBeAdded = stmtCtxToBeAdded.publicDefinition();
260             if (SINGLETON_STATEMENTS.contains(stmtToBeAdded) || YangStmtMapping.DEFAULT.equals(stmtToBeAdded)
261                     && YangStmtMapping.LEAF.equals(targetCtx.publicDefinition())) {
262                 for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
263                     InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.publicDefinition()),
264                         stmtCtxToBeAdded,
265                         "Deviation cannot add substatement %s to target node %s because it is already defined "
266                         + "in target and can appear only once.",
267                         stmtToBeAdded.getStatementName(), targetCtx.argument());
268                 }
269             }
270         }
271
272         copyStatement(stmtCtxToBeAdded, targetCtx);
273     }
274
275     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
276             justification = "https://github.com/spotbugs/spotbugs/issues/811")
277     private static void performDeviateReplace(final StatementContextBase<?, ?, ?> deviateStmtCtx,
278             final StatementContextBase<?, ?, ?> targetCtx) {
279         for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
280             validateDeviationTarget(originalStmtCtx, targetCtx);
281             replaceStatement(originalStmtCtx, targetCtx);
282         }
283     }
284
285     private static void replaceStatement(final Mutable<?, ?, ?> stmtCtxToBeReplaced,
286             final StatementContextBase<?, ?, ?> targetCtx) {
287         final StatementDefinition stmtToBeReplaced = stmtCtxToBeReplaced.publicDefinition();
288
289         if (YangStmtMapping.DEFAULT.equals(stmtToBeReplaced)
290                 && YangStmtMapping.LEAF_LIST.equals(targetCtx.publicDefinition())) {
291             LOG.error("Deviation cannot replace substatement {} in target leaf-list {} because a leaf-list can "
292                     + "have multiple default statements. At line: {}", stmtToBeReplaced.getStatementName(),
293                     targetCtx.argument(), stmtCtxToBeReplaced.sourceReference());
294             return;
295         }
296
297         for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.effectiveSubstatements()) {
298             if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
299                 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeReplaced);
300                 copyStatement(stmtCtxToBeReplaced, targetCtx);
301                 return;
302             }
303         }
304
305         for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
306             if (stmtToBeReplaced.equals(targetCtxSubstatement.publicDefinition())) {
307                 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
308                 copyStatement(stmtCtxToBeReplaced, targetCtx);
309                 return;
310             }
311         }
312
313         // This is a special case when deviate replace of a config/mandatory/max/min-elements substatement targets
314         // a node which does not contain an explicitly declared config/mandatory/max/min-elements.
315         // However, according to RFC6020/RFC7950, these properties are always implicitly present.
316         if (IMPLICIT_STATEMENTS.contains(stmtToBeReplaced)) {
317             addStatement(stmtCtxToBeReplaced, targetCtx);
318             return;
319         }
320
321         throw new InferenceException(stmtCtxToBeReplaced,
322             "Deviation cannot replace substatement %s in target node %s because it does not exist in target node.",
323             stmtToBeReplaced.getStatementName(), targetCtx.argument());
324     }
325
326     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
327             justification = "https://github.com/spotbugs/spotbugs/issues/811")
328     private static void performDeviateDelete(final StatementContextBase<?, ?, ?> deviateStmtCtx,
329             final StatementContextBase<?, ?, ?> targetCtx) {
330         for (Mutable<?, ?, ?> originalStmtCtx : deviateStmtCtx.mutableDeclaredSubstatements()) {
331             validateDeviationTarget(originalStmtCtx, targetCtx);
332             deleteStatement(originalStmtCtx, targetCtx);
333         }
334     }
335
336     private static void deleteStatement(final StmtContext<?, ?, ?> stmtCtxToBeDeleted,
337             final StatementContextBase<?, ?, ?> targetCtx) {
338         final StatementDefinition stmtToBeDeleted = stmtCtxToBeDeleted.publicDefinition();
339         final String stmtArgument = stmtCtxToBeDeleted.rawArgument();
340
341         for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableEffectiveSubstatements()) {
342             if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
343                     targetCtxSubstatement.rawArgument())) {
344                 targetCtx.removeStatementFromEffectiveSubstatements(stmtToBeDeleted, stmtArgument);
345                 return;
346             }
347         }
348
349         for (final Mutable<?, ?, ?> targetCtxSubstatement : targetCtx.mutableDeclaredSubstatements()) {
350             if (statementsAreEqual(stmtToBeDeleted, stmtArgument, targetCtxSubstatement.publicDefinition(),
351                     targetCtxSubstatement.rawArgument())) {
352                 targetCtxSubstatement.setIsSupportedToBuildEffective(false);
353                 return;
354             }
355         }
356
357         LOG.error("Deviation cannot delete substatement {} with argument '{}' in target node {} because it does "
358                 + "not exist in the target node. At line: {}", stmtToBeDeleted.getStatementName(), stmtArgument,
359                 targetCtx.argument(), stmtCtxToBeDeleted.sourceReference());
360     }
361
362     private static void copyStatement(final Mutable<?, ?, ?> stmtCtxToBeCopied,
363             final StatementContextBase<?, ?, ?> targetCtx) {
364         // we need to make a copy of the statement context only if it is an unknown statement, otherwise
365         // we can reuse the original statement context
366         if (!StmtContextUtils.isUnknownStatement(stmtCtxToBeCopied)) {
367             targetCtx.addEffectiveSubstatement(stmtCtxToBeCopied.replicaAsChildOf(targetCtx));
368         } else {
369             targetCtx.addEffectiveSubstatement(targetCtx.childCopyOf(stmtCtxToBeCopied, CopyType.ORIGINAL));
370         }
371     }
372
373     private static boolean statementsAreEqual(final StatementDefinition firstStmtDef, final String firstStmtArg,
374             final StatementDefinition secondStmtDef, final String secondStmtArg) {
375         return firstStmtDef.equals(secondStmtDef) && Objects.equals(firstStmtArg, secondStmtArg);
376     }
377
378     private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
379             final StmtContext<?, ?, ?> targetCtx) {
380         InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
381             targetCtx.yangVersion()), deviateSubStmtCtx,
382             "%s is not a valid deviation target for substatement %s.", targetCtx.argument(),
383             deviateSubStmtCtx.publicDefinition().getStatementName());
384     }
385
386     private static boolean isSupportedDeviationTarget(final StmtContext<?, ?, ?> deviateSubstatementCtx,
387             final StmtContext<?, ?, ?> deviateTargetCtx, final YangVersion yangVersion) {
388         Set<StatementDefinition> supportedDeviationTargets =
389                 YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(yangVersion,
390                         deviateSubstatementCtx.publicDefinition());
391
392         if (supportedDeviationTargets == null) {
393             supportedDeviationTargets = YangValidationBundles.SUPPORTED_DEVIATION_TARGETS.get(YangVersion.VERSION_1,
394                     deviateSubstatementCtx.publicDefinition());
395         }
396
397         // if supportedDeviationTargets is null, it means that the deviate substatement is an unknown statement
398         return supportedDeviationTargets == null || supportedDeviationTargets.contains(
399                 deviateTargetCtx.publicDefinition());
400     }
401 }