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