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