Refactor EffectiveStmtCtx.Parent.schemaPath()
[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 com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.VerifyException;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.Streams;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.HashMap;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Objects;
24 import java.util.Optional;
25 import java.util.stream.Collectors;
26 import java.util.stream.Stream;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.yangtools.concepts.Immutable;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.QNameModule;
32 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
33 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
34 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
35 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
37 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
38 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.OnDemandSchemaTreeStorageNode;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
47 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * A statement which has been inferred to exist. Functionally it is equivalent to a SubstatementContext, but it is not
53  * backed by a declaration (and declared statements). It is backed by a prototype StatementContextBase and has only
54  * effective substatements, which are either transformed from that prototype or added by inference.
55  */
56 final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
57         extends StatementContextBase<A, D, E> implements OnDemandSchemaTreeStorageNode {
58     // An effective copy view, with enough information to decide what to do next
59     private static final class EffectiveCopy implements Immutable {
60         // Original statement
61         private final ReactorStmtCtx<?, ?, ?> orig;
62         // Effective view, if the statement is to be reused it equals to orig
63         private final ReactorStmtCtx<?, ?, ?> copy;
64
65         EffectiveCopy(final ReactorStmtCtx<?, ?, ?> orig, final ReactorStmtCtx<?, ?, ?> copy) {
66             this.orig = requireNonNull(orig);
67             this.copy = requireNonNull(copy);
68         }
69
70         boolean isReused() {
71             return orig == copy;
72         }
73
74         ReactorStmtCtx<?, ?, ?> toChildContext(final @NonNull InferredStatementContext<?, ?, ?> parent) {
75             return isReused() ? orig.replicaAsChildOf(parent) : copy;
76         }
77
78         ReactorStmtCtx<?, ?, ?> toReusedChild(final @NonNull InferredStatementContext<?, ?, ?> parent) {
79             verify(isReused(), "Attempted to discard copy %s", copy);
80             return orig.replicaAsChildOf(parent);
81         }
82     }
83
84     private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class);
85
86     // Sentinel object for 'substatements'
87     private static final Object SWEPT_SUBSTATEMENTS = new Object();
88
89     private final @NonNull StatementContextBase<A, D, E> prototype;
90     private final @NonNull StatementContextBase<?, ?, ?> parent;
91     private final @NonNull StmtContext<A, D, E> originalCtx;
92     private final @NonNull CopyType childCopyType;
93     private final QNameModule targetModule;
94     private final A argument;
95
96     /**
97      * Effective substatements, lazily materialized. This field can have four states:
98      * <ul>
99      *   <li>it can be {@code null}, in which case no materialization has taken place</li>
100      *   <li>it can be a {@link HashMap}, in which case partial materialization has taken place</li>
101      *   <li>it can be a {@link List}, in which case full materialization has taken place</li>
102      *   <li>it can be {@link SWEPT_SUBSTATEMENTS}, in which case materialized state is no longer available</li>
103      * </ul>
104      */
105     private Object substatements;
106
107     private InferredStatementContext(final InferredStatementContext<A, D, E> original,
108             final StatementContextBase<?, ?, ?> parent) {
109         super(original);
110         this.parent = requireNonNull(parent);
111         this.childCopyType = original.childCopyType;
112         this.targetModule = original.targetModule;
113         this.prototype = original.prototype;
114         this.originalCtx = original.originalCtx;
115         this.argument = original.argument;
116         // Substatements are initialized here
117         this.substatements = ImmutableList.of();
118     }
119
120     InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype,
121             final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) {
122         super(prototype.definition(), CopyHistory.of(myCopyType, prototype.history()));
123         this.parent = requireNonNull(parent);
124         this.prototype = requireNonNull(prototype);
125         this.argument = targetModule == null ? prototype.argument()
126                 : prototype.definition().adaptArgumentValue(prototype, targetModule);
127         this.childCopyType = requireNonNull(childCopyType);
128         this.targetModule = targetModule;
129         this.originalCtx = prototype.getOriginalCtx().orElse(prototype);
130
131         // Mark prototype as blocking statement cleanup
132         prototype.incRef();
133     }
134
135     @Override
136     public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
137         return ImmutableList.of();
138     }
139
140     @Override
141     public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
142         return mutableEffectiveSubstatements(ensureEffectiveSubstatements());
143     }
144
145     @Override
146     public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
147         // No need to concat with declared
148         return effectiveSubstatements();
149     }
150
151     @Override
152     public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
153         // No need to concat with declared
154         return effectiveSubstatements().stream();
155     }
156
157     @Override
158     public StatementSourceReference sourceReference() {
159         return originalCtx.sourceReference();
160     }
161
162     @Override
163     public String rawArgument() {
164         return originalCtx.rawArgument();
165     }
166
167     @Override
168     public Optional<StmtContext<A, D, E>> getOriginalCtx() {
169         return Optional.of(originalCtx);
170     }
171
172     @Override
173     public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() {
174         return Optional.of(prototype);
175     }
176
177     @Override
178     public D declared() {
179         /*
180          * Share original instance of declared statement between all effective statements which have been copied or
181          * derived from this original declared statement.
182          */
183         return originalCtx.declared();
184     }
185
186     @Override
187     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
188         substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef);
189     }
190
191     @Override
192     public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
193             final String statementArg) {
194         substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef,
195             statementArg);
196     }
197
198     @Override
199     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
200         substatements = addEffectiveSubstatement(ensureEffectiveSubstatements(), substatement);
201     }
202
203     @Override
204     void addEffectiveSubstatementsImpl(final Collection<? extends Mutable<?, ?, ?>> statements) {
205         substatements = addEffectiveSubstatementsImpl(ensureEffectiveSubstatements(), statements);
206     }
207
208     @Override
209     InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
210         return new InferredStatementContext<>(this, newParent);
211     }
212
213     @Override
214     E createEffective(final StatementFactory<A, D, E> factory) {
215         // If we have not materialized we do not have a difference in effective substatements, hence we can forward
216         // towards the source of the statement.
217         return substatements == null ? tryToReusePrototype(factory) : super.createEffective(factory);
218     }
219
220     private @NonNull E tryToReusePrototype(final StatementFactory<A, D, E> factory) {
221         final E origEffective = prototype.buildEffective();
222         final Collection<? extends @NonNull EffectiveStatement<?, ?>> origSubstatements =
223             origEffective.effectiveSubstatements();
224
225         // First check if we can reuse the entire prototype
226         if (!factory.canReuseCurrent(this, prototype, origSubstatements)) {
227             return tryToReuseSubstatements(factory, origEffective);
228         }
229
230         // No substatements to deal with, we can freely reuse the original
231         if (origSubstatements.isEmpty()) {
232             LOG.debug("Reusing empty: {}", origEffective);
233             substatements = ImmutableList.of();
234             prototype.decRef();
235             return origEffective;
236         }
237
238         // We can reuse this statement let's see if all the statements agree
239         final List<EffectiveCopy> declCopy = prototype.streamDeclared()
240             .filter(StmtContext::isSupportedByFeatures)
241             .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
242             .filter(Objects::nonNull)
243             .collect(Collectors.toUnmodifiableList());
244         final List<EffectiveCopy> effCopy = prototype.streamEffective()
245             .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
246             .filter(Objects::nonNull)
247             .collect(Collectors.toUnmodifiableList());
248
249         if (allReused(declCopy) && allReused(effCopy)) {
250             LOG.debug("Reusing after substatement check: {}", origEffective);
251             // FIXME: can we skip this if !haveRef()?
252             substatements = reusePrototypeReplicas(Streams.concat(declCopy.stream(), effCopy.stream())
253                 .map(copy -> copy.toReusedChild(this)));
254             prototype.decRef();
255             return origEffective;
256         }
257
258         final List<ReactorStmtCtx<?, ?, ?>> declared = declCopy.stream()
259             .map(copy -> copy.toChildContext(this))
260             .collect(ImmutableList.toImmutableList());
261         final List<ReactorStmtCtx<?, ?, ?>> effective = effCopy.stream()
262             .map(copy -> copy.toChildContext(this))
263             .collect(ImmutableList.toImmutableList());
264         substatements = declared.isEmpty() ? effective
265             : Streams.concat(declared.stream(), effective.stream()).collect(ImmutableList.toImmutableList());
266         prototype.decRef();
267
268         // Values are the effective copies, hence this efficiently deals with recursion.
269         return factory.createEffective(this, declared.stream(), effective.stream());
270     }
271
272     private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory, final @NonNull E original) {
273         if (allSubstatementsContextIndependent()) {
274             LOG.debug("Reusing substatements of: {}", prototype);
275             // FIXME: can we skip this if !haveRef()?
276             substatements = reusePrototypeReplicas();
277             prototype.decRef();
278             return factory.copyEffective(this, original);
279         }
280
281         // Fall back to full instantiation, which populates our substatements. Then check if we should be reusing
282         // the substatement list, as this operation turned out to not affect them.
283         final E effective = super.createEffective(factory);
284         if (sameSubstatements(original.effectiveSubstatements(), effective)) {
285             LOG.debug("Reusing unchanged substatements of: {}", prototype);
286             return factory.copyEffective(this, original);
287         }
288         return effective;
289     }
290
291     private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas() {
292         return reusePrototypeReplicas(Streams.concat(
293             prototype.streamDeclared().filter(StmtContext::isSupportedByFeatures),
294             prototype.streamEffective()));
295     }
296
297     private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<StmtContext<?, ?, ?>> stream) {
298         return stream
299             .map(stmt -> {
300                 final ReplicaStatementContext<?, ?, ?> ret = ((ReactorStmtCtx<?, ?, ?>) stmt).replicaAsChildOf(this);
301                 ret.buildEffective();
302                 return ret;
303             })
304             .collect(Collectors.toUnmodifiableList());
305     }
306
307     private static boolean sameSubstatements(final Collection<?> original, final EffectiveStatement<?, ?> effective) {
308         final Collection<?> copied = effective.effectiveSubstatements();
309         if (copied != effective.effectiveSubstatements() || original.size() != copied.size()) {
310             // Do not bother if result is treating substatements as transient
311             return false;
312         }
313
314         final Iterator<?> oit = original.iterator();
315         final Iterator<?> cit = copied.iterator();
316         while (oit.hasNext()) {
317             verify(cit.hasNext());
318             // Identity comparison on purpose to side-step whatever equality there might be. We want to reuse instances
319             // after all.
320             if (oit.next() != cit.next()) {
321                 return false;
322             }
323         }
324         verify(!cit.hasNext());
325         return true;
326     }
327
328     private static boolean allReused(final List<EffectiveCopy> entries) {
329         return entries.stream().allMatch(EffectiveCopy::isReused);
330     }
331
332     @Override
333     boolean hasEmptySubstatements() {
334         if (substatements == null) {
335             return prototype.hasEmptySubstatements();
336         }
337         return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty();
338     }
339
340     @Override
341     boolean noSensitiveSubstatements() {
342         accessSubstatements();
343         if (substatements == null) {
344             // No difference, defer to prototype
345             return prototype.allSubstatementsContextIndependent();
346         }
347         if (substatements instanceof List) {
348             // Fully materialized, walk all statements
349             return noSensitiveSubstatements(castEffective(substatements));
350         }
351
352         // Partially-materialized. This case has three distinct outcomes:
353         // - prototype does not have a sensitive statement (1)
354         // - protype has a sensitive substatement, and
355         //   - we have not marked is as unsupported (2)
356         //   - we have marked it as unsupported (3)
357         //
358         // Determining the outcome between (2) and (3) is a bother, this check errs on the side of false negative side
359         // and treats (3) as (2) -- i.e. even if we marked a sensitive statement as unsupported, we still consider it
360         // as affecting the result.
361         return prototype.allSubstatementsContextIndependent()
362             && noSensitiveSubstatements(castMaterialized(substatements).values());
363     }
364
365     @Override
366     public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
367             final @NonNull Class<Z> type) {
368         if (substatements instanceof List) {
369             return super.findSubstatementArgument(type);
370         }
371
372         final Optional<X> templateArg = prototype.findSubstatementArgument(type);
373         if (templateArg.isEmpty()) {
374             return templateArg;
375         }
376         if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
377             // X is known to be QName
378             return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
379         }
380         return templateArg;
381     }
382
383     @Override
384     public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
385         return substatements instanceof List ? super.hasSubstatement(type)
386             // We do not allow deletion of partially-materialized statements, hence this is accurate
387             : prototype.hasSubstatement(type);
388     }
389
390     @Override
391     public <Y extends DeclaredStatement<QName>, Z extends SchemaTreeEffectiveStatement<Y>>
392             StmtContext<QName, Y, Z> requestSchemaTreeChild(final QName qname) {
393         if (substatements instanceof List) {
394             // We have performed materialization, hence we have triggered creation of all our schema tree child
395             // statements.
396             return null;
397         }
398
399         final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype));
400         LOG.debug("Materializing child {} from {}", qname, templateQName);
401
402         final StmtContext<?, ?, ?> template;
403         if (prototype instanceof InferredStatementContext) {
404             // Note: we need to access namespace here, as the target statement may have already been populated, in which
405             //       case we want to obtain the statement in local namespace storage.
406             template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(
407                 SchemaTreeNamespace.class, templateQName);
408         } else {
409             template = prototype.allSubstatementsStream()
410                 .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
411                     && templateQName.equals(stmt.argument()))
412                 .findAny()
413                 .orElse(null);
414         }
415
416         if (template == null) {
417             // We do not have a template, this child does not exist. It may be added later, but that is someone else's
418             // responsibility.
419             LOG.debug("Child {} does not have a template", qname);
420             return null;
421         }
422
423         @SuppressWarnings("unchecked")
424         final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
425             .orElseThrow(
426                 () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
427         ensureCompletedPhase(ret);
428         addMaterialized(template, ret);
429
430         LOG.debug("Child {} materialized", qname);
431         return ret;
432     }
433
434     // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
435     // BuildGlobalContext, hence it must be called at most once.
436     private List<ReactorStmtCtx<?, ?, ?>> ensureEffectiveSubstatements() {
437         accessSubstatements();
438         return substatements instanceof List ? castEffective(substatements)
439             : initializeSubstatements(castMaterialized(substatements));
440     }
441
442     @Override
443     Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() {
444         // When we have not initialized, there are no statements to catch up: we will catch up when we are copying
445         // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL).
446         if (substatements == null) {
447             return ImmutableList.of();
448         }
449         accessSubstatements();
450         if (substatements instanceof HashMap) {
451             return castMaterialized(substatements).values();
452         } else {
453             return castEffective(substatements);
454         }
455     }
456
457     @Override
458     Stream<? extends StmtContext<?, ?, ?>> streamDeclared() {
459         return Stream.empty();
460     }
461
462     @Override
463     Stream<? extends StmtContext<?, ?, ?>> streamEffective() {
464         accessSubstatements();
465         return ensureEffectiveSubstatements().stream();
466     }
467
468     private void accessSubstatements() {
469         verify(substatements != SWEPT_SUBSTATEMENTS, "Attempted to access substatements of %s", this);
470     }
471
472     @Override
473     void markNoParentRef() {
474         final Object local = substatements;
475         if (local != null) {
476             markNoParentRef(castEffective(local));
477         }
478     }
479
480     @Override
481     int sweepSubstatements() {
482         final Object local = substatements;
483         substatements = SWEPT_SUBSTATEMENTS;
484         int count = 0;
485         if (local != null) {
486             final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local);
487             sweep(list);
488             count = countUnswept(list);
489         }
490         return count;
491     }
492
493     private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements(
494             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
495         final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
496         final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
497
498         final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
499         for (final Mutable<?, ?, ?> stmtContext : declared) {
500             if (stmtContext.isSupportedByFeatures()) {
501                 copySubstatement(stmtContext, buffer, materializedSchemaTree);
502             }
503         }
504         for (final Mutable<?, ?, ?> stmtContext : effective) {
505             copySubstatement(stmtContext, buffer, materializedSchemaTree);
506         }
507
508         final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
509         ret.addAll((Collection) buffer);
510         substatements = ret;
511
512         prototype.decRef();
513         return ret;
514     }
515
516     // Statement copy mess starts here
517     //
518     // FIXME: This is messy and is probably wrong in some corner case. Even if it is correct, the way how it is correct
519     //        relies on hard-coded maps. At the end of the day, the logic needs to be controlled by statement's
520     //        StatementSupport.
521     // FIXME: YANGTOOLS-652: this map looks very much like UsesStatementSupport.TOP_REUSED_DEF_SET
522     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.USES);
523
524     private EffectiveCopy effectiveCopy(final ReactorStmtCtx<?, ?, ?> stmt) {
525         // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses"
526         if (REUSED_DEF_SET.contains(stmt.definition().getPublicView())) {
527             return new EffectiveCopy(stmt, stmt);
528         }
529
530         final ReactorStmtCtx<?, ?, ?> effective = stmt.asEffectiveChildOf(this, childCopyType, targetModule);
531         return effective == null ? null : new EffectiveCopy(stmt, effective);
532     }
533
534     private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
535             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
536         final StatementDefinition def = substatement.publicDefinition();
537
538         // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses"
539         if (REUSED_DEF_SET.contains(def)) {
540             LOG.trace("Reusing substatement {} for {}", substatement, this);
541             buffer.add(substatement.replicaAsChildOf(this));
542             return;
543         }
544
545         // Consult materialized substatements. We are in a copy operation and will end up throwing materialized
546         // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
547         //
548         // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
549         // against parent would change -- and we certainly do not want that to happen.
550         final ReactorStmtCtx<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
551         if (materialized == null) {
552             copySubstatement(substatement).ifPresent(copy -> {
553                 ensureCompletedPhase(copy);
554                 buffer.add(copy);
555             });
556         } else {
557             buffer.add(materialized);
558         }
559     }
560
561     private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
562         // FIXME: YANGTOOLS-1195: this is not exactly what we want to do here, because we are dealing with two different
563         //                        requests: copy for inference purposes (this method), while we also copy for purposes
564         //                        of buildEffective() -- in which case we want to probably invoke asEffectiveChildOf()
565         //                        or similar
566         return substatement.copyAsChildOf(this, childCopyType, targetModule);
567     }
568
569     private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
570         final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree;
571         if (substatements == null) {
572             // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
573             // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
574             // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
575             // resizing operation.
576             materializedSchemaTree = new HashMap<>(4);
577             substatements = materializedSchemaTree;
578         } else {
579             verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
580             materializedSchemaTree = castMaterialized(substatements);
581         }
582
583         final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
584             (StatementContextBase<?, ?, ?>) copy);
585         if (existing != null) {
586             throw new VerifyException(
587                 "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
588         }
589     }
590
591     private static @Nullable ReactorStmtCtx<?, ?, ?> findMaterialized(
592             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree,
593             final StmtContext<?, ?, ?> template) {
594         return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
595     }
596
597     @SuppressWarnings("unchecked")
598     private static List<ReactorStmtCtx<?, ?, ?>> castEffective(final Object substatements) {
599         return (List<ReactorStmtCtx<?, ?, ?>>) substatements;
600     }
601
602     @SuppressWarnings("unchecked")
603     private static HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> castMaterialized(final Object substatements) {
604         return (HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>>) substatements;
605     }
606
607     // Statement copy mess ends here
608
609     /*
610      * KEEP THINGS ORGANIZED!
611      *
612      * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
613      * properly updated there.
614      */
615     @Override
616     @Deprecated
617     public SchemaPath schemaPath() {
618         return substatementGetSchemaPath();
619     }
620
621     @Override
622     public A argument() {
623         return argument;
624     }
625
626     @Override
627     public StatementContextBase<?, ?, ?> getParentContext() {
628         return parent;
629     }
630
631     @Override
632     public StorageNodeType getStorageNodeType() {
633         return StorageNodeType.STATEMENT_LOCAL;
634     }
635
636     @Override
637     public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
638         return parent;
639     }
640
641     @Override
642     public RootStatementContext<?, ?, ?> getRoot() {
643         return parent.getRoot();
644     }
645
646     @Override
647     public EffectiveConfig effectiveConfig() {
648         return effectiveConfig(parent);
649     }
650
651     @Override
652     protected boolean isIgnoringIfFeatures() {
653         return isIgnoringIfFeatures(parent);
654     }
655
656     @Override
657     protected boolean isIgnoringConfig() {
658         return isIgnoringConfig(parent);
659     }
660
661     @Override
662     protected boolean isParentSupportedByFeatures() {
663         return parent.isSupportedByFeatures();
664     }
665 }