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