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