Add StmtContext.findFirstSubstatementArgument()
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / InferredStatementContext.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, 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.stmt.reactor;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableSet;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.List;
17 import java.util.Optional;
18 import java.util.stream.Stream;
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.model.api.SchemaPath;
23 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
24 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
27 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
28 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.OnDemandSchemaTreeStorageNode;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextDefaults;
34 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * A statement which has been inferred to exist. Functionally it is equivalent to a SubstatementContext, but it is not
40  * backed by a declaration (and declared statements). It is backed by a prototype StatementContextBase and has only
41  * effective substatements, which are either transformed from that prototype or added by inference.
42  */
43 final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
44         extends StatementContextBase<A, D, E> implements OnDemandSchemaTreeStorageNode {
45     private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class);
46
47     private final @NonNull StatementContextBase<A, D, E> prototype;
48     private final @NonNull StatementContextBase<?, ?, ?> parent;
49     private final @NonNull StmtContext<A, D, E> originalCtx;
50     private final @NonNull CopyType childCopyType;
51     private final QNameModule targetModule;
52     private final A argument;
53
54     private InferredStatementContext(final InferredStatementContext<A, D, E> original,
55             final StatementContextBase<?, ?, ?> parent) {
56         super(original);
57         this.parent = requireNonNull(parent);
58         this.childCopyType = original.childCopyType;
59         this.targetModule = original.targetModule;
60         this.prototype = original.prototype;
61         this.originalCtx = original.originalCtx;
62         this.argument = original.argument;
63         setSubstatementsInitialized();
64     }
65
66     InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype,
67             final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) {
68         super(prototype.definition(), CopyHistory.of(myCopyType, prototype.getCopyHistory()));
69         this.parent = requireNonNull(parent);
70         this.prototype = requireNonNull(prototype);
71         this.argument = targetModule == null ? prototype.getStatementArgument()
72                 : prototype.definition().adaptArgumentValue(prototype, targetModule);
73         this.childCopyType = requireNonNull(childCopyType);
74         this.targetModule = targetModule;
75         this.originalCtx = prototype.getOriginalCtx().orElse(prototype);
76
77         // Note: substatements from prototype are initialized lazily through ensureSubstatements()
78     }
79
80     @Override
81     public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
82         return ImmutableList.of();
83     }
84
85     @Override
86     public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
87         // No need to concat with declared
88         return effectiveSubstatements();
89     }
90
91     @Override
92     public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
93         // No need to concat with declared
94         return effectiveSubstatements().stream();
95     }
96
97     @Override
98     public StatementSourceReference getStatementSourceReference() {
99         return originalCtx.getStatementSourceReference();
100     }
101
102     @Override
103     public String rawStatementArgument() {
104         return originalCtx.rawStatementArgument();
105     }
106
107     @Override
108     public Optional<StmtContext<A, D, E>> getOriginalCtx() {
109         return Optional.of(originalCtx);
110     }
111
112     @Override
113     public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() {
114         return Optional.of(prototype);
115     }
116
117     @Override
118     public D buildDeclared() {
119         /*
120          * Share original instance of declared statement between all effective statements which have been copied or
121          * derived from this original declared statement.
122          */
123         return originalCtx.buildDeclared();
124     }
125
126     @Override
127     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
128         ensureSubstatements();
129         return super.mutableEffectiveSubstatements();
130     }
131
132     @Override
133     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
134         ensureSubstatements();
135         super.addEffectiveSubstatement(substatement);
136     }
137
138     @Override
139     public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
140         ensureSubstatements();
141         super.addEffectiveSubstatements(statements);
142     }
143
144     @Override
145     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
146             final String statementArg) {
147         ensureSubstatements();
148         super.removeStatementFromEffectiveSubstatements(statementDef, statementArg);
149     }
150
151     @Override
152     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
153         ensureSubstatements();
154         super.removeStatementFromEffectiveSubstatements(statementDef);
155     }
156
157     @Override
158     InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
159         return new InferredStatementContext<>(this, newParent);
160     }
161
162     @Override
163     boolean hasEmptySubstatements() {
164         ensureSubstatements();
165         return hasEmptyEffectiveSubstatements();
166     }
167
168     @Override
169     public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
170             final @NonNull Class<Z> type) {
171         if (substatementsInitialized()) {
172             return StmtContextDefaults.findSubstatementArgument(this, type);
173         }
174
175         final Optional<X> templateArg = prototype.findSubstatementArgument(type);
176         if (templateArg.isEmpty()) {
177             return templateArg;
178         }
179         if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
180             // X is known to be QName
181             return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
182         }
183         return templateArg;
184     }
185
186     @Override
187     public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
188         return substatementsInitialized() ? StmtContextDefaults.hasSubstatement(prototype, type)
189             : prototype.hasSubstatement(type);
190     }
191
192     @Override
193     public <D extends DeclaredStatement<QName>, E extends EffectiveStatement<QName, D>>
194             StmtContext<QName, D, E> requestSchemaTreeChild(final QName qname) {
195         LOG.debug("Materializing on lookup of {}", qname);
196         // FIXME: YANGTOOLS-1160: we do not want to force full materialization here
197         ensureSubstatements();
198
199         // Now we have to do a lookup as we do not have access to the namespace being populated (yet). Here we are
200         // bypassing additional checks and talk directly to superclass to get the statements.
201         for (StmtContext<?, ?, ?> stmt : super.mutableEffectiveSubstatements()) {
202             if (stmt.producesEffective(SchemaTreeEffectiveStatement.class)
203                 && qname.equals(stmt.coerceStatementArgument())) {
204                 return (StmtContext<QName, D, E>) stmt;
205             }
206         }
207         return null;
208     }
209
210     // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
211     // BuildGlobalContext, hence it must be called at most once.
212     private void ensureSubstatements() {
213         if (!substatementsInitialized()) {
214             initializeSubstatements();
215         }
216     }
217
218     private void initializeSubstatements() {
219         final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
220         final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
221         final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
222
223         for (final Mutable<?, ?, ?> stmtContext : declared) {
224             if (stmtContext.isSupportedByFeatures()) {
225                 copySubstatement(stmtContext, buffer);
226             }
227         }
228         for (final Mutable<?, ?, ?> stmtContext : effective) {
229             copySubstatement(stmtContext, buffer);
230         }
231
232         // We are bypassing usual safeties here, as this is not introducing new statements but rather just materializing
233         // them when the need has arised.
234         addInitialEffectiveSubstatements(buffer);
235     }
236
237     // Statement copy mess starts here
238     //
239     // FIXME: This is messy and is probably wrong in some corner case. Even if it is correct, the way how it is correct
240     //        relies on hard-coded maps. At the end of the day, the logic needs to be controlled by statement's
241     //        StatementSupport.
242     // FIXME: YANGTOOLS-652: this map looks very much like UsesStatementSupport.TOP_REUSED_DEF_SET
243     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
244         YangStmtMapping.TYPE,
245         YangStmtMapping.TYPEDEF,
246         YangStmtMapping.USES);
247
248     private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer) {
249         final StatementDefinition def = substatement.getPublicDefinition();
250
251         // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses"
252         if (REUSED_DEF_SET.contains(def)) {
253             LOG.debug("Reusing substatement {} for {}", substatement, this);
254             buffer.add(substatement);
255             return;
256         }
257
258         substatement.copyAsChildOf(this, childCopyType, targetModule).ifPresent(buffer::add);
259     }
260
261     // Statement copy mess ends here
262
263     /*
264      * KEEP THINGS ORGANIZED!
265      *
266      * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
267      * properly updated there.
268      */
269     @Override
270     @Deprecated
271     public Optional<SchemaPath> getSchemaPath() {
272         return substatementGetSchemaPath();
273     }
274
275     @Override
276     public A getStatementArgument() {
277         return argument;
278     }
279
280     @Override
281     public StatementContextBase<?, ?, ?> getParentContext() {
282         return parent;
283     }
284
285     @Override
286     public StorageNodeType getStorageNodeType() {
287         return StorageNodeType.STATEMENT_LOCAL;
288     }
289
290     @Override
291     public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
292         return parent;
293     }
294
295     @Override
296     public RootStatementContext<?, ?, ?> getRoot() {
297         return parent.getRoot();
298     }
299
300     @Override
301     public boolean isConfiguration() {
302         return isConfiguration(parent);
303     }
304
305     @Override
306     protected boolean isIgnoringIfFeatures() {
307         return isIgnoringIfFeatures(parent);
308     }
309
310     @Override
311     protected boolean isIgnoringConfig() {
312         return isIgnoringConfig(parent);
313     }
314
315     @Override
316     protected boolean isParentSupportedByFeatures() {
317         return parent.isSupportedByFeatures();
318     }
319 }