Bug 6869: [Yang 1.1] Allow if-feature in bit, enum, refine & identity
[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.base.Preconditions;
11 import com.google.common.collect.ImmutableSet;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.Set;
15 import javax.annotation.Nonnull;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.common.QNameModule;
18 import org.opendaylight.yangtools.yang.common.YangVersion;
19 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
20 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
21 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
22 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.DescriptionStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.IfFeatureStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.ReferenceStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
28 import org.opendaylight.yangtools.yang.model.api.stmt.StatusStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.WhenStatement;
31 import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace;
32 import org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractDeclaredStatement;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
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
91             getSubstatementValidator().validate(usesNode);
92
93             if (StmtContextUtils.isInExtensionBody(usesNode)) {
94                 return;
95             }
96
97             final ModelActionBuilder usesAction = usesNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
98             final QName groupingName = usesNode.getStatementArgument();
99
100             final Prerequisite<StmtContext<?, ?, ?>> sourceGroupingPre = usesAction.requiresCtx(usesNode,
101                     GroupingNamespace.class, groupingName, ModelProcessingPhase.EFFECTIVE_MODEL);
102             final Prerequisite<? extends StmtContext.Mutable<?, ?, ?>> targetNodePre = usesAction.mutatesEffectiveCtx(
103                     usesNode.getParentContext());
104
105             usesAction.apply(new InferenceAction() {
106
107                 @Override
108                 public void apply() {
109                     final StatementContextBase<?, ?, ?> targetNodeStmtCtx = (StatementContextBase<?, ?, ?>) targetNodePre.get();
110                     final StatementContextBase<?, ?, ?> sourceGrpStmtCtx = (StatementContextBase<?, ?, ?>) sourceGroupingPre.get();
111
112                     try {
113                         copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode);
114                         resolveUsesNode(usesNode, targetNodeStmtCtx);
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 StatementContextBase<?, ?, ?> 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 StatementContextBase<?, ?, ?> 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         Preconditions.checkArgument(refineArgument instanceof SchemaNodeIdentifier,
291                 "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier. At %s", refineArgument,
292                 refineCtx.getStatementSourceReference());
293
294         final SchemaNodeIdentifier refineTargetNodeIdentifier = (SchemaNodeIdentifier) refineArgument;
295         final StatementContextBase<?, ?, ?> refineTargetNodeCtx = Utils.findNode(usesParentCtx,
296                 refineTargetNodeIdentifier);
297         Preconditions.checkArgument(refineTargetNodeCtx != null, "Refine target node %s not found. At %s",
298                 refineTargetNodeIdentifier, refineCtx.getStatementSourceReference());
299         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
300             LOG.debug(
301                     "Refine node '{}' in uses '{}' has target node unknown statement '{}'. Refine has been skipped. At line: {}",
302                     refineCtx.getStatementArgument(), refineCtx.getParentContext().getStatementArgument(),
303                     refineTargetNodeCtx.getStatementArgument(), refineCtx.getStatementSourceReference());
304             refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
305             return;
306         }
307
308         addOrReplaceNodes(refineCtx, refineTargetNodeCtx);
309         refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
310     }
311
312     private static void addOrReplaceNodes(final StatementContextBase<?, ?, ?> refineCtx,
313             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
314         for (final StatementContextBase<?, ?, ?> refineSubstatementCtx : refineCtx.declaredSubstatements()) {
315             if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
316                 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
317             }
318         }
319     }
320
321     private static void addOrReplaceNode(final StatementContextBase<?, ?, ?> refineSubstatementCtx,
322             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
323
324         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
325
326         SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
327                 refineSubstatementCtx.getStatementSourceReference(),
328                 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
329                 refineSubstatementCtx.getRoot().getStatementArgument(), refineSubstatementCtx.getParentContext()
330                         .getStatementArgument(), refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx
331                         .getPublicDefinition());
332
333         if (isAllowedToAddByRefine(refineSubstatementDef)) {
334             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
335         } else {
336             refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
337             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
338         }
339     }
340
341     private static final Set<YangStmtMapping> ALLOWED_TO_ADD_BY_REFINE_DEF_SET = ImmutableSet.of(YangStmtMapping.MUST);
342
343     private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
344         return ALLOWED_TO_ADD_BY_REFINE_DEF_SET.contains(publicDefinition);
345     }
346
347     private static boolean isSupportedRefineSubstatement(final StatementContextBase<?, ?, ?> refineSubstatementCtx) {
348         final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
349                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
350
351         return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
352                 || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition())
353                 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
354     }
355
356     private static boolean isSupportedRefineTarget(final StatementContextBase<?, ?, ?> refineSubstatementCtx,
357             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
358
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 StatementContextBase<?, ?, ?> 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 targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx.getRoot());
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 }