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