CopyHistory and yangVersion merge
[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.parser.rfc7950.reactor.YangValidationBundles;
32 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
33 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
47 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
48 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
49 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
50 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 abstract class AbstractDeviateStatementSupport
55         extends BaseStatementSupport<DeviateKind, DeviateStatement, DeviateEffectiveStatement> {
56     private static final Logger LOG = LoggerFactory.getLogger(AbstractDeviateStatementSupport.class);
57
58     private static final SubstatementValidator DEVIATE_NOT_SUPPORTED_SUBSTATEMENT_VALIDATOR =
59             SubstatementValidator.builder(YangStmtMapping.DEVIATE).build();
60
61     private static final SubstatementValidator DEVIATE_ADD_SUBSTATEMENT_VALIDATOR =
62             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
63                 .addOptional(YangStmtMapping.CONFIG)
64                 .addOptional(YangStmtMapping.DEFAULT)
65                 .addOptional(YangStmtMapping.MANDATORY)
66                 .addOptional(YangStmtMapping.MAX_ELEMENTS)
67                 .addOptional(YangStmtMapping.MIN_ELEMENTS)
68                 .addAny(YangStmtMapping.MUST)
69                 .addAny(YangStmtMapping.UNIQUE)
70                 .addOptional(YangStmtMapping.UNITS)
71                 .build();
72
73     private static final SubstatementValidator DEVIATE_REPLACE_SUBSTATEMENT_VALIDATOR =
74             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
75                 .addOptional(YangStmtMapping.CONFIG)
76                 .addOptional(YangStmtMapping.DEFAULT)
77                 .addOptional(YangStmtMapping.MANDATORY)
78                 .addOptional(YangStmtMapping.MAX_ELEMENTS)
79                 .addOptional(YangStmtMapping.MIN_ELEMENTS)
80                 .addOptional(YangStmtMapping.TYPE)
81                 .addOptional(YangStmtMapping.UNITS)
82                 .build();
83
84     private static final SubstatementValidator DEVIATE_DELETE_SUBSTATEMENT_VALIDATOR =
85             SubstatementValidator.builder(YangStmtMapping.DEVIATE)
86                 .addOptional(YangStmtMapping.DEFAULT)
87                 .addAny(YangStmtMapping.MUST)
88                 .addAny(YangStmtMapping.UNIQUE)
89                 .addOptional(YangStmtMapping.UNITS)
90                 .build();
91
92     private static final ImmutableMap<String, DeviateKind> KEYWORD_TO_DEVIATE_MAP =
93             Maps.uniqueIndex(Arrays.asList(DeviateKind.values()), DeviateKind::getKeyword);
94
95     private static final ImmutableSet<YangStmtMapping> SINGLETON_STATEMENTS = ImmutableSet.of(
96             YangStmtMapping.UNITS, YangStmtMapping.CONFIG, YangStmtMapping.MANDATORY,
97             YangStmtMapping.MIN_ELEMENTS, YangStmtMapping.MAX_ELEMENTS);
98
99     private static final ImmutableSet<YangStmtMapping> IMPLICIT_STATEMENTS = ImmutableSet.of(YangStmtMapping.CONFIG,
100             YangStmtMapping.MANDATORY, YangStmtMapping.MAX_ELEMENTS, YangStmtMapping.MIN_ELEMENTS);
101
102     AbstractDeviateStatementSupport() {
103         super(YangStmtMapping.DEVIATE);
104     }
105
106     @Override
107     public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
108         return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value), ctx.sourceReference(),
109             "String '%s' is not valid deviate argument", value);
110     }
111
112     @Override
113     public final void onFullDefinitionDeclared(
114             final Mutable<DeviateKind, DeviateStatement, DeviateEffectiveStatement> deviateStmtCtx) {
115         final DeviateKind deviateKind = deviateStmtCtx.argument();
116         getSubstatementValidatorForDeviate(deviateKind).validate(deviateStmtCtx);
117
118         final SchemaNodeIdentifier deviationTarget =
119                 (SchemaNodeIdentifier) deviateStmtCtx.coerceParentContext().argument();
120
121         if (!isDeviationSupported(deviateStmtCtx, deviationTarget)) {
122             return;
123         }
124
125         final ModelActionBuilder deviateAction = deviateStmtCtx.newInferenceAction(
126                 ModelProcessingPhase.EFFECTIVE_MODEL);
127
128         final Prerequisite<StmtContext<DeviateKind, DeviateStatement,
129             DeviateEffectiveStatement>> sourceCtxPrerequisite =
130                 deviateAction.requiresCtx(deviateStmtCtx, ModelProcessingPhase.EFFECTIVE_MODEL);
131
132         final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> targetCtxPrerequisite =
133                 deviateAction.mutatesEffectiveCtxPath(deviateStmtCtx.getRoot(),
134                     SchemaTreeNamespace.class, deviationTarget.getNodeIdentifiers());
135
136         deviateAction.apply(new InferenceAction() {
137             @Override
138             public void apply(final InferenceContext ctx) {
139                 // FIXME once BUG-7760 gets fixed, there will be no need for these dirty casts
140                 final StatementContextBase<?, ?, ?> sourceNodeStmtCtx =
141                         (StatementContextBase<?, ?, ?>) sourceCtxPrerequisite.resolve(ctx);
142                 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
143                         (StatementContextBase<?, ?, ?>) targetCtxPrerequisite.resolve(ctx);
144
145                 switch (deviateKind) {
146                     case NOT_SUPPORTED:
147                         targetNodeStmtCtx.setIsSupportedToBuildEffective(false);
148                         break;
149                     case ADD:
150                         performDeviateAdd(sourceNodeStmtCtx, targetNodeStmtCtx);
151                         break;
152                     case REPLACE:
153                         performDeviateReplace(sourceNodeStmtCtx, targetNodeStmtCtx);
154                         break;
155                     case DELETE:
156                         performDeviateDelete(sourceNodeStmtCtx, targetNodeStmtCtx);
157                         break;
158                     default:
159                         throw new IllegalStateException("Unsupported deviate " + deviateKind);
160                 }
161             }
162
163             @Override
164             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
165                 throw new InferenceException(deviateStmtCtx.coerceParentContext().sourceReference(),
166                     "Deviation target '%s' not found.", deviationTarget);
167             }
168         });
169     }
170
171     @Override
172     public String internArgument(final String rawArgument) {
173         if ("add".equals(rawArgument)) {
174             return "add";
175         } else if ("delete".equals(rawArgument)) {
176             return "delete";
177         } else if ("replace".equals(rawArgument)) {
178             return "replace";
179         } else if ("not-supported".equals(rawArgument)) {
180             return "not-supported";
181         } else {
182             return rawArgument;
183         }
184     }
185
186     @Override
187     protected final SubstatementValidator getSubstatementValidator() {
188         return null;
189     }
190
191     @Override
192     protected final DeviateStatement createDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx,
193             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
194         return new DeviateStatementImpl(ctx.getRawArgument(), ctx.getArgument(), substatements);
195     }
196
197     @Override
198     protected final DeviateStatement createEmptyDeclared(final StmtContext<DeviateKind, DeviateStatement, ?> ctx) {
199         // This is exceedingly unlikely, just reuse the implementation
200         return createDeclared(ctx, ImmutableList.of());
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.sourceReference(),
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.sourceReference(), "Deviation cannot replace "
322                 + "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.sourceReference(),
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 }