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