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