Refactor InferenceAction
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / rfc6020 / UsesStatementImpl.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.ImmutableSet;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.Set;
14 import javax.annotation.Nonnull;
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.common.QNameModule;
17 import org.opendaylight.yangtools.yang.common.YangVersion;
18 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
19 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
20 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
21 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
22 import org.opendaylight.yangtools.yang.model.api.stmt.DescriptionStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.IfFeatureStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.ReferenceStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
27 import org.opendaylight.yangtools.yang.model.api.stmt.StatusStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.WhenStatement;
30 import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace;
31 import org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractDeclaredStatement;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
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.source.ModuleCtxToModuleQName;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
46 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
47 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
48 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
49 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.UsesEffectiveStatementImpl;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53
54 public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implements UsesStatement {
55     private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(YangStmtMapping
56             .USES)
57             .addAny(YangStmtMapping.AUGMENT)
58             .addOptional(YangStmtMapping.DESCRIPTION)
59             .addAny(YangStmtMapping.IF_FEATURE)
60             .addAny(YangStmtMapping.REFINE)
61             .addOptional(YangStmtMapping.REFERENCE)
62             .addOptional(YangStmtMapping.STATUS)
63             .addOptional(YangStmtMapping.WHEN)
64             .build();
65
66     private static final Logger LOG = LoggerFactory.getLogger(UsesStatementImpl.class);
67
68     protected UsesStatementImpl(final StmtContext<QName, UsesStatement, ?> context) {
69         super(context);
70     }
71
72     public static class Definition extends
73             AbstractStatementSupport<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> {
74
75         public Definition() {
76             super(YangStmtMapping.USES);
77         }
78
79         @Override
80         public QName parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
81             return Utils.qNameFromArgument(ctx, value);
82         }
83
84         @Override
85         public void onFullDefinitionDeclared(
86                 final StmtContext.Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode) {
87             if (!StmtContextUtils.areFeaturesSupported(usesNode)) {
88                 return;
89             }
90             super.onFullDefinitionDeclared(usesNode);
91
92             if (StmtContextUtils.isInExtensionBody(usesNode)) {
93                 return;
94             }
95
96             final ModelActionBuilder usesAction = usesNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
97             final QName groupingName = usesNode.getStatementArgument();
98
99             final Prerequisite<StmtContext<?, ?, ?>> sourceGroupingPre = usesAction.requiresCtx(usesNode,
100                     GroupingNamespace.class, groupingName, ModelProcessingPhase.EFFECTIVE_MODEL);
101             final Prerequisite<? extends StmtContext.Mutable<?, ?, ?>> targetNodePre = usesAction.mutatesEffectiveCtx(
102                     usesNode.getParentContext());
103
104             usesAction.apply(new InferenceAction() {
105
106                 @Override
107                 public void apply(final InferenceContext ctx) {
108                     final StatementContextBase<?, ?, ?> targetNodeStmtCtx = (StatementContextBase<?, ?, ?>) targetNodePre.resolve(ctx);
109                     final StatementContextBase<?, ?, ?> sourceGrpStmtCtx = (StatementContextBase<?, ?, ?>) sourceGroupingPre.resolve(ctx);
110
111                     try {
112                         copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode);
113                         resolveUsesNode(usesNode, targetNodeStmtCtx);
114                         StmtContextUtils.validateIfFeatureAndWhenOnListKeys(usesNode);
115                     } catch (final SourceException e) {
116                         LOG.warn(e.getMessage(), e);
117                         throw e;
118                     }
119                 }
120
121                 @Override
122                 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
123                     InferenceException.throwIf(failed.contains(sourceGroupingPre),
124                             usesNode.getStatementSourceReference(), "Grouping '%s' was not resolved.", groupingName);
125                     throw new InferenceException("Unknown error occurred.", usesNode.getStatementSourceReference());
126                 }
127             });
128         }
129
130         @Override
131         public UsesStatement createDeclared(final StmtContext<QName, UsesStatement, ?> ctx) {
132             return new UsesStatementImpl(ctx);
133         }
134
135         @Override
136         public EffectiveStatement<QName, UsesStatement> createEffective(
137                 final StmtContext<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> ctx) {
138             return new UsesEffectiveStatementImpl(ctx);
139         }
140
141         @Override
142         protected SubstatementValidator getSubstatementValidator() {
143             return SUBSTATEMENT_VALIDATOR;
144         }
145
146     }
147
148     @Nonnull
149     @Override
150     public QName getName() {
151         return argument();
152     }
153
154     @Override
155     public WhenStatement getWhenStatement() {
156         return firstDeclared(WhenStatement.class);
157     }
158
159     @Nonnull
160     @Override
161     public Collection<? extends IfFeatureStatement> getIfFeatures() {
162         return allDeclared(IfFeatureStatement.class);
163     }
164
165     @Override
166     public StatusStatement getStatus() {
167         return firstDeclared(StatusStatement.class);
168     }
169
170     @Override
171     public DescriptionStatement getDescription() {
172         return firstDeclared(DescriptionStatement.class);
173     }
174
175     @Override
176     public ReferenceStatement getReference() {
177         return firstDeclared(ReferenceStatement.class);
178     }
179
180     @Nonnull
181     @Override
182     public Collection<? extends AugmentStatement> getAugments() {
183         return allDeclared(AugmentStatement.class);
184     }
185
186     @Nonnull
187     @Override
188     public Collection<? extends RefineStatement> getRefines() {
189         return allDeclared(RefineStatement.class);
190     }
191
192     /**
193      * @param sourceGrpStmtCtx
194      *            source grouping statement context
195      * @param targetCtx
196      *            target context
197      * @param usesNode
198      *            uses node
199      * @throws SourceException
200      *             instance of SourceException
201      */
202     private static void copyFromSourceToTarget(final StmtContext<?, ?, ?> sourceGrpStmtCtx,
203             final StatementContextBase<?, ?, ?> targetCtx,
204             final StmtContext.Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode) {
205         final Collection<StatementContextBase<?, ?, ?>> declared = sourceGrpStmtCtx.declaredSubstatements();
206         final Collection<StatementContextBase<?, ?, ?>> effective = sourceGrpStmtCtx.effectiveSubstatements();
207         final Collection<StatementContextBase<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
208         final QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
209
210         for (final StatementContextBase<?, ?, ?> original : declared) {
211             if (StmtContextUtils.areFeaturesSupported(original)) {
212                 copyStatement(original, targetCtx, newQNameModule, buffer);
213             }
214         }
215
216         for (final StatementContextBase<?, ?, ?> original : effective) {
217             copyStatement(original, targetCtx, newQNameModule, buffer);
218         }
219
220         targetCtx.addEffectiveSubstatements(buffer);
221         usesNode.addAsEffectOfStatement(buffer);
222     }
223
224     private static void copyStatement(final StatementContextBase<?, ?, ?> original,
225             final StatementContextBase<?, ?, ?> targetCtx, final QNameModule targetModule,
226             final Collection<StatementContextBase<?, ?, ?>> buffer) {
227         if (needToCopyByUses(original)) {
228             final StatementContextBase<?, ?, ?> copy = original.createCopy(targetModule, targetCtx,
229                     CopyType.ADDED_BY_USES);
230             buffer.add(copy);
231         } else if (isReusedByUsesOnTop(original)) {
232             buffer.add(original);
233         }
234     }
235
236     private static final Set<YangStmtMapping> TOP_REUSED_DEF_SET = ImmutableSet.of(
237         YangStmtMapping.TYPE,
238         YangStmtMapping.TYPEDEF);
239
240     private static boolean isReusedByUsesOnTop(final StmtContext<?, ?, ?> stmtContext) {
241         return TOP_REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
242     }
243
244     private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
245         YangStmtMapping.DESCRIPTION,
246         YangStmtMapping.REFERENCE,
247         YangStmtMapping.STATUS);
248     private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
249         YangStmtMapping.TYPE,
250         YangStmtMapping.TYPEDEF,
251         YangStmtMapping.USES);
252
253     public static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
254         final StatementDefinition def = stmtContext.getPublicDefinition();
255         if (REUSED_DEF_SET.contains(def)) {
256             LOG.debug("Will reuse {} statement {}", def, stmtContext);
257             return false;
258         }
259         if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
260             return !YangStmtMapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
261         }
262
263         LOG.debug("Will copy {} statement {}", def, stmtContext);
264         return true;
265     }
266
267     public static void resolveUsesNode(
268             final Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode,
269             final StatementContextBase<?, ?, ?> targetNodeStmtCtx) {
270         for (final StatementContextBase<?, ?, ?> subStmtCtx : usesNode.declaredSubstatements()) {
271             if (StmtContextUtils.producesDeclared(subStmtCtx, RefineStatement.class)
272                     && areFeaturesSupported(subStmtCtx)) {
273                 performRefine(subStmtCtx, targetNodeStmtCtx);
274             }
275         }
276     }
277
278     private static boolean areFeaturesSupported(final Mutable<?, ?, ?> subStmtCtx) {
279         /*
280          * In case of Yang 1.1, checks whether features are supported.
281          */
282         return !YangVersion.VERSION_1_1.equals(subStmtCtx.getRootVersion()) || StmtContextUtils
283                 .areFeaturesSupported(subStmtCtx);
284     }
285
286     private static void performRefine(final StatementContextBase<?, ?, ?> refineCtx,
287             final StatementContextBase<?, ?, ?> usesParentCtx) {
288
289         final Object refineArgument = refineCtx.getStatementArgument();
290         InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier),
291             refineCtx.getStatementSourceReference(),
292             "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
293
294         final SchemaNodeIdentifier refineTargetNodeIdentifier = (SchemaNodeIdentifier) refineArgument;
295         final StatementContextBase<?, ?, ?> refineTargetNodeCtx = Utils.findNode(usesParentCtx,
296                 refineTargetNodeIdentifier);
297
298         InferenceException.throwIfNull(refineTargetNodeCtx, refineCtx.getStatementSourceReference(),
299             "Refine target node %s not found.", refineTargetNodeIdentifier);
300
301         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
302             LOG.debug(
303                     "Refine node '{}' in uses '{}' has target node unknown statement '{}'. Refine has been skipped. At line: {}",
304                     refineCtx.getStatementArgument(), refineCtx.getParentContext().getStatementArgument(),
305                     refineTargetNodeCtx.getStatementArgument(), refineCtx.getStatementSourceReference());
306             refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
307             return;
308         }
309
310         addOrReplaceNodes(refineCtx, refineTargetNodeCtx);
311         refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
312     }
313
314     private static void addOrReplaceNodes(final StatementContextBase<?, ?, ?> refineCtx,
315             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
316         for (final StatementContextBase<?, ?, ?> refineSubstatementCtx : refineCtx.declaredSubstatements()) {
317             if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
318                 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
319             }
320         }
321     }
322
323     private static void addOrReplaceNode(final StatementContextBase<?, ?, ?> refineSubstatementCtx,
324             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
325
326         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
327
328         SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
329                 refineSubstatementCtx.getStatementSourceReference(),
330                 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
331                 refineSubstatementCtx.getRoot().getStatementArgument(), refineSubstatementCtx.getParentContext()
332                         .getStatementArgument(), refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx
333                         .getPublicDefinition());
334
335         if (isAllowedToAddByRefine(refineSubstatementDef)) {
336             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
337         } else {
338             refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
339             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
340         }
341     }
342
343     private static final Set<YangStmtMapping> ALLOWED_TO_ADD_BY_REFINE_DEF_SET = ImmutableSet.of(YangStmtMapping.MUST);
344
345     private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
346         return ALLOWED_TO_ADD_BY_REFINE_DEF_SET.contains(publicDefinition);
347     }
348
349     private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
350         final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
351                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
352
353         return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
354                 || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition())
355                 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
356     }
357
358     private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
359             final StmtContext<?, ?, ?> refineTargetNodeCtx) {
360         final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS
361                 .get(refineSubstatementCtx.getPublicDefinition());
362
363         return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
364                 || supportedRefineTargets.contains(refineTargetNodeCtx.getPublicDefinition());
365     }
366
367
368     private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
369             final StmtContext<?, ?, ?> stmtContext) {
370         if (targetCtx.isRootContext()) {
371             return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
372         }
373         if (targetCtx.getPublicDefinition() == YangStmtMapping.AUGMENT) {
374             return Utils.getRootModuleQName(targetCtx);
375         }
376
377         final Object targetStmtArgument = targetCtx.getStatementArgument();
378         final Object sourceStmtArgument = stmtContext.getStatementArgument();
379         if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
380             return ((QName) targetStmtArgument).getModule();
381         }
382
383         return null;
384     }
385
386 }