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