Use simple requireNonNull()
[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     InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
128         return new InferredStatementContext<>(this, newParent);
129     }
130
131     @Override
132     boolean hasEmptySubstatements() {
133         ensureEffectiveSubstatements();
134         return hasEmptyEffectiveSubstatements();
135     }
136
137     @Override
138     public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
139             final @NonNull Class<Z> type) {
140         if (substatementsInitialized()) {
141             return StmtContextDefaults.findSubstatementArgument(this, type);
142         }
143
144         final Optional<X> templateArg = prototype.findSubstatementArgument(type);
145         if (templateArg.isEmpty()) {
146             return templateArg;
147         }
148         if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
149             // X is known to be QName
150             return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
151         }
152         return templateArg;
153     }
154
155     @Override
156     public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
157         return substatementsInitialized() ? StmtContextDefaults.hasSubstatement(prototype, type)
158             : prototype.hasSubstatement(type);
159     }
160
161     @Override
162     public <D extends DeclaredStatement<QName>, E extends EffectiveStatement<QName, D>>
163             StmtContext<QName, D, E> requestSchemaTreeChild(final QName qname) {
164         LOG.debug("Materializing on lookup of {}", qname);
165         // FIXME: YANGTOOLS-1160: we do not want to force full materialization here
166         ensureEffectiveSubstatements();
167
168         // Now we have to do a lookup as we do not have access to the namespace being populated (yet). Here we are
169         // bypassing additional checks and talk directly to superclass to get the statements.
170         for (StmtContext<?, ?, ?> stmt : super.mutableEffectiveSubstatements()) {
171             if (stmt.producesEffective(SchemaTreeEffectiveStatement.class)
172                 && qname.equals(stmt.coerceStatementArgument())) {
173                 return (StmtContext<QName, D, E>) stmt;
174             }
175         }
176         return null;
177     }
178
179     // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
180     // BuildGlobalContext, hence it must be called at most once.
181     @Override
182     void ensureEffectiveSubstatements() {
183         if (!substatementsInitialized()) {
184             initializeSubstatements();
185         }
186     }
187
188     @Override
189     Iterable<StatementContextBase<?, ?, ?>> effectiveChildrenToComplete() {
190         // When we have not initialized, there are no statements to catch up: we will catch up when we are copying
191         // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL)
192         return substatementsInitialized() ? super.effectiveChildrenToComplete() : List.of();
193     }
194
195     private void initializeSubstatements() {
196         final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
197         final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
198         final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
199
200         for (final Mutable<?, ?, ?> stmtContext : declared) {
201             if (stmtContext.isSupportedByFeatures()) {
202                 copySubstatement(stmtContext, buffer);
203             }
204         }
205         for (final Mutable<?, ?, ?> stmtContext : effective) {
206             copySubstatement(stmtContext, buffer);
207         }
208
209         // We are bypassing usual safeties here, as this is not introducing new statements but rather just materializing
210         // them when the need has arised.
211         addInitialEffectiveSubstatements(buffer);
212     }
213
214     // Statement copy mess starts here
215     //
216     // FIXME: This is messy and is probably wrong in some corner case. Even if it is correct, the way how it is correct
217     //        relies on hard-coded maps. At the end of the day, the logic needs to be controlled by statement's
218     //        StatementSupport.
219     // FIXME: YANGTOOLS-652: this map looks very much like UsesStatementSupport.TOP_REUSED_DEF_SET
220     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
221         YangStmtMapping.TYPE,
222         YangStmtMapping.TYPEDEF,
223         YangStmtMapping.USES);
224
225     private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer) {
226         final StatementDefinition def = substatement.getPublicDefinition();
227
228         // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses"
229         if (REUSED_DEF_SET.contains(def)) {
230             LOG.debug("Reusing substatement {} for {}", substatement, this);
231             buffer.add(substatement);
232             return;
233         }
234
235         substatement.copyAsChildOf(this, childCopyType, targetModule).ifPresent(buffer::add);
236     }
237
238     // Statement copy mess ends here
239
240     /*
241      * KEEP THINGS ORGANIZED!
242      *
243      * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
244      * properly updated there.
245      */
246     @Override
247     @Deprecated
248     public Optional<SchemaPath> getSchemaPath() {
249         return substatementGetSchemaPath();
250     }
251
252     @Override
253     public A getStatementArgument() {
254         return argument;
255     }
256
257     @Override
258     public StatementContextBase<?, ?, ?> getParentContext() {
259         return parent;
260     }
261
262     @Override
263     public StorageNodeType getStorageNodeType() {
264         return StorageNodeType.STATEMENT_LOCAL;
265     }
266
267     @Override
268     public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
269         return parent;
270     }
271
272     @Override
273     public RootStatementContext<?, ?, ?> getRoot() {
274         return parent.getRoot();
275     }
276
277     @Override
278     public boolean isConfiguration() {
279         return isConfiguration(parent);
280     }
281
282     @Override
283     protected boolean isIgnoringIfFeatures() {
284         return isIgnoringIfFeatures(parent);
285     }
286
287     @Override
288     protected boolean isIgnoringConfig() {
289         return isIgnoringConfig(parent);
290     }
291
292     @Override
293     protected boolean isParentSupportedByFeatures() {
294         return parent.isSupportedByFeatures();
295     }
296 }