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