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