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