Reformulate StatementContextFactory.createEffective()
[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.ImmutableList;
12 import com.google.common.collect.ImmutableMap;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.LinkedHashMap;
17 import java.util.Map;
18 import java.util.Optional;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.common.QNameModule;
22 import org.opendaylight.yangtools.yang.common.YangVersion;
23 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
24 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
26 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
29 import org.opendaylight.yangtools.yang.model.api.stmt.RefineEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Descendant;
33 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.UsesEffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
36 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseQNameStatementSupport;
38 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.refine.RefineEffectiveStatementImpl;
39 import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
54 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
55 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
56 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
57 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 public final class UsesStatementSupport
62         extends BaseQNameStatementSupport<UsesStatement, UsesEffectiveStatement> {
63     private static final Logger LOG = LoggerFactory.getLogger(UsesStatementSupport.class);
64     private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(YangStmtMapping
65         .USES)
66         .addAny(YangStmtMapping.AUGMENT)
67         .addOptional(YangStmtMapping.DESCRIPTION)
68         .addAny(YangStmtMapping.IF_FEATURE)
69         .addAny(YangStmtMapping.REFINE)
70         .addOptional(YangStmtMapping.REFERENCE)
71         .addOptional(YangStmtMapping.STATUS)
72         .addOptional(YangStmtMapping.WHEN)
73         .build();
74     private static final UsesStatementSupport INSTANCE = new UsesStatementSupport();
75
76     private UsesStatementSupport() {
77         super(YangStmtMapping.USES);
78     }
79
80     public static UsesStatementSupport getInstance() {
81         return INSTANCE;
82     }
83
84     @Override
85     public QName parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
86         return StmtContextUtils.parseNodeIdentifier(ctx, value);
87     }
88
89     @Override
90     public void onFullDefinitionDeclared(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
91         if (!usesNode.isSupportedByFeatures()) {
92             return;
93         }
94         super.onFullDefinitionDeclared(usesNode);
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 =
109                         (StatementContextBase<?, ?, ?>) targetNodePre.resolve(ctx);
110                 final StatementContextBase<?, ?, ?> sourceGrpStmtCtx =
111                         (StatementContextBase<?, ?, ?>) sourceGroupingPre.resolve(ctx);
112
113                 copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode);
114                 resolveUsesNode(usesNode, targetNodeStmtCtx);
115                 StmtContextUtils.validateIfFeatureAndWhenOnListKeys(usesNode);
116             }
117
118             @Override
119             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
120                 InferenceException.throwIf(failed.contains(sourceGroupingPre),
121                         usesNode.getStatementSourceReference(), "Grouping '%s' was not resolved.", groupingName);
122                 throw new InferenceException("Unknown error occurred.", usesNode.getStatementSourceReference());
123             }
124         });
125     }
126
127     @Override
128     protected SubstatementValidator getSubstatementValidator() {
129         return SUBSTATEMENT_VALIDATOR;
130     }
131
132     @Override
133     protected UsesStatement createDeclared(final StmtContext<QName, UsesStatement, ?> ctx,
134             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
135         return new RegularUsesStatement(ctx.coerceRawStatementArgument(), ctx.coerceStatementArgument(), substatements);
136     }
137
138     @Override
139     protected UsesStatement createEmptyDeclared(final StmtContext<QName, UsesStatement, ?> ctx) {
140         return new EmptyUsesStatement(ctx.coerceRawStatementArgument(), ctx.coerceStatementArgument());
141     }
142
143     @Override
144     protected UsesEffectiveStatement createEffective(final Current<QName, UsesStatement> stmt,
145             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
146         final GroupingDefinition sourceGrouping = getSourceGrouping(stmt);
147         final int flags = historyAndStatusFlags(stmt.history(), substatements);
148         final QName argument = stmt.coerceArgument();
149         final UsesStatement declared = stmt.declared();
150
151         if (substatements.isEmpty()) {
152             return argument.equals(declared.argument())
153                 ? new EmptyLocalUsesEffectiveStatement(declared, sourceGrouping, flags)
154                         : new SimpleCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags);
155         }
156
157         if (declared.argument().equals(argument)) {
158             return new RegularLocalUsesEffectiveStatement(declared, sourceGrouping, flags, substatements);
159         }
160         if (findFirstStatement(substatements, RefineEffectiveStatement.class) == null) {
161             return new SimpleCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags, substatements);
162         }
163         return new FullCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags, substatements);
164     }
165
166     static @NonNull ImmutableMap<Descendant, SchemaNode> indexRefines(
167             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
168         final Map<Descendant, SchemaNode> refines = new LinkedHashMap<>();
169
170         for (EffectiveStatement<?, ?> effectiveStatement : substatements) {
171             if (effectiveStatement instanceof RefineEffectiveStatementImpl) {
172                 final RefineEffectiveStatementImpl refineStmt = (RefineEffectiveStatementImpl) effectiveStatement;
173                 refines.put(refineStmt.argument(), refineStmt.getRefineTargetNode());
174             }
175         }
176
177         return ImmutableMap.copyOf(refines);
178     }
179
180     private static GroupingDefinition getSourceGrouping(final Current<QName, ?> stmt) {
181         return (GroupingDefinition) stmt.getFromNamespace(GroupingNamespace.class, stmt.coerceArgument())
182                 .buildEffective();
183     }
184
185     /**
186      * Copy statements from a grouping to a target node.
187      *
188      * @param sourceGrpStmtCtx
189      *            source grouping statement context
190      * @param targetCtx
191      *            target context
192      * @param usesNode
193      *            uses node
194      * @throws SourceException
195      *             instance of SourceException
196      */
197     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
198             justification = "https://github.com/spotbugs/spotbugs/issues/811")
199     private static void copyFromSourceToTarget(final Mutable<?, ?, ?> sourceGrpStmtCtx,
200             final StatementContextBase<?, ?, ?> targetCtx,
201             final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
202         final Collection<? extends Mutable<?, ?, ?>> declared = sourceGrpStmtCtx.mutableDeclaredSubstatements();
203         final Collection<? extends Mutable<?, ?, ?>> effective = sourceGrpStmtCtx.mutableEffectiveSubstatements();
204         final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
205         final QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
206
207         for (final Mutable<?, ?, ?> original : declared) {
208             if (original.isSupportedByFeatures() && shouldCopy(original)) {
209                 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(buffer::add);
210             }
211         }
212
213         for (final Mutable<?, ?, ?> original : effective) {
214             if (shouldCopy(original)) {
215                 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(buffer::add);
216             }
217         }
218
219         targetCtx.addEffectiveSubstatements(buffer);
220         usesNode.addAsEffectOfStatement(buffer);
221     }
222
223     private static boolean shouldCopy(final StmtContext<?, ?, ?> stmt) {
224         // https://tools.ietf.org/html/rfc7950#section-7.13:
225         //
226         //        The effect of a "uses" reference to a grouping is that the nodes
227         //        defined by the grouping are copied into the current schema tree and
228         //        are then updated according to the "refine" and "augment" statements.
229         //
230         // This means that the statement that is about to be copied (and can be subjected to buildEffective() I think)
231         // is actually a SchemaTreeEffectiveStatement
232         if (SchemaTreeEffectiveStatement.class.isAssignableFrom(
233                 stmt.getPublicDefinition().getEffectiveRepresentationClass())) {
234             return true;
235         }
236
237         // As per https://tools.ietf.org/html/rfc7950#section-7.13.2:
238         //
239         //        o  Any node can get refined extensions, if the extension allows
240         //           refinement.  See Section 7.19 for details.
241         //
242         // and https://tools.ietf.org/html/rfc7950#section-7.19:
243         //
244         //        An extension can allow refinement (see Section 7.13.2) and deviations
245         //        (Section 7.20.3.2), but the mechanism for how this is defined is
246         //        outside the scope of this specification.
247         //
248         // This is actively used out there (tailf-common.yang's tailf:action), which is incorrect, though. They do
249         // publish a bunch of metadata (through tailf-meta-extension.yang), but fail to publish a key aspect of the
250         // statement: it attaches to schema tree namespace (just as RFC7950 action does). Such an extension would
251         // automatically result in the extension being picked up by the above check and everybody would live happily
252         // ever after.
253         //
254         // We do not live in that world yet, hence we do the following and keep our fingers crossed.
255         // FIXME: YANGTOOLS-403: this should not be necessary once we implement the above (although tests will complain)
256         return StmtContextUtils.isUnknownStatement(stmt);
257     }
258
259     private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
260             final StmtContext<?, ?, ?> stmtContext) {
261         if (targetCtx.getParentContext() == null) {
262             return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
263         }
264         if (targetCtx.getPublicDefinition() == YangStmtMapping.AUGMENT) {
265             return StmtContextUtils.getRootModuleQName(targetCtx);
266         }
267
268         final Object targetStmtArgument = targetCtx.getStatementArgument();
269         final Object sourceStmtArgument = stmtContext.getStatementArgument();
270         if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
271             return ((QName) targetStmtArgument).getModule();
272         }
273
274         return null;
275     }
276
277     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
278             justification = "https://github.com/spotbugs/spotbugs/issues/811")
279     private static void resolveUsesNode(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode,
280             final StmtContext<?, ?, ?> targetNodeStmtCtx) {
281         for (final Mutable<?, ?, ?> subStmtCtx : usesNode.mutableDeclaredSubstatements()) {
282             if (subStmtCtx.producesDeclared(RefineStatement.class) && areFeaturesSupported(subStmtCtx)) {
283                 performRefine(subStmtCtx, targetNodeStmtCtx);
284             }
285         }
286     }
287
288     private static boolean areFeaturesSupported(final StmtContext<?, ?, ?> subStmtCtx) {
289         /*
290          * In case of Yang 1.1, checks whether features are supported.
291          */
292         return !YangVersion.VERSION_1_1.equals(subStmtCtx.getRootVersion()) || subStmtCtx.isSupportedByFeatures();
293     }
294
295     private static void performRefine(final Mutable<?, ?, ?> subStmtCtx, final StmtContext<?, ?, ?> usesParentCtx) {
296         final Object refineArgument = subStmtCtx.getStatementArgument();
297         InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier),
298             subStmtCtx.getStatementSourceReference(),
299             "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
300
301         final Optional<StmtContext<?, ?, ?>> optRefineTargetCtx = SchemaTreeNamespace.findNode(
302             usesParentCtx, (SchemaNodeIdentifier) refineArgument);
303         InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx.getStatementSourceReference(),
304             "Refine target node %s not found.", refineArgument);
305
306         final StmtContext<?, ?, ?> refineTargetNodeCtx = optRefineTargetCtx.get();
307         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
308             LOG.trace("Refine node '{}' in uses '{}' has target node unknown statement '{}'. "
309                 + "Refine has been skipped. At line: {}", subStmtCtx.getStatementArgument(),
310                 subStmtCtx.coerceParentContext().getStatementArgument(),
311                 refineTargetNodeCtx.getStatementArgument(), subStmtCtx.getStatementSourceReference());
312             subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
313             return;
314         }
315
316         Verify.verify(refineTargetNodeCtx instanceof StatementContextBase);
317         addOrReplaceNodes(subStmtCtx, (StatementContextBase<?, ?, ?>) refineTargetNodeCtx);
318         subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
319     }
320
321     private static void addOrReplaceNodes(final Mutable<?, ?, ?> subStmtCtx,
322             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
323         for (final Mutable<?, ?, ?> refineSubstatementCtx : subStmtCtx.mutableDeclaredSubstatements()) {
324             if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
325                 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
326             }
327         }
328     }
329
330     private static void addOrReplaceNode(final Mutable<?, ?, ?> refineSubstatementCtx,
331             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
332
333         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
334
335         SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
336                 refineSubstatementCtx.getStatementSourceReference(),
337                 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
338                 refineSubstatementCtx.getRoot().rawStatementArgument(),
339                 refineSubstatementCtx.coerceParentContext().getStatementArgument(),
340                 refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx.getPublicDefinition());
341
342         if (isAllowedToAddByRefine(refineSubstatementDef)) {
343             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
344         } else {
345             refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
346             refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
347         }
348     }
349
350     private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
351         return YangStmtMapping.MUST.equals(publicDefinition);
352     }
353
354     private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
355         final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
356                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
357
358         return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
359                 || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition())
360                 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
361     }
362
363     private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
364             final StmtContext<?, ?, ?> refineTargetNodeCtx) {
365         final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS.get(
366             refineSubstatementCtx.getPublicDefinition());
367
368         return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
369                 || supportedRefineTargets.contains(refineTargetNodeCtx.getPublicDefinition());
370     }
371 }