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