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