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