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