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