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