Move copy operation execution
[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.ImmutableMap;
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     // Note: do not put CopyPolicy.DECLARED_COPY, we treat non-presence as such
163     private static final ImmutableMap<StatementDefinition, CopyPolicy> GROUPING_TO_TARGET_POLICY =
164             ImmutableMap.<StatementDefinition, CopyPolicy>builder()
165                 // FIXME: YANGTOOLS-652: this map looks very much like InferredStatementContext.REUSED_DEF_SET
166                 // a grouping's type/typedef statements are fully defined at the grouping, we want the same effective
167                 // statement
168                 .put(YangStmtMapping.TYPE, CopyPolicy.CONTEXT_INDEPENDENT)
169                 .put(YangStmtMapping.TYPEDEF, CopyPolicy.CONTEXT_INDEPENDENT)
170
171                 // We do not want to propagate description/reference/status statements, as they are the source
172                 // grouping's documentation, not target statement's
173                 .put(YangStmtMapping.DESCRIPTION, CopyPolicy.IGNORE)
174                 .put(YangStmtMapping.REFERENCE, CopyPolicy.IGNORE)
175                 .put(YangStmtMapping.STATUS, CopyPolicy.IGNORE)
176
177                 // Do not propagate uses, as their effects have been accounted for in effective statements
178                 // FIXME: YANGTOOLS-652: this check is different from InferredStatementContext. Why is that? We should
179                 //                       express a common condition in our own implementation of applyCopyPolicy() --
180                 //                       most notably reactor performs the equivalent of CopyPolicy.CONTEXT_INDEPENDENT.
181                 // FIXME: YANGTOOLS-694: note that if the above is true, why are we propagating grouping statements?
182                 .put(YangStmtMapping.USES, CopyPolicy.IGNORE)
183                 .build();
184
185     private static void copyStatement(final Mutable<?, ?, ?> original,
186             final StatementContextBase<?, ?, ?> targetCtx, final QNameModule targetModule,
187             final Collection<Mutable<?, ?, ?>> buffer) {
188
189         // FIXME: YANGTOOLS-694: This method needs to be adjusted to account for RFC7950,
190         //                       https://tools.ietf.org/html/rfc7950#section-7.13, which states that:
191         //
192         //        The effect of a "uses" reference to a grouping is that the nodes
193         //        defined by the grouping are copied into the current schema tree and
194         //        are then updated according to the "refine" and "augment" statements.
195         //
196         //                       This means that the statement that is about to be copied (and can be subjected to
197         //                       buildEffective() I think) is actually a SchemaTreeEffectiveStatement -- i.e. if it
198         //                       is not a SchemaTreeEffectiveStatement, it just cannot be added to target's tree and
199         //                       hence it should not be copied.
200         final CopyPolicy policy = GROUPING_TO_TARGET_POLICY.get(original.getPublicDefinition());
201         if (policy == null) {
202             original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, targetModule).ifPresent(buffer::add);
203         } else if (policy == CopyPolicy.CONTEXT_INDEPENDENT) {
204             buffer.add(original);
205         } else if (policy == CopyPolicy.IGNORE) {
206             // No-op
207         } else {
208             throw new IllegalStateException("Unhandled policy " + policy);
209         }
210     }
211
212     private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
213             final StmtContext<?, ?, ?> stmtContext) {
214         if (targetCtx.getParentContext() == null) {
215             return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
216         }
217         if (targetCtx.getPublicDefinition() == YangStmtMapping.AUGMENT) {
218             return StmtContextUtils.getRootModuleQName(targetCtx);
219         }
220
221         final Object targetStmtArgument = targetCtx.getStatementArgument();
222         final Object sourceStmtArgument = stmtContext.getStatementArgument();
223         if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
224             return ((QName) targetStmtArgument).getModule();
225         }
226
227         return null;
228     }
229
230     private static void resolveUsesNode(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode,
231             final StmtContext<?, ?, ?> targetNodeStmtCtx) {
232         for (final Mutable<?, ?, ?> subStmtCtx : usesNode.mutableDeclaredSubstatements()) {
233             if (StmtContextUtils.producesDeclared(subStmtCtx, RefineStatement.class)
234                     && areFeaturesSupported(subStmtCtx)) {
235                 performRefine(subStmtCtx, targetNodeStmtCtx);
236             }
237         }
238     }
239
240     private static boolean areFeaturesSupported(final StmtContext<?, ?, ?> subStmtCtx) {
241         /*
242          * In case of Yang 1.1, checks whether features are supported.
243          */
244         return !YangVersion.VERSION_1_1.equals(subStmtCtx.getRootVersion()) || subStmtCtx.isSupportedByFeatures();
245     }
246
247     private static void performRefine(final Mutable<?, ?, ?> subStmtCtx, final StmtContext<?, ?, ?> usesParentCtx) {
248         final Object refineArgument = subStmtCtx.getStatementArgument();
249         InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier),
250             subStmtCtx.getStatementSourceReference(),
251             "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
252
253         final Optional<StmtContext<?, ?, ?>> optRefineTargetCtx = ChildSchemaNodeNamespace.findNode(
254             usesParentCtx, (SchemaNodeIdentifier) refineArgument);
255         InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx.getStatementSourceReference(),
256             "Refine target node %s not found.", refineArgument);
257
258         final StmtContext<?, ?, ?> refineTargetNodeCtx = optRefineTargetCtx.get();
259         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
260             LOG.trace("Refine node '{}' in uses '{}' has target node unknown statement '{}'. "
261                 + "Refine has been skipped. At line: {}", subStmtCtx.getStatementArgument(),
262                 subStmtCtx.coerceParentContext().getStatementArgument(),
263                 refineTargetNodeCtx.getStatementArgument(), subStmtCtx.getStatementSourceReference());
264             subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
265             return;
266         }
267
268         Verify.verify(refineTargetNodeCtx instanceof StatementContextBase);
269         addOrReplaceNodes(subStmtCtx, (StatementContextBase<?, ?, ?>) refineTargetNodeCtx);
270         subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
271     }
272
273     private static void addOrReplaceNodes(final Mutable<?, ?, ?> subStmtCtx,
274             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
275         for (final Mutable<?, ?, ?> refineSubstatementCtx : subStmtCtx.mutableDeclaredSubstatements()) {
276             if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
277                 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
278             }
279         }
280     }
281
282     private static void addOrReplaceNode(final Mutable<?, ?, ?> refineSubstatementCtx,
283             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
284
285         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
286
287         SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
288                 refineSubstatementCtx.getStatementSourceReference(),
289                 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
290                 refineSubstatementCtx.getRoot().getStatementArgument(),
291                 refineSubstatementCtx.coerceParentContext().getStatementArgument(),
292                 refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx.getPublicDefinition());
293
294         if (isAllowedToAddByRefine(refineSubstatementDef)) {
295             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
296         } else {
297             refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
298             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
299         }
300     }
301
302     private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
303         return YangStmtMapping.MUST.equals(publicDefinition);
304     }
305
306     private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
307         final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
308                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
309
310         return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
311                 || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition())
312                 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
313     }
314
315     private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
316             final StmtContext<?, ?, ?> refineTargetNodeCtx) {
317         final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS.get(
318             refineSubstatementCtx.getPublicDefinition());
319
320         return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
321                 || supportedRefineTargets.contains(refineTargetNodeCtx.getPublicDefinition());
322     }
323 }