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