Disable uses/augment statements of unsupported paths
[yangtools.git] / parser / 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.parser.api.YangParserConfiguration;
43 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
44 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.EffectiveStmtUtils;
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.BoundStmtCtx;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
59 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
61 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
62 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
63 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
64 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
65 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
66 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
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 =
74         SubstatementValidator.builder(YangStmtMapping.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, SUBSTATEMENT_VALIDATOR);
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 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 Mutable<?, ?, ?> targetNodeStmtCtx = targetNodePre.resolve(ctx);
113                 final StmtContext<?, ?, ?> sourceGrpStmtCtx = sourceGroupingPre.resolve(ctx);
114
115                 copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode);
116                 resolveUsesNode(usesNode, targetNodeStmtCtx);
117                 StmtContextUtils.validateIfFeatureAndWhenOnListKeys(usesNode);
118                 usesNode.addToNs(SourceGroupingNamespace.class, Empty.value(), sourceGrpStmtCtx);
119             }
120
121             @Override
122             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
123                 InferenceException.throwIf(failed.contains(sourceGroupingPre), usesNode,
124                     "Grouping '%s' was not resolved.", groupingName);
125                 throw new InferenceException("Unknown error occurred.", usesNode);
126             }
127         });
128     }
129
130     @Override
131     protected UsesStatement createDeclared(final BoundStmtCtx<QName> ctx,
132             final ImmutableList<DeclaredStatement<?>> substatements) {
133         return DeclaredStatements.createUses(ctx.getRawArgument(), ctx.getArgument(), substatements);
134     }
135
136     @Override
137     protected UsesStatement attachDeclarationReference(final UsesStatement stmt, final DeclarationReference reference) {
138         return DeclaredStatementDecorators.decorateUses(stmt, reference);
139     }
140
141     @Override
142     protected UsesEffectiveStatement createEffective(final Current<QName, UsesStatement> stmt,
143             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
144         final EffectiveStatement<?, ?> source =
145             verifyNotNull(stmt.getFromNamespace(SourceGroupingNamespace.class, Empty.value())).buildEffective();
146         verify(source instanceof GroupingDefinition, "Unexpected source %s", source);
147         final GroupingDefinition sourceGrouping = (GroupingDefinition) source;
148
149         final int flags = EffectiveStmtUtils.historyAndStatusFlags(stmt.history(), substatements);
150         final QName argument = stmt.getArgument();
151         final UsesStatement declared = stmt.declared();
152
153         if (substatements.isEmpty()) {
154             return argument.equals(declared.argument())
155                 ? new EmptyLocalUsesEffectiveStatement(declared, sourceGrouping, flags)
156                         : new SimpleCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags);
157         }
158
159         if (declared.argument().equals(argument)) {
160             return new RegularLocalUsesEffectiveStatement(declared, sourceGrouping, flags, substatements);
161         }
162         if (findFirstStatement(substatements, RefineEffectiveStatement.class) == null) {
163             return new SimpleCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags, substatements);
164         }
165         return new FullCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags, substatements);
166     }
167
168     static @NonNull ImmutableMap<Descendant, SchemaNode> indexRefines(
169             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
170         final Map<Descendant, SchemaNode> refines = new LinkedHashMap<>();
171
172         for (EffectiveStatement<?, ?> effectiveStatement : substatements) {
173             if (effectiveStatement instanceof RefineEffectiveStatementImpl) {
174                 final RefineEffectiveStatementImpl refineStmt = (RefineEffectiveStatementImpl) effectiveStatement;
175                 refines.put(refineStmt.argument(), refineStmt.getRefineTargetNode());
176             }
177         }
178
179         return ImmutableMap.copyOf(refines);
180     }
181
182     /**
183      * Copy statements from a grouping to a target node.
184      *
185      * @param sourceGrpStmtCtx
186      *            source grouping statement context
187      * @param targetCtx
188      *            target context
189      * @param usesNode
190      *            uses node
191      * @throws SourceException
192      *             instance of SourceException
193      */
194     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
195             justification = "https://github.com/spotbugs/spotbugs/issues/811")
196     private static void copyFromSourceToTarget(final StmtContext<?, ?, ?> sourceGrpStmtCtx,
197             final Mutable<?, ?, ?> targetCtx, final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
198         final var declared = sourceGrpStmtCtx.declaredSubstatements();
199         final var effective = sourceGrpStmtCtx.effectiveSubstatements();
200         final var buffer = new ArrayList<Mutable<?, ?, ?>>(declared.size() + effective.size());
201         final QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
202
203         for (StmtContext<?, ?, ?> original : declared) {
204             if (shouldCopy(original)) {
205                 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(copy -> {
206                     if (!original.isSupportedByFeatures() || !original.isSupportedToBuildEffective()) {
207                         copy.setUnsupported();
208                     }
209                     buffer.add(copy);
210                 });
211             }
212         }
213
214         for (StmtContext<?, ?, ?> original : effective) {
215             if (shouldCopy(original)) {
216                 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(buffer::add);
217             }
218         }
219
220         targetCtx.addEffectiveSubstatements(buffer);
221         usesNode.addAsEffectOfStatement(buffer);
222     }
223
224     private static boolean shouldCopy(final StmtContext<?, ?, ?> stmt) {
225         // https://tools.ietf.org/html/rfc7950#section-7.13:
226         //
227         //        The effect of a "uses" reference to a grouping is that the nodes
228         //        defined by the grouping are copied into the current schema tree and
229         //        are then updated according to the "refine" and "augment" statements.
230         //
231         // This means that the statement that is about to be copied (and can be subjected to buildEffective() I think)
232         // is actually a SchemaTreeEffectiveStatement
233         if (SchemaTreeEffectiveStatement.class.isAssignableFrom(
234                 stmt.publicDefinition().getEffectiveRepresentationClass())) {
235             return true;
236         }
237
238         // As per https://tools.ietf.org/html/rfc7950#section-7.13.2:
239         //
240         //        o  Any node can get refined extensions, if the extension allows
241         //           refinement.  See Section 7.19 for details.
242         //
243         // and https://tools.ietf.org/html/rfc7950#section-7.19:
244         //
245         //        An extension can allow refinement (see Section 7.13.2) and deviations
246         //        (Section 7.20.3.2), but the mechanism for how this is defined is
247         //        outside the scope of this specification.
248         //
249         // This is actively used out there (tailf-common.yang's tailf:action), which is incorrect, though. They do
250         // publish a bunch of metadata (through tailf-meta-extension.yang), but fail to publish a key aspect of the
251         // statement: it attaches to schema tree namespace (just as RFC7950 action does). Such an extension would
252         // automatically result in the extension being picked up by the above check and everybody would live happily
253         // ever after.
254         //
255         // We do not live in that world yet, hence we do the following and keep our fingers crossed.
256         // FIXME: YANGTOOLS-403: this should not be necessary once we implement the above (although tests will complain)
257         return StmtContextUtils.isUnknownStatement(stmt);
258     }
259
260     private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
261             final StmtContext<?, ?, ?> stmtContext) {
262         if (targetCtx.getParentContext() == null) {
263             return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
264         }
265         if (targetCtx.publicDefinition() == YangStmtMapping.AUGMENT) {
266             return StmtContextUtils.getRootModuleQName(targetCtx);
267         }
268
269         final Object targetStmtArgument = targetCtx.argument();
270         final Object sourceStmtArgument = stmtContext.argument();
271         if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
272             return ((QName) targetStmtArgument).getModule();
273         }
274
275         return null;
276     }
277
278     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
279             justification = "https://github.com/spotbugs/spotbugs/issues/811")
280     private static void resolveUsesNode(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode,
281             final StmtContext<?, ?, ?> targetNodeStmtCtx) {
282         for (Mutable<?, ?, ?> subStmtCtx : usesNode.mutableDeclaredSubstatements()) {
283             if (subStmtCtx.producesDeclared(RefineStatement.class) && areFeaturesSupported(subStmtCtx)) {
284                 performRefine(subStmtCtx, targetNodeStmtCtx);
285             }
286         }
287     }
288
289     private static boolean areFeaturesSupported(final StmtContext<?, ?, ?> subStmtCtx) {
290         /*
291          * In case of Yang 1.1, checks whether features are supported.
292          */
293         return !YangVersion.VERSION_1_1.equals(subStmtCtx.yangVersion()) || subStmtCtx.isSupportedByFeatures();
294     }
295
296     private static void performRefine(final Mutable<?, ?, ?> subStmtCtx, final StmtContext<?, ?, ?> usesParentCtx) {
297         final Object refineArgument = subStmtCtx.argument();
298         InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier), subStmtCtx,
299             "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
300
301         // FIXME: this really should be handled via separate inference, i.e. we first instantiate the template and when
302         //        it appears, this refine will trigger on it. This reinforces the FIXME below.
303         final Optional<StmtContext<?, ?, ?>> optRefineTargetCtx = SchemaTreeNamespace.findNode(
304             usesParentCtx, (SchemaNodeIdentifier) refineArgument);
305         InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx, "Refine target node %s not found.",
306             refineArgument);
307
308         // FIXME: This communicates the looked-up target node to RefineStatementSupport.buildEffective(). We should do
309         //        this trick through a shared namespace or similar reactor-agnostic meeting place. It really feels like
310         //        an inference action RefineStatementSupport should be doing.
311         final StmtContext<?, ?, ?> refineTargetNodeCtx = optRefineTargetCtx.get();
312         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
313             LOG.trace("Refine node '{}' in uses '{}' has target node unknown statement '{}'. "
314                 + "Refine has been skipped. At line: {}", subStmtCtx.argument(),
315                 subStmtCtx.coerceParentContext().argument(), refineTargetNodeCtx.argument(),
316                 subStmtCtx.sourceReference());
317         } else {
318             verify(refineTargetNodeCtx instanceof Mutable, "Unexpected target %s", refineTargetNodeCtx);
319             addOrReplaceNodes(subStmtCtx, (Mutable<?, ?, ?>) refineTargetNodeCtx);
320         }
321
322         // Target is a prerequisite for the 'refine', hence if the target is not supported, the refine is not supported
323         // as well. Otherwise add a pointer to the target into refine's local namespace.
324         if (refineTargetNodeCtx.isSupportedToBuildEffective()) {
325             subStmtCtx.addToNs(RefineTargetNamespace.class, Empty.value(), refineTargetNodeCtx);
326         } else {
327             subStmtCtx.setUnsupported();
328         }
329     }
330
331     private static void addOrReplaceNodes(final StmtContext<?, ?, ?> subStmtCtx,
332             final Mutable<?, ?, ?> refineTargetNodeCtx) {
333         for (StmtContext<?, ?, ?> refineSubstatementCtx : subStmtCtx.declaredSubstatements()) {
334             if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
335                 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
336             }
337         }
338     }
339
340     private static void addOrReplaceNode(final StmtContext<?, ?, ?> refineSubstatementCtx,
341             final Mutable<?, ?, ?> refineTargetNodeCtx) {
342
343         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.publicDefinition();
344
345         // FIXME: this is quite costly, use an explicit block
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         // FIXME: childCopyOf() should handle this through per-statement copy policy, right?
356         refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx.replicaAsChildOf(refineTargetNodeCtx));
357     }
358
359     // FIXME: clarify this and inline into single caller
360     private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
361         return YangStmtMapping.MUST.equals(publicDefinition);
362     }
363
364     private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
365         final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
366                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
367
368         return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
369                 || supportedRefineSubstatements.contains(refineSubstatementCtx.publicDefinition())
370                 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
371     }
372
373     private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
374             final StmtContext<?, ?, ?> refineTargetNodeCtx) {
375         final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS.get(
376             refineSubstatementCtx.publicDefinition());
377
378         return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
379                 || supportedRefineTargets.contains(refineTargetNodeCtx.publicDefinition());
380     }
381 }