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