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