BUG-7052: reduce StatementContextBase proliferation
[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 (!usesNode.isSupportedByFeatures()) {
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 Mutable<?, ?, ?> 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 (original.isSupportedByFeatures()) {
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()) || subStmtCtx.isSupportedByFeatures();
283     }
284
285     private static void performRefine(final StatementContextBase<?, ?, ?> refineCtx,
286             final StatementContextBase<?, ?, ?> usesParentCtx) {
287
288         final Object refineArgument = refineCtx.getStatementArgument();
289         InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier),
290             refineCtx.getStatementSourceReference(),
291             "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
292
293         final SchemaNodeIdentifier refineTargetNodeIdentifier = (SchemaNodeIdentifier) refineArgument;
294         final StatementContextBase<?, ?, ?> refineTargetNodeCtx = Utils.findNode(usesParentCtx,
295                 refineTargetNodeIdentifier);
296
297         InferenceException.throwIfNull(refineTargetNodeCtx, refineCtx.getStatementSourceReference(),
298             "Refine target node %s not found.", refineTargetNodeIdentifier);
299
300         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
301             LOG.debug(
302                     "Refine node '{}' in uses '{}' has target node unknown statement '{}'. Refine has been skipped. At line: {}",
303                     refineCtx.getStatementArgument(), refineCtx.getParentContext().getStatementArgument(),
304                     refineTargetNodeCtx.getStatementArgument(), refineCtx.getStatementSourceReference());
305             refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
306             return;
307         }
308
309         addOrReplaceNodes(refineCtx, refineTargetNodeCtx);
310         refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
311     }
312
313     private static void addOrReplaceNodes(final StatementContextBase<?, ?, ?> refineCtx,
314             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
315         for (final StatementContextBase<?, ?, ?> refineSubstatementCtx : refineCtx.declaredSubstatements()) {
316             if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
317                 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
318             }
319         }
320     }
321
322     private static void addOrReplaceNode(final StatementContextBase<?, ?, ?> refineSubstatementCtx,
323             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
324
325         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
326
327         SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
328                 refineSubstatementCtx.getStatementSourceReference(),
329                 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
330                 refineSubstatementCtx.getRoot().getStatementArgument(), refineSubstatementCtx.getParentContext()
331                         .getStatementArgument(), refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx
332                         .getPublicDefinition());
333
334         if (isAllowedToAddByRefine(refineSubstatementDef)) {
335             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
336         } else {
337             refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
338             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
339         }
340     }
341
342     private static final Set<YangStmtMapping> ALLOWED_TO_ADD_BY_REFINE_DEF_SET = ImmutableSet.of(YangStmtMapping.MUST);
343
344     private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
345         return ALLOWED_TO_ADD_BY_REFINE_DEF_SET.contains(publicDefinition);
346     }
347
348     private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
349         final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
350                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
351
352         return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
353                 || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition())
354                 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
355     }
356
357     private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
358             final StmtContext<?, ?, ?> refineTargetNodeCtx) {
359         final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS
360                 .get(refineSubstatementCtx.getPublicDefinition());
361
362         return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
363                 || supportedRefineTargets.contains(refineTargetNodeCtx.getPublicDefinition());
364     }
365
366
367     private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
368             final StmtContext<?, ?, ?> stmtContext) {
369         if (targetCtx.isRootContext()) {
370             return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
371         }
372         if (targetCtx.getPublicDefinition() == YangStmtMapping.AUGMENT) {
373             return Utils.getRootModuleQName(targetCtx);
374         }
375
376         final Object targetStmtArgument = targetCtx.getStatementArgument();
377         final Object sourceStmtArgument = stmtContext.getStatementArgument();
378         if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
379             return ((QName) targetStmtArgument).getModule();
380         }
381
382         return null;
383     }
384
385 }