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