Expose Iterator from effectiveChildrenToComplete()
[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) : super.createEffective(factory);
215     }
216
217     private @NonNull E tryToReusePrototype(final StatementFactory<A, D, E> factory) {
218         final E origEffective = prototype.buildEffective();
219         final Collection<? extends @NonNull EffectiveStatement<?, ?>> origSubstatements =
220             origEffective.effectiveSubstatements();
221
222         // First check if we can reuse the entire prototype
223         if (!factory.canReuseCurrent(this, prototype, origSubstatements)) {
224             return internAlongCopyAxis(factory, tryToReuseSubstatements(factory, origEffective));
225         }
226
227         // We can reuse this statement let's see if all statements agree...
228         // ... no substatements to deal with, we can freely reuse the original
229         if (origSubstatements.isEmpty()) {
230             LOG.debug("Reusing empty: {}", origEffective);
231             substatements = ImmutableList.of();
232             prototype.decRef();
233             return origEffective;
234         }
235
236         // ... all are context independent, reuse the original
237         if (allSubstatementsContextIndependent()) {
238             LOG.debug("Reusing context-independent: {}", origEffective);
239             substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
240             prototype.decRef();
241             return origEffective;
242         }
243
244         // ... copy-sensitive check
245         final List<EffectiveCopy> declCopy = prototype.streamDeclared()
246             .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
247             .filter(Objects::nonNull)
248             .collect(Collectors.toUnmodifiableList());
249         final List<EffectiveCopy> effCopy = prototype.streamEffective()
250             .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
251             .filter(Objects::nonNull)
252             .collect(Collectors.toUnmodifiableList());
253
254         // ... are any copy-sensitive?
255         if (allReused(declCopy) && allReused(effCopy)) {
256             LOG.debug("Reusing after substatement check: {}", origEffective);
257             substatements = noRefs() ? REUSED_SUBSTATEMENTS
258                 : reusePrototypeReplicas(Streams.concat(declCopy.stream(), effCopy.stream())
259                     .map(copy -> copy.toReusedChild(this)));
260             prototype.decRef();
261             return origEffective;
262         }
263
264         // *sigh*, ok, heavy lifting through a shallow copy
265         final List<ReactorStmtCtx<?, ?, ?>> declared = declCopy.stream()
266             .map(copy -> copy.toChildContext(this))
267             .collect(ImmutableList.toImmutableList());
268         final List<ReactorStmtCtx<?, ?, ?>> effective = effCopy.stream()
269             .map(copy -> copy.toChildContext(this))
270             .collect(ImmutableList.toImmutableList());
271         substatements = declared.isEmpty() ? effective
272             : Streams.concat(declared.stream(), effective.stream()).collect(ImmutableList.toImmutableList());
273         prototype.decRef();
274
275         // Values are the effective copies, hence this efficiently deals with recursion.
276         return internAlongCopyAxis(factory, factory.createEffective(this, declared.stream(), effective.stream()));
277     }
278
279     private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory, final @NonNull E original) {
280         if (allSubstatementsContextIndependent()) {
281             LOG.debug("Reusing substatements of: {}", prototype);
282             substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
283             prototype.decRef();
284             return factory.copyEffective(this, original);
285         }
286
287         // Fall back to full instantiation, which populates our substatements. Then check if we should be reusing
288         // the substatement list, as this operation turned out to not affect them.
289         final E effective = super.createEffective(factory);
290         // Since we have forced instantiation to deal with this case, we also need to reset the 'modified' flag
291         setUnmodified();
292
293         if (sameSubstatements(original.effectiveSubstatements(), effective)) {
294             LOG.debug("Reusing unchanged substatements of: {}", prototype);
295             return factory.copyEffective(this, original);
296         }
297         return effective;
298     }
299
300     private @NonNull E internAlongCopyAxis(final StatementFactory<A, D, E> factory, final @NonNull E stmt) {
301         if (!isModified()) {
302             final EffectiveStatementState state = factory.extractEffectiveState(stmt);
303             if (state != null) {
304                 return prototype.unmodifiedEffectiveSource().attachEffectiveCopy(state, stmt);
305             }
306         }
307         return stmt;
308     }
309
310     private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas() {
311         return reusePrototypeReplicas(Streams.concat(prototype.streamDeclared(), prototype.streamEffective()));
312     }
313
314     private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<StmtContext<?, ?, ?>> stream) {
315         return stream
316             .map(stmt -> {
317                 final ReplicaStatementContext<?, ?, ?> ret = ((ReactorStmtCtx<?, ?, ?>) stmt).replicaAsChildOf(this);
318                 ret.buildEffective();
319                 return ret;
320             })
321             .collect(Collectors.toUnmodifiableList());
322     }
323
324     private static boolean sameSubstatements(final Collection<?> original, final EffectiveStatement<?, ?> effective) {
325         final Collection<?> copied = effective.effectiveSubstatements();
326         if (copied != effective.effectiveSubstatements() || original.size() != copied.size()) {
327             // Do not bother if result is treating substatements as transient
328             return false;
329         }
330
331         final Iterator<?> oit = original.iterator();
332         final Iterator<?> cit = copied.iterator();
333         while (oit.hasNext()) {
334             verify(cit.hasNext());
335             // Identity comparison on purpose to side-step whatever equality there might be. We want to reuse instances
336             // after all.
337             if (oit.next() != cit.next()) {
338                 return false;
339             }
340         }
341         verify(!cit.hasNext());
342         return true;
343     }
344
345     private static boolean allReused(final List<EffectiveCopy> entries) {
346         return entries.stream().allMatch(EffectiveCopy::isReused);
347     }
348
349     @Override
350     ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource() {
351         return isModified() ? this : prototype.unmodifiedEffectiveSource();
352     }
353
354     @Override
355     boolean hasEmptySubstatements() {
356         if (substatements == null) {
357             return prototype.hasEmptySubstatements();
358         }
359         return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty();
360     }
361
362     @Override
363     boolean noSensitiveSubstatements() {
364         accessSubstatements();
365         if (substatements == null) {
366             // No difference, defer to prototype
367             return prototype.allSubstatementsContextIndependent();
368         }
369         if (substatements instanceof List) {
370             // Fully materialized, walk all statements
371             return noSensitiveSubstatements(castEffective(substatements));
372         }
373
374         // Partially-materialized. This case has three distinct outcomes:
375         // - prototype does not have a sensitive statement (1)
376         // - protype has a sensitive substatement, and
377         //   - we have not marked is as unsupported (2)
378         //   - we have marked it as unsupported (3)
379         //
380         // Determining the outcome between (2) and (3) is a bother, this check errs on the side of false negative side
381         // and treats (3) as (2) -- i.e. even if we marked a sensitive statement as unsupported, we still consider it
382         // as affecting the result.
383         return prototype.allSubstatementsContextIndependent()
384             && noSensitiveSubstatements(castMaterialized(substatements).values());
385     }
386
387     @Override
388     <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
389             final @NonNull Class<Z> type) {
390         if (substatements instanceof List) {
391             return super.findSubstatementArgumentImpl(type);
392         }
393
394         final Optional<X> templateArg = prototype.findSubstatementArgument(type);
395         if (templateArg.isEmpty()) {
396             return templateArg;
397         }
398         if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
399             // X is known to be QName
400             return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
401         }
402         return templateArg;
403     }
404
405     @Override
406     boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
407         return substatements instanceof List ? super.hasSubstatementImpl(type)
408             // We do not allow deletion of partially-materialized statements, hence this is accurate
409             : prototype.hasSubstatement(type);
410     }
411
412     @Override
413     public <Y extends DeclaredStatement<QName>, Z extends SchemaTreeEffectiveStatement<Y>>
414             StmtContext<QName, Y, Z> requestSchemaTreeChild(final QName qname) {
415         if (substatements instanceof List) {
416             // We have performed materialization, hence we have triggered creation of all our schema tree child
417             // statements.
418             return null;
419         }
420
421         final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype));
422         LOG.debug("Materializing child {} from {}", qname, templateQName);
423
424         final StmtContext<?, ?, ?> template;
425         if (prototype instanceof InferredStatementContext) {
426             // Note: we need to access namespace here, as the target statement may have already been populated, in which
427             //       case we want to obtain the statement in local namespace storage.
428             template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(
429                 SchemaTreeNamespace.class, templateQName);
430         } else {
431             template = prototype.allSubstatementsStream()
432                 .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
433                     && templateQName.equals(stmt.argument()))
434                 .findAny()
435                 .orElse(null);
436         }
437
438         if (template == null) {
439             // We do not have a template, this child does not exist. It may be added later, but that is someone else's
440             // responsibility.
441             LOG.debug("Child {} does not have a template", qname);
442             return null;
443         }
444
445         @SuppressWarnings("unchecked")
446         final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
447             .orElseThrow(
448                 () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
449         ensureCompletedPhase(ret);
450         addMaterialized(template, ret);
451
452         LOG.debug("Child {} materialized", qname);
453         return ret;
454     }
455
456     // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
457     // BuildGlobalContext, hence it must be called at most once.
458     private List<ReactorStmtCtx<?, ?, ?>> ensureEffectiveSubstatements() {
459         accessSubstatements();
460         return substatements instanceof List ? castEffective(substatements)
461             : initializeSubstatements(castMaterialized(substatements));
462     }
463
464     @Override
465     Iterator<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() {
466         // When we have not initialized, there are no statements to catch up: we will catch up when we are copying
467         // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL).
468         if (substatements == null) {
469             return Collections.emptyIterator();
470         }
471         accessSubstatements();
472         if (substatements instanceof HashMap) {
473             return castMaterialized(substatements).values().iterator();
474         } else {
475             return castEffective(substatements).iterator();
476         }
477     }
478
479     @Override
480     Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared() {
481         return Stream.empty();
482     }
483
484     @Override
485     Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective() {
486         return ensureEffectiveSubstatements().stream().filter(StmtContext::isSupportedToBuildEffective);
487     }
488
489     private void accessSubstatements() {
490         if (substatements instanceof String) {
491             throw new VerifyException("Access to " + substatements + " substatements of " + this);
492         }
493     }
494
495     @Override
496     void markNoParentRef() {
497         final Object local = substatements;
498         if (local != null) {
499             markNoParentRef(castEffective(local));
500         }
501     }
502
503     @Override
504     int sweepSubstatements() {
505         final Object local = substatements;
506         substatements = SWEPT_SUBSTATEMENTS;
507         int count = 0;
508         if (local instanceof List) {
509             final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local);
510             sweep(list);
511             count = countUnswept(list);
512         }
513         return count;
514     }
515
516     private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements(
517             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
518         final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
519         final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
520
521         final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
522         for (final Mutable<?, ?, ?> stmtContext : declared) {
523             if (stmtContext.isSupportedByFeatures()) {
524                 copySubstatement(stmtContext, buffer, materializedSchemaTree);
525             }
526         }
527         for (final Mutable<?, ?, ?> stmtContext : effective) {
528             copySubstatement(stmtContext, buffer, materializedSchemaTree);
529         }
530
531         final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
532         ret.addAll((Collection) buffer);
533         substatements = ret;
534         setModified();
535
536         prototype.decRef();
537         return ret;
538     }
539
540     //
541     // Statement copy mess starts here. As it turns out, it's not that much of a mess, but it does make your head spin
542     // sometimes. Tread softly because you tread on my dreams.
543     //
544
545     private EffectiveCopy effectiveCopy(final ReactorStmtCtx<?, ?, ?> stmt) {
546         final ReactorStmtCtx<?, ?, ?> effective = stmt.asEffectiveChildOf(this, childCopyType(), targetModule);
547         return effective == null ? null : new EffectiveCopy(stmt, effective);
548     }
549
550     private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
551             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
552         // Consult materialized substatements. We are in a copy operation and will end up throwing materialized
553         // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
554         //
555         // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
556         // against parent would change -- and we certainly do not want that to happen.
557         final ReactorStmtCtx<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
558         if (materialized == null) {
559             copySubstatement(substatement).ifPresent(copy -> {
560                 ensureCompletedPhase(copy);
561                 buffer.add(copy);
562             });
563         } else {
564             buffer.add(materialized);
565         }
566     }
567
568     private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
569         return substatement.copyAsChildOf(this, childCopyType(), targetModule);
570     }
571
572     private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
573         final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree;
574         if (substatements == null) {
575             // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
576             // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
577             // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
578             // resizing operation.
579             materializedSchemaTree = new HashMap<>(4);
580             substatements = materializedSchemaTree;
581             setModified();
582         } else {
583             verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
584             materializedSchemaTree = castMaterialized(substatements);
585         }
586
587         final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
588             (StatementContextBase<?, ?, ?>) copy);
589         if (existing != null) {
590             throw new VerifyException(
591                 "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
592         }
593     }
594
595     private static @Nullable ReactorStmtCtx<?, ?, ?> findMaterialized(
596             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree,
597             final StmtContext<?, ?, ?> template) {
598         return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
599     }
600
601     @SuppressWarnings("unchecked")
602     private static List<ReactorStmtCtx<?, ?, ?>> castEffective(final Object substatements) {
603         return (List<ReactorStmtCtx<?, ?, ?>>) substatements;
604     }
605
606     @SuppressWarnings("unchecked")
607     private static HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> castMaterialized(final Object substatements) {
608         return (HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>>) substatements;
609     }
610
611     // Statement copy mess ends here
612
613     /*
614      * KEEP THINGS ORGANIZED!
615      *
616      * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
617      * properly updated there.
618      */
619     @Override
620     public A argument() {
621         return argument;
622     }
623
624     @Override
625     public StatementContextBase<?, ?, ?> getParentContext() {
626         return parent;
627     }
628
629     @Override
630     public StorageNodeType getStorageNodeType() {
631         return StorageNodeType.STATEMENT_LOCAL;
632     }
633
634     @Override
635     public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
636         return parent;
637     }
638
639     @Override
640     public RootStatementContext<?, ?, ?> getRoot() {
641         return parent.getRoot();
642     }
643
644     @Override
645     public EffectiveConfig effectiveConfig() {
646         return effectiveConfig(parent);
647     }
648
649     @Override
650     protected boolean isIgnoringIfFeatures() {
651         return isIgnoringIfFeatures(parent);
652     }
653
654     @Override
655     protected boolean isIgnoringConfig() {
656         return isIgnoringConfig(parent);
657     }
658
659     @Override
660     protected boolean isParentSupportedByFeatures() {
661         return parent.isSupportedByFeatures();
662     }
663 }