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