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