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