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