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