Defer copy decisions to StatementSupport
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / uses / UsesStatementSupport.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.uses;
9
10 import com.google.common.base.Verify;
11 import com.google.common.collect.ImmutableSet;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.Optional;
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.StatementDefinition;
20 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
21 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
22 import org.opendaylight.yangtools.yang.model.api.stmt.UsesEffectiveStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
24 import org.opendaylight.yangtools.yang.parser.rfc7950.namespace.ChildSchemaNodeNamespace;
25 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
26 import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace;
27 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractQNameStatementSupport;
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.SourceException;
41 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
42 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
43 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public final class UsesStatementSupport
48         extends AbstractQNameStatementSupport<UsesStatement, UsesEffectiveStatement> {
49     private static final Logger LOG = LoggerFactory.getLogger(UsesStatementSupport.class);
50     private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(YangStmtMapping
51         .USES)
52         .addAny(YangStmtMapping.AUGMENT)
53         .addOptional(YangStmtMapping.DESCRIPTION)
54         .addAny(YangStmtMapping.IF_FEATURE)
55         .addAny(YangStmtMapping.REFINE)
56         .addOptional(YangStmtMapping.REFERENCE)
57         .addOptional(YangStmtMapping.STATUS)
58         .addOptional(YangStmtMapping.WHEN)
59         .build();
60     private static final UsesStatementSupport INSTANCE = new UsesStatementSupport();
61
62     private UsesStatementSupport() {
63         super(YangStmtMapping.USES);
64     }
65
66     public static UsesStatementSupport getInstance() {
67         return INSTANCE;
68     }
69
70     @Override
71     public QName parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
72         return StmtContextUtils.parseNodeIdentifier(ctx, value);
73     }
74
75     @Override
76     public void onFullDefinitionDeclared(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
77         if (!usesNode.isSupportedByFeatures()) {
78             return;
79         }
80         super.onFullDefinitionDeclared(usesNode);
81
82         final ModelActionBuilder usesAction = usesNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
83         final QName groupingName = usesNode.getStatementArgument();
84
85         final Prerequisite<StmtContext<?, ?, ?>> sourceGroupingPre = usesAction.requiresCtx(usesNode,
86                 GroupingNamespace.class, groupingName, ModelProcessingPhase.EFFECTIVE_MODEL);
87         final Prerequisite<? extends StmtContext.Mutable<?, ?, ?>> targetNodePre = usesAction.mutatesEffectiveCtx(
88                 usesNode.getParentContext());
89
90         usesAction.apply(new InferenceAction() {
91
92             @Override
93             public void apply(final InferenceContext ctx) {
94                 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
95                         (StatementContextBase<?, ?, ?>) targetNodePre.resolve(ctx);
96                 final StatementContextBase<?, ?, ?> sourceGrpStmtCtx =
97                         (StatementContextBase<?, ?, ?>) sourceGroupingPre.resolve(ctx);
98
99                 copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode);
100                 resolveUsesNode(usesNode, targetNodeStmtCtx);
101                 StmtContextUtils.validateIfFeatureAndWhenOnListKeys(usesNode);
102             }
103
104             @Override
105             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
106                 InferenceException.throwIf(failed.contains(sourceGroupingPre),
107                         usesNode.getStatementSourceReference(), "Grouping '%s' was not resolved.", groupingName);
108                 throw new InferenceException("Unknown error occurred.", usesNode.getStatementSourceReference());
109             }
110         });
111     }
112
113     @Override
114     public UsesStatement createDeclared(final StmtContext<QName, UsesStatement, ?> ctx) {
115         return new UsesStatementImpl(ctx);
116     }
117
118     @Override
119     public UsesEffectiveStatement createEffective(final StmtContext<QName, UsesStatement, UsesEffectiveStatement> ctx) {
120         return new UsesEffectiveStatementImpl(ctx);
121     }
122
123     @Override
124     protected SubstatementValidator getSubstatementValidator() {
125         return SUBSTATEMENT_VALIDATOR;
126     }
127
128     /**
129      * Copy statements from a grouping to a target node.
130      *
131      * @param sourceGrpStmtCtx
132      *            source grouping statement context
133      * @param targetCtx
134      *            target context
135      * @param usesNode
136      *            uses node
137      * @throws SourceException
138      *             instance of SourceException
139      */
140     private static void copyFromSourceToTarget(final Mutable<?, ?, ?> sourceGrpStmtCtx,
141             final StatementContextBase<?, ?, ?> targetCtx,
142             final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
143         final Collection<? extends Mutable<?, ?, ?>> declared = sourceGrpStmtCtx.mutableDeclaredSubstatements();
144         final Collection<? extends Mutable<?, ?, ?>> effective = sourceGrpStmtCtx.mutableEffectiveSubstatements();
145         final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
146         final QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
147
148         for (final Mutable<?, ?, ?> original : declared) {
149             if (original.isSupportedByFeatures()) {
150                 copyStatement(original, targetCtx, newQNameModule, buffer);
151             }
152         }
153
154         for (final Mutable<?, ?, ?> original : effective) {
155             copyStatement(original, targetCtx, newQNameModule, buffer);
156         }
157
158         targetCtx.addEffectiveSubstatements(buffer);
159         usesNode.addAsEffectOfStatement(buffer);
160     }
161
162     // FIXME: YANGTOOLS-652: this map looks very much like InferredStatementContext.REUSED_DEF_SET
163     private static final ImmutableSet<YangStmtMapping> TOP_REUSED_DEF_SET = ImmutableSet.of(
164         YangStmtMapping.TYPE,
165         YangStmtMapping.TYPEDEF);
166
167     private static void copyStatement(final Mutable<?, ?, ?> original,
168             final StatementContextBase<?, ?, ?> targetCtx, final QNameModule targetModule,
169             final Collection<Mutable<?, ?, ?>> buffer) {
170         final StatementDefinition def = original.getPublicDefinition();
171         if (TOP_REUSED_DEF_SET.contains(def)) {
172             buffer.add(original);
173             return;
174         }
175         // Do not propagate uses, as their effects have been accounted for in effective statements
176         // FIXME: YANGTOOLS-652: this check is different from InferredStatementContext. Why is that? We should express
177         //                       a common condition in our own implementation of copyAsChildOf()
178         if (!YangStmtMapping.USES.equals(def)) {
179             original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, targetModule).ifPresent(buffer::add);
180         }
181     }
182
183     private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
184             final StmtContext<?, ?, ?> stmtContext) {
185         if (targetCtx.getParentContext() == null) {
186             return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
187         }
188         if (targetCtx.getPublicDefinition() == YangStmtMapping.AUGMENT) {
189             return StmtContextUtils.getRootModuleQName(targetCtx);
190         }
191
192         final Object targetStmtArgument = targetCtx.getStatementArgument();
193         final Object sourceStmtArgument = stmtContext.getStatementArgument();
194         if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
195             return ((QName) targetStmtArgument).getModule();
196         }
197
198         return null;
199     }
200
201     private static void resolveUsesNode(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode,
202             final StmtContext<?, ?, ?> targetNodeStmtCtx) {
203         for (final Mutable<?, ?, ?> subStmtCtx : usesNode.mutableDeclaredSubstatements()) {
204             if (StmtContextUtils.producesDeclared(subStmtCtx, RefineStatement.class)
205                     && areFeaturesSupported(subStmtCtx)) {
206                 performRefine(subStmtCtx, targetNodeStmtCtx);
207             }
208         }
209     }
210
211     private static boolean areFeaturesSupported(final StmtContext<?, ?, ?> subStmtCtx) {
212         /*
213          * In case of Yang 1.1, checks whether features are supported.
214          */
215         return !YangVersion.VERSION_1_1.equals(subStmtCtx.getRootVersion()) || subStmtCtx.isSupportedByFeatures();
216     }
217
218     private static void performRefine(final Mutable<?, ?, ?> subStmtCtx, final StmtContext<?, ?, ?> usesParentCtx) {
219         final Object refineArgument = subStmtCtx.getStatementArgument();
220         InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier),
221             subStmtCtx.getStatementSourceReference(),
222             "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
223
224         final Optional<StmtContext<?, ?, ?>> optRefineTargetCtx = ChildSchemaNodeNamespace.findNode(
225             usesParentCtx, (SchemaNodeIdentifier) refineArgument);
226         InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx.getStatementSourceReference(),
227             "Refine target node %s not found.", refineArgument);
228
229         final StmtContext<?, ?, ?> refineTargetNodeCtx = optRefineTargetCtx.get();
230         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
231             LOG.trace("Refine node '{}' in uses '{}' has target node unknown statement '{}'. "
232                 + "Refine has been skipped. At line: {}", subStmtCtx.getStatementArgument(),
233                 subStmtCtx.coerceParentContext().getStatementArgument(),
234                 refineTargetNodeCtx.getStatementArgument(), subStmtCtx.getStatementSourceReference());
235             subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
236             return;
237         }
238
239         Verify.verify(refineTargetNodeCtx instanceof StatementContextBase);
240         addOrReplaceNodes(subStmtCtx, (StatementContextBase<?, ?, ?>) refineTargetNodeCtx);
241         subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
242     }
243
244     private static void addOrReplaceNodes(final Mutable<?, ?, ?> subStmtCtx,
245             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
246         for (final Mutable<?, ?, ?> refineSubstatementCtx : subStmtCtx.mutableDeclaredSubstatements()) {
247             if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
248                 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
249             }
250         }
251     }
252
253     private static void addOrReplaceNode(final Mutable<?, ?, ?> refineSubstatementCtx,
254             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
255
256         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
257
258         SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
259                 refineSubstatementCtx.getStatementSourceReference(),
260                 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
261                 refineSubstatementCtx.getRoot().getStatementArgument(),
262                 refineSubstatementCtx.coerceParentContext().getStatementArgument(),
263                 refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx.getPublicDefinition());
264
265         if (isAllowedToAddByRefine(refineSubstatementDef)) {
266             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
267         } else {
268             refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
269             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
270         }
271     }
272
273     private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
274         return YangStmtMapping.MUST.equals(publicDefinition);
275     }
276
277     private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
278         final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
279                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
280
281         return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
282                 || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition())
283                 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
284     }
285
286     private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
287             final StmtContext<?, ?, ?> refineTargetNodeCtx) {
288         final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS.get(
289             refineSubstatementCtx.getPublicDefinition());
290
291         return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
292                 || supportedRefineTargets.contains(refineTargetNodeCtx.getPublicDefinition());
293     }
294 }