3d012f30b54d7fa9457b6b388096b8afd283ffd2
[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.SchemaPath;
32 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
33 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
35 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
36 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
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             // FIXME: YANGTOOLS-1214: deduplicate this return
224             return tryToReuseSubstatements(factory, origEffective);
225         }
226
227         // We can reuse this statement let's see if all statements agree...
228         // ... no substatements to deal with, we can freely reuse the original
229         if (origSubstatements.isEmpty()) {
230             LOG.debug("Reusing empty: {}", origEffective);
231             substatements = ImmutableList.of();
232             prototype.decRef();
233             return origEffective;
234         }
235
236         // ... all are context independent, reuse the original
237         if (allSubstatementsContextIndependent()) {
238             LOG.debug("Reusing context-independent: {}", origEffective);
239             substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
240             prototype.decRef();
241             return origEffective;
242         }
243
244         // ... copy-sensitive check
245         final List<EffectiveCopy> declCopy = prototype.streamDeclared()
246             .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
247             .filter(Objects::nonNull)
248             .collect(Collectors.toUnmodifiableList());
249         final List<EffectiveCopy> effCopy = prototype.streamEffective()
250             .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
251             .filter(Objects::nonNull)
252             .collect(Collectors.toUnmodifiableList());
253
254         // ... are any copy-sensitive?
255         if (allReused(declCopy) && allReused(effCopy)) {
256             LOG.debug("Reusing after substatement check: {}", origEffective);
257             substatements = noRefs() ? REUSED_SUBSTATEMENTS
258                 : reusePrototypeReplicas(Streams.concat(declCopy.stream(), effCopy.stream())
259                     .map(copy -> copy.toReusedChild(this)));
260             prototype.decRef();
261             return origEffective;
262         }
263
264         // *sigh*, ok, heavy lifting through a shallow copy
265         final List<ReactorStmtCtx<?, ?, ?>> declared = declCopy.stream()
266             .map(copy -> copy.toChildContext(this))
267             .collect(ImmutableList.toImmutableList());
268         final List<ReactorStmtCtx<?, ?, ?>> effective = effCopy.stream()
269             .map(copy -> copy.toChildContext(this))
270             .collect(ImmutableList.toImmutableList());
271         substatements = declared.isEmpty() ? effective
272             : Streams.concat(declared.stream(), effective.stream()).collect(ImmutableList.toImmutableList());
273         prototype.decRef();
274
275         // Values are the effective copies, hence this efficiently deals with recursion.
276         // FIXME: YANGTOOLS-1214: deduplicate this return
277         return factory.createEffective(this, declared.stream(), effective.stream());
278     }
279
280     private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory, final @NonNull E original) {
281         if (allSubstatementsContextIndependent()) {
282             LOG.debug("Reusing substatements of: {}", prototype);
283             substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
284             prototype.decRef();
285             return factory.copyEffective(this, original);
286         }
287
288         // Fall back to full instantiation, which populates our substatements. Then check if we should be reusing
289         // the substatement list, as this operation turned out to not affect them.
290         final E effective = super.createEffective(factory);
291         // Since we have forced instantiation to deal with this case, we also need to reset the 'modified' flag
292         setUnmodified();
293
294         if (sameSubstatements(original.effectiveSubstatements(), effective)) {
295             LOG.debug("Reusing unchanged substatements of: {}", prototype);
296             return factory.copyEffective(this, original);
297         }
298         return effective;
299     }
300
301     private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas() {
302         return reusePrototypeReplicas(Streams.concat(prototype.streamDeclared(), prototype.streamEffective()));
303     }
304
305     private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<StmtContext<?, ?, ?>> stream) {
306         return stream
307             .map(stmt -> {
308                 final ReplicaStatementContext<?, ?, ?> ret = ((ReactorStmtCtx<?, ?, ?>) stmt).replicaAsChildOf(this);
309                 ret.buildEffective();
310                 return ret;
311             })
312             .collect(Collectors.toUnmodifiableList());
313     }
314
315     private static boolean sameSubstatements(final Collection<?> original, final EffectiveStatement<?, ?> effective) {
316         final Collection<?> copied = effective.effectiveSubstatements();
317         if (copied != effective.effectiveSubstatements() || original.size() != copied.size()) {
318             // Do not bother if result is treating substatements as transient
319             return false;
320         }
321
322         final Iterator<?> oit = original.iterator();
323         final Iterator<?> cit = copied.iterator();
324         while (oit.hasNext()) {
325             verify(cit.hasNext());
326             // Identity comparison on purpose to side-step whatever equality there might be. We want to reuse instances
327             // after all.
328             if (oit.next() != cit.next()) {
329                 return false;
330             }
331         }
332         verify(!cit.hasNext());
333         return true;
334     }
335
336     private static boolean allReused(final List<EffectiveCopy> entries) {
337         return entries.stream().allMatch(EffectiveCopy::isReused);
338     }
339
340     @Override
341     ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource() {
342         return isModified() ? this : prototype.unmodifiedEffectiveSource();
343     }
344
345     @Override
346     boolean hasEmptySubstatements() {
347         if (substatements == null) {
348             return prototype.hasEmptySubstatements();
349         }
350         return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty();
351     }
352
353     @Override
354     boolean noSensitiveSubstatements() {
355         accessSubstatements();
356         if (substatements == null) {
357             // No difference, defer to prototype
358             return prototype.allSubstatementsContextIndependent();
359         }
360         if (substatements instanceof List) {
361             // Fully materialized, walk all statements
362             return noSensitiveSubstatements(castEffective(substatements));
363         }
364
365         // Partially-materialized. This case has three distinct outcomes:
366         // - prototype does not have a sensitive statement (1)
367         // - protype has a sensitive substatement, and
368         //   - we have not marked is as unsupported (2)
369         //   - we have marked it as unsupported (3)
370         //
371         // Determining the outcome between (2) and (3) is a bother, this check errs on the side of false negative side
372         // and treats (3) as (2) -- i.e. even if we marked a sensitive statement as unsupported, we still consider it
373         // as affecting the result.
374         return prototype.allSubstatementsContextIndependent()
375             && noSensitiveSubstatements(castMaterialized(substatements).values());
376     }
377
378     @Override
379     <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
380             final @NonNull Class<Z> type) {
381         if (substatements instanceof List) {
382             return super.findSubstatementArgumentImpl(type);
383         }
384
385         final Optional<X> templateArg = prototype.findSubstatementArgument(type);
386         if (templateArg.isEmpty()) {
387             return templateArg;
388         }
389         if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
390             // X is known to be QName
391             return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
392         }
393         return templateArg;
394     }
395
396     @Override
397     boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
398         return substatements instanceof List ? super.hasSubstatementImpl(type)
399             // We do not allow deletion of partially-materialized statements, hence this is accurate
400             : prototype.hasSubstatement(type);
401     }
402
403     @Override
404     public <Y extends DeclaredStatement<QName>, Z extends SchemaTreeEffectiveStatement<Y>>
405             StmtContext<QName, Y, Z> requestSchemaTreeChild(final QName qname) {
406         if (substatements instanceof List) {
407             // We have performed materialization, hence we have triggered creation of all our schema tree child
408             // statements.
409             return null;
410         }
411
412         final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype));
413         LOG.debug("Materializing child {} from {}", qname, templateQName);
414
415         final StmtContext<?, ?, ?> template;
416         if (prototype instanceof InferredStatementContext) {
417             // Note: we need to access namespace here, as the target statement may have already been populated, in which
418             //       case we want to obtain the statement in local namespace storage.
419             template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(
420                 SchemaTreeNamespace.class, templateQName);
421         } else {
422             template = prototype.allSubstatementsStream()
423                 .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
424                     && templateQName.equals(stmt.argument()))
425                 .findAny()
426                 .orElse(null);
427         }
428
429         if (template == null) {
430             // We do not have a template, this child does not exist. It may be added later, but that is someone else's
431             // responsibility.
432             LOG.debug("Child {} does not have a template", qname);
433             return null;
434         }
435
436         @SuppressWarnings("unchecked")
437         final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
438             .orElseThrow(
439                 () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
440         ensureCompletedPhase(ret);
441         addMaterialized(template, ret);
442
443         LOG.debug("Child {} materialized", qname);
444         return ret;
445     }
446
447     // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
448     // BuildGlobalContext, hence it must be called at most once.
449     private List<ReactorStmtCtx<?, ?, ?>> ensureEffectiveSubstatements() {
450         accessSubstatements();
451         return substatements instanceof List ? castEffective(substatements)
452             : initializeSubstatements(castMaterialized(substatements));
453     }
454
455     @Override
456     Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() {
457         // When we have not initialized, there are no statements to catch up: we will catch up when we are copying
458         // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL).
459         if (substatements == null) {
460             return ImmutableList.of();
461         }
462         accessSubstatements();
463         if (substatements instanceof HashMap) {
464             return castMaterialized(substatements).values();
465         } else {
466             return castEffective(substatements);
467         }
468     }
469
470     @Override
471     Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared() {
472         return Stream.empty();
473     }
474
475     @Override
476     Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective() {
477         return ensureEffectiveSubstatements().stream().filter(StmtContext::isSupportedToBuildEffective);
478     }
479
480     private void accessSubstatements() {
481         if (substatements instanceof String) {
482             throw new VerifyException("Access to " + substatements + " substatements of " + this);
483         }
484     }
485
486     @Override
487     void markNoParentRef() {
488         final Object local = substatements;
489         if (local != null) {
490             markNoParentRef(castEffective(local));
491         }
492     }
493
494     @Override
495     int sweepSubstatements() {
496         final Object local = substatements;
497         substatements = SWEPT_SUBSTATEMENTS;
498         int count = 0;
499         if (local instanceof List) {
500             final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local);
501             sweep(list);
502             count = countUnswept(list);
503         }
504         return count;
505     }
506
507     private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements(
508             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
509         final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
510         final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
511
512         final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
513         for (final Mutable<?, ?, ?> stmtContext : declared) {
514             if (stmtContext.isSupportedByFeatures()) {
515                 copySubstatement(stmtContext, buffer, materializedSchemaTree);
516             }
517         }
518         for (final Mutable<?, ?, ?> stmtContext : effective) {
519             copySubstatement(stmtContext, buffer, materializedSchemaTree);
520         }
521
522         final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
523         ret.addAll((Collection) buffer);
524         substatements = ret;
525         setModified();
526
527         prototype.decRef();
528         return ret;
529     }
530
531     //
532     // Statement copy mess starts here. As it turns out, it's not that much of a mess, but it does make your head spin
533     // sometimes. Tread softly because you tread on my dreams.
534     //
535
536     private EffectiveCopy effectiveCopy(final ReactorStmtCtx<?, ?, ?> stmt) {
537         final ReactorStmtCtx<?, ?, ?> effective = stmt.asEffectiveChildOf(this, childCopyType(), targetModule);
538         return effective == null ? null : new EffectiveCopy(stmt, effective);
539     }
540
541     private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
542             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
543         // Consult materialized substatements. We are in a copy operation and will end up throwing materialized
544         // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
545         //
546         // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
547         // against parent would change -- and we certainly do not want that to happen.
548         final ReactorStmtCtx<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
549         if (materialized == null) {
550             copySubstatement(substatement).ifPresent(copy -> {
551                 ensureCompletedPhase(copy);
552                 buffer.add(copy);
553             });
554         } else {
555             buffer.add(materialized);
556         }
557     }
558
559     private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
560         return substatement.copyAsChildOf(this, childCopyType(), targetModule);
561     }
562
563     private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
564         final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree;
565         if (substatements == null) {
566             // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
567             // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
568             // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
569             // resizing operation.
570             materializedSchemaTree = new HashMap<>(4);
571             substatements = materializedSchemaTree;
572             setModified();
573         } else {
574             verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
575             materializedSchemaTree = castMaterialized(substatements);
576         }
577
578         final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
579             (StatementContextBase<?, ?, ?>) copy);
580         if (existing != null) {
581             throw new VerifyException(
582                 "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
583         }
584     }
585
586     private static @Nullable ReactorStmtCtx<?, ?, ?> findMaterialized(
587             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree,
588             final StmtContext<?, ?, ?> template) {
589         return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
590     }
591
592     @SuppressWarnings("unchecked")
593     private static List<ReactorStmtCtx<?, ?, ?>> castEffective(final Object substatements) {
594         return (List<ReactorStmtCtx<?, ?, ?>>) substatements;
595     }
596
597     @SuppressWarnings("unchecked")
598     private static HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> castMaterialized(final Object substatements) {
599         return (HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>>) substatements;
600     }
601
602     // Statement copy mess ends here
603
604     /*
605      * KEEP THINGS ORGANIZED!
606      *
607      * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
608      * properly updated there.
609      */
610     @Override
611     @Deprecated
612     public SchemaPath schemaPath() {
613         return substatementGetSchemaPath();
614     }
615
616     @Override
617     public A argument() {
618         return argument;
619     }
620
621     @Override
622     public StatementContextBase<?, ?, ?> getParentContext() {
623         return parent;
624     }
625
626     @Override
627     public StorageNodeType getStorageNodeType() {
628         return StorageNodeType.STATEMENT_LOCAL;
629     }
630
631     @Override
632     public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
633         return parent;
634     }
635
636     @Override
637     public RootStatementContext<?, ?, ?> getRoot() {
638         return parent.getRoot();
639     }
640
641     @Override
642     public EffectiveConfig effectiveConfig() {
643         return effectiveConfig(parent);
644     }
645
646     @Override
647     protected boolean isIgnoringIfFeatures() {
648         return isIgnoringIfFeatures(parent);
649     }
650
651     @Override
652     protected boolean isIgnoringConfig() {
653         return isIgnoringConfig(parent);
654     }
655
656     @Override
657     protected boolean isParentSupportedByFeatures() {
658         return parent.isSupportedByFeatures();
659     }
660 }