438c6e6365d87ad367c189b72323bcb47ccdfbf8
[yangtools.git] / parser / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / StatementContextBase.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
15
16 import com.google.common.base.VerifyException;
17 import com.google.common.collect.ImmutableCollection;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableMultimap;
20 import com.google.common.collect.Multimap;
21 import com.google.common.collect.Multimaps;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.EnumMap;
26 import java.util.EventListener;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.stream.Stream;
32 import org.eclipse.jdt.annotation.NonNull;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
36 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.ExecutionOrder;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.UndeclaredStatementFactory;
54 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
55 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
56 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 /**
61  * Core reactor statement implementation of {@link Mutable}.
62  *
63  * @param <A> Argument type
64  * @param <D> Declared Statement representation
65  * @param <E> Effective Statement representation
66  */
67 abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
68         extends ReactorStmtCtx<A, D, E> implements CopyHistory {
69     /**
70      * Event listener when an item is added to model namespace.
71      */
72     interface OnNamespaceItemAdded extends EventListener {
73         /**
74          * Invoked whenever a new item is added to a namespace.
75          */
76         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
77     }
78
79     /**
80      * Event listener when a parsing {@link ModelProcessingPhase} is completed.
81      */
82     interface OnPhaseFinished extends EventListener {
83         /**
84          * Invoked whenever a processing phase has finished.
85          */
86         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
87     }
88
89     /**
90      * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
91      */
92     interface ContextMutation {
93
94         boolean isFinished();
95     }
96
97     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
98
99     // Bottom 4 bits, encoding a CopyHistory, aight?
100     private static final byte COPY_ORIGINAL              = 0x00;
101     private static final byte COPY_LAST_TYPE_MASK        = 0x03;
102     @Deprecated(since = "7.0.9", forRemoval = true)
103     private static final byte COPY_ADDED_BY_USES         = 0x04;
104     private static final byte COPY_ADDED_BY_AUGMENTATION = 0x08;
105
106     // Top four bits, of which we define the topmost two to 0. We use the bottom two to encode last CopyType, aight?
107     private static final int COPY_CHILD_TYPE_SHIFT       = 4;
108
109     private static final CopyType @NonNull [] COPY_TYPE_VALUES = CopyType.values();
110
111     static {
112         final int copyTypes = COPY_TYPE_VALUES.length;
113         // This implies CopyType.ordinal() is <= COPY_TYPE_MASK
114         verify(copyTypes == COPY_LAST_TYPE_MASK + 1, "Unexpected %s CopyType values", copyTypes);
115     }
116
117     /**
118      * 8 bits worth of instance storage. This is treated as a constant bit field with following structure:
119      * <pre>
120      *   <code>
121      * |7|6|5|4|3|2|1|0|
122      * |0 0|cct|a|u|lst|
123      *   </code>
124      * </pre>
125      *
126      * <p>
127      * The four allocated fields are:
128      * <ul>
129      *   <li>{@code lst}, encoding the four states corresponding to {@link CopyHistory#getLastOperation()}</li>
130      *   <li>{@code u}, encoding {@link #isAddedByUses()}</li>
131      *   <li>{@code a}, encoding {@link #isAugmenting()}</li>
132      *   <li>{@code cct} encoding {@link #childCopyType()}</li>
133      * </ul>
134      * We still have two unused bits.
135      */
136     private final byte bitsAight;
137
138     // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
139     //       operations, hence we want to keep it close by.
140     private final @NonNull StatementDefinitionContext<A, D, E> definition;
141
142     // TODO: consider keying by Byte equivalent of ExecutionOrder
143     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
144     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
145
146     private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
147
148     /**
149      * {@link ModelProcessingPhase.ExecutionOrder} value of current {@link ModelProcessingPhase} of this statement.
150      */
151     private byte executionOrder;
152
153     /**
154      * This field should live in AbstractResumedStatement, but is placed here for memory efficiency to squat in the
155      * alignment shadow of {@link #bitsAight} and {@link #executionOrder}.
156      */
157     private boolean implicitDeclaredFlag;
158
159     // TODO: we a single byte of alignment shadow left, we should think how we can use it to cache information we build
160     //       during InferredStatementContext.tryToReusePrototype(). We usually end up being routed to
161     //       copyAsChildOfImpl() -- which performs an eager instantiation and checks for changes afterwards. We should
162     //       be able to capture how parent scope affects the copy in a few bits. If we can do that, than we can reap
163     //       the benefits by just examining new parent context and old parent context contribution to the state. If
164     //       their impact is the same, we can skip instantiation of statements and directly reuse them (individually,
165     //       or as a complete file).
166     //
167     //       Whatever we end up tracking, we need to track two views of that -- for the statement itself
168     //       (sans substatements) and a summary of substatements. I think it should be possible to get this working
169     //       with 2x5bits -- we have up to 15 mutable bits available if we share the field with implicitDeclaredFlag.
170
171     // Copy constructor used by subclasses to implement reparent()
172     StatementContextBase(final StatementContextBase<A, D, E> original) {
173         super(original);
174         this.bitsAight = original.bitsAight;
175         this.definition = original.definition;
176         this.executionOrder = original.executionOrder;
177     }
178
179     StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
180         this.definition = requireNonNull(def);
181         this.bitsAight = COPY_ORIGINAL;
182     }
183
184     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyType copyType) {
185         this.definition = requireNonNull(def);
186         this.bitsAight = (byte) copyFlags(copyType);
187     }
188
189     StatementContextBase(final StatementContextBase<A, D, E> prototype, final CopyType copyType,
190             final CopyType childCopyType) {
191         this.definition = prototype.definition;
192         this.bitsAight = (byte) (copyFlags(copyType)
193             | prototype.bitsAight & ~COPY_LAST_TYPE_MASK | childCopyType.ordinal() << COPY_CHILD_TYPE_SHIFT);
194     }
195
196     private static int copyFlags(final CopyType copyType) {
197         return historyFlags(copyType) | copyType.ordinal();
198     }
199
200     private static byte historyFlags(final CopyType copyType) {
201         switch (copyType) {
202             case ADDED_BY_AUGMENTATION:
203                 return COPY_ADDED_BY_AUGMENTATION;
204             case ADDED_BY_USES:
205                 return COPY_ADDED_BY_USES;
206             case ADDED_BY_USES_AUGMENTATION:
207                 return COPY_ADDED_BY_AUGMENTATION | COPY_ADDED_BY_USES;
208             case ORIGINAL:
209                 return COPY_ORIGINAL;
210             default:
211                 throw new VerifyException("Unhandled type " + copyType);
212         }
213     }
214
215     @Override
216     public final Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
217         return effectOfStatement;
218     }
219
220     @Override
221     public final void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
222         if (ctxs.isEmpty()) {
223             return;
224         }
225
226         if (effectOfStatement.isEmpty()) {
227             effectOfStatement = new ArrayList<>(ctxs.size());
228         }
229         effectOfStatement.addAll(ctxs);
230     }
231
232     //
233     // CopyHistory integration
234     //
235
236     @Override
237     public final CopyHistory history() {
238         return this;
239     }
240
241     @Override
242     @Deprecated(since = "7.0.9", forRemoval = true)
243     public final boolean isAddedByUses() {
244         return (bitsAight & COPY_ADDED_BY_USES) != 0;
245     }
246
247     @Override
248     @Deprecated(since = "8.0.0")
249     public final boolean isAugmenting() {
250         return (bitsAight & COPY_ADDED_BY_AUGMENTATION) != 0;
251     }
252
253     @Override
254     public final CopyType getLastOperation() {
255         return COPY_TYPE_VALUES[bitsAight & COPY_LAST_TYPE_MASK];
256     }
257
258     // This method exists only for space optimization of InferredStatementContext
259     final CopyType childCopyType() {
260         return COPY_TYPE_VALUES[bitsAight >> COPY_CHILD_TYPE_SHIFT & COPY_LAST_TYPE_MASK];
261     }
262
263     //
264     // Inference completion tracking
265     //
266
267     @Override
268     final byte executionOrder() {
269         return executionOrder;
270     }
271
272     // FIXME: this should be propagated through a correct constructor
273     @Deprecated
274     final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
275         this.executionOrder = completedPhase.executionOrder();
276     }
277
278     @Override
279     public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
280             final Class<@NonNull N> type, final T key, final U value) {
281         addToNamespace(type, key, value);
282     }
283
284     static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
285             final List<ReactorStmtCtx<?, ?, ?>> effective) {
286         return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
287     }
288
289     private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
290         return effective.isEmpty() ? ImmutableList.of() : effective;
291     }
292
293     static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
294             final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
295         if (effective.isEmpty()) {
296             return effective;
297         }
298
299         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
300         while (iterator.hasNext()) {
301             final StmtContext<?, ?, ?> next = iterator.next();
302             if (statementDef.equals(next.publicDefinition())) {
303                 iterator.remove();
304             }
305         }
306
307         return shrinkEffective(effective);
308     }
309
310     static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
311             final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
312             final String statementArg) {
313         if (statementArg == null) {
314             return removeStatementFromEffectiveSubstatements(effective, statementDef);
315         }
316
317         if (effective.isEmpty()) {
318             return effective;
319         }
320
321         final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
322         while (iterator.hasNext()) {
323             final Mutable<?, ?, ?> next = iterator.next();
324             if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
325                 iterator.remove();
326             }
327         }
328
329         return shrinkEffective(effective);
330     }
331
332     @Override
333     public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
334             Mutable<X, Y, Z> createUndeclaredSubstatement(final StatementSupport<X, Y, Z> support, final X arg) {
335         requireNonNull(support);
336         checkArgument(support instanceof UndeclaredStatementFactory, "Unsupported statement support %s", support);
337
338         final var ret = new UndeclaredStmtCtx<>(this, support, arg);
339         support.onStatementAdded(ret);
340         return ret;
341     }
342
343     final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
344             final Mutable<?, ?, ?> substatement) {
345         verifyStatement(substatement);
346
347         final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
348         final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
349         ensureCompletedExecution(stmt);
350         resized.add(stmt);
351         return resized;
352     }
353
354     static final void afterAddEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
355         // Undeclared statements still need to have 'onDeclarationFinished()' triggered
356         if (substatement instanceof UndeclaredStmtCtx) {
357             finishDeclaration((UndeclaredStmtCtx<?, ?, ?>) substatement);
358         }
359     }
360
361     // Split out to keep generics working without a warning
362     private static <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> void finishDeclaration(
363             final UndeclaredStmtCtx<X, Y, Z> substatement) {
364         substatement.definition().onDeclarationFinished(substatement, ModelProcessingPhase.FULL_DECLARATION);
365     }
366
367     @Override
368     public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
369         if (!statements.isEmpty()) {
370             statements.forEach(StatementContextBase::verifyStatement);
371             addEffectiveSubstatementsImpl(statements);
372         }
373     }
374
375     abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
376
377     final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
378             final Collection<? extends Mutable<?, ?, ?>> statements) {
379         final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
380         final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
381             (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
382         if (executionOrder != ExecutionOrder.NULL) {
383             for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
384                 ensureCompletedExecution(stmt, executionOrder);
385             }
386         }
387
388         resized.addAll(casted);
389         return resized;
390     }
391
392     abstract Iterator<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
393
394     // exposed for InferredStatementContext only
395     final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
396         verifyStatement(stmt);
397         ensureCompletedExecution((ReactorStmtCtx<?, ?, ?>) stmt);
398     }
399
400     // Make sure target statement has transitioned at least to our phase (if we have one). This method is just before we
401     // take allow a statement to become our substatement. This is needed to ensure that every statement tree does not
402     // contain any statements which did not complete the same phase as the root statement.
403     private void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt) {
404         if (executionOrder != ExecutionOrder.NULL) {
405             ensureCompletedExecution(stmt, executionOrder);
406         }
407     }
408
409     private static void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt, final byte executionOrder) {
410         verify(stmt.tryToCompletePhase(executionOrder), "Statement %s cannot complete phase %s", stmt, executionOrder);
411     }
412
413     private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
414         verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
415     }
416
417     private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
418             final int toAdd) {
419         // We cannot allow statement to be further mutated.
420         // TODO: we really want to say 'not NULL and not at or after EFFECTIVE_MODEL here. This will matter if we have
421         //       a phase after EFFECTIVE_MODEL
422         verify(executionOrder != ExecutionOrder.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
423             sourceReference());
424         return beforeAddEffectiveStatementUnsafe(effective, toAdd);
425     }
426
427     final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
428             final int toAdd) {
429         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
430         checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
431                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
432                 "Effective statement cannot be added in declared phase at: %s", sourceReference());
433
434         return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
435     }
436
437     @Override
438     final E createEffective() {
439         final E result = createEffective(definition.getFactory());
440         if (result instanceof MutableStatement) {
441             getRoot().addMutableStmtToSeal((MutableStatement) result);
442         }
443         return result;
444     }
445
446     abstract @NonNull E createEffective(@NonNull StatementFactory<A, D, E> factory);
447
448     /**
449      * Routing of the request to build an effective statement from {@link InferredStatementContext} towards the original
450      * definition site. This is needed to pick the correct instantiation method: for declared statements we will
451      * eventually land in {@link AbstractResumedStatement}, for underclared statements that will be
452      * {@link UndeclaredStmtCtx}.
453      *
454      * @param factory Statement factory
455      * @param ctx Inferred statement context, i.e. where the effective statement is instantiated
456      * @return Built effective stateue
457      */
458     abstract @NonNull E createInferredEffective(@NonNull StatementFactory<A, D, E> factory,
459         @NonNull InferredStatementContext<A, D, E> ctx);
460
461     /**
462      * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
463      * {@link StmtContext#buildEffective()} contract.
464      *
465      * @return Stream of supported declared statements.
466      */
467     // FIXME: we really want to unify this with streamEffective(), under its name
468     abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared();
469
470     /**
471      * Return a stream of inferred statements which can be built into an {@link EffectiveStatement}, as per
472      * {@link StmtContext#buildEffective()} contract.
473      *
474      * @return Stream of supported effective statements.
475      */
476     // FIXME: this method is currently a misnomer, but unifying with streamDeclared() would make this accurate again
477     abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective();
478
479     @Override
480     final boolean doTryToCompletePhase(final byte targetOrder) {
481         final boolean finished = phaseMutation.isEmpty() || runMutations(targetOrder);
482         if (completeChildren(targetOrder) && finished) {
483             onPhaseCompleted(targetOrder);
484             return true;
485         }
486         return false;
487     }
488
489     private boolean completeChildren(final byte targetOrder) {
490         boolean finished = true;
491         for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
492             finished &= child.tryToCompletePhase(targetOrder);
493         }
494         final var it = effectiveChildrenToComplete();
495         while (it.hasNext()) {
496             finished &= it.next().tryToCompletePhase(targetOrder);
497         }
498         return finished;
499     }
500
501     private boolean runMutations(final byte targetOrder) {
502         final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(targetOrder));
503         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
504         return openMutations.isEmpty() || runMutations(phase, openMutations);
505     }
506
507     private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
508         boolean finished = true;
509         final Iterator<ContextMutation> it = openMutations.iterator();
510         while (it.hasNext()) {
511             final ContextMutation current = it.next();
512             if (current.isFinished()) {
513                 it.remove();
514             } else {
515                 finished = false;
516             }
517         }
518
519         if (openMutations.isEmpty()) {
520             phaseMutation.removeAll(phase);
521             cleanupPhaseMutation();
522         }
523         return finished;
524     }
525
526     private void cleanupPhaseMutation() {
527         if (phaseMutation.isEmpty()) {
528             phaseMutation = ImmutableMultimap.of();
529         }
530     }
531
532     /**
533      * Occurs on end of {@link ModelProcessingPhase} of source parsing. This method must not be called with
534      * {@code executionOrder} equal to {@link ExecutionOrder#NULL}.
535      *
536      * @param phase that was to be completed (finished)
537      * @throws SourceException when an error occurred in source parsing
538      */
539     private void onPhaseCompleted(final byte completedOrder) {
540         executionOrder = completedOrder;
541         if (completedOrder == ExecutionOrder.EFFECTIVE_MODEL) {
542             // We have completed effective model, substatements are guaranteed not to change
543             summarizeSubstatementPolicy();
544         }
545
546         final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(completedOrder));
547         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
548         if (!listeners.isEmpty()) {
549             runPhaseListeners(phase, listeners);
550         }
551     }
552
553     private void summarizeSubstatementPolicy() {
554         if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
555             setAllSubstatementsContextIndependent();
556         }
557     }
558
559     /**
560      * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
561      * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
562      * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
563      * considered copy-insensitive.
564      *
565      * <p>
566      * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
567      *
568      * @return True if no substatements require copy-sensitive handling
569      */
570     abstract boolean noSensitiveSubstatements();
571
572     /**
573      * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
574      * {@link #noSensitiveSubstatements()}.
575      *
576      * @param substatements Substatements to check
577      * @return True if no substatements require context-sensitive handling
578      */
579     static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
580         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
581             if (stmt.isSupportedToBuildEffective()) {
582                 if (!stmt.allSubstatementsContextIndependent()) {
583                     // This is a recursive property
584                     return false;
585                 }
586
587                 switch (stmt.definition().support().copyPolicy()) {
588                     case CONTEXT_INDEPENDENT:
589                     case EXACT_REPLICA:
590                     case IGNORE:
591                         break;
592                     default:
593                         return false;
594                 }
595             }
596         }
597         return true;
598     }
599
600     private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
601         final Iterator<OnPhaseFinished> listener = listeners.iterator();
602         while (listener.hasNext()) {
603             final OnPhaseFinished next = listener.next();
604             if (next.phaseFinished(this, phase)) {
605                 listener.remove();
606             }
607         }
608
609         if (listeners.isEmpty()) {
610             phaseListeners.removeAll(phase);
611             if (phaseListeners.isEmpty()) {
612                 phaseListeners = ImmutableMultimap.of();
613             }
614         }
615     }
616
617     @Override
618     final StatementDefinitionContext<A, D, E> definition() {
619         return definition;
620     }
621
622     final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
623             final OnNamespaceItemAdded listener) {
624         final Object potential = getFromNamespace(type, key);
625         if (potential != null) {
626             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
627             listener.namespaceItemAdded(this, type, key, potential);
628             return;
629         }
630
631         getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
632             @Override
633             void onValueAdded(final Object value) {
634                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
635             }
636         });
637     }
638
639     final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
640             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
641             final OnNamespaceItemAdded listener) {
642         final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
643         if (existing.isPresent()) {
644             final Entry<K, V> entry = existing.get();
645             LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
646             waitForPhase(entry.getValue(), type, phase, criterion, listener);
647             return;
648         }
649
650         final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
651         behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
652             @Override
653             boolean onValueAdded(final K key, final V value) {
654                 if (criterion.match(key)) {
655                     LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
656                     waitForPhase(value, type, phase, criterion, listener);
657                     return true;
658                 }
659
660                 return false;
661             }
662         });
663     }
664
665     final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
666             final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
667         final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
668         checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
669             type, this);
670         final Entry<K, V> match = optMatch.get();
671         listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
672     }
673
674     final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
675             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
676             final OnNamespaceItemAdded listener) {
677         ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
678             (context, phaseCompleted) -> {
679                 selectMatch(type, criterion, listener);
680                 return true;
681             });
682     }
683
684     private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
685             final Class<N> type) {
686         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
687         checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
688             type);
689
690         return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
691     }
692
693     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
694         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
695     }
696
697     /**
698      * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
699      * the listener is notified immediately.
700      *
701      * @param phase requested completion phase
702      * @param listener listener to invoke
703      * @throws NullPointerException if any of the arguments is null
704      */
705     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
706         requireNonNull(phase, "Statement context processing phase cannot be null");
707         requireNonNull(listener, "Statement context phase listener cannot be null");
708
709         ModelProcessingPhase finishedPhase = ModelProcessingPhase.ofExecutionOrder(executionOrder);
710         while (finishedPhase != null) {
711             if (phase.equals(finishedPhase)) {
712                 listener.phaseFinished(this, finishedPhase);
713                 return;
714             }
715             finishedPhase = finishedPhase.getPreviousPhase();
716         }
717         if (phaseListeners.isEmpty()) {
718             phaseListeners = newMultimap();
719         }
720
721         phaseListeners.put(phase, listener);
722     }
723
724     /**
725      * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
726      *
727      * @throws IllegalStateException when the mutation was registered after phase was completed
728      */
729     final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
730         checkState(executionOrder < phase.executionOrder(), "Mutation registered after phase was completed at: %s",
731             sourceReference());
732
733         if (phaseMutation.isEmpty()) {
734             phaseMutation = newMultimap();
735         }
736         phaseMutation.put(phase, mutation);
737     }
738
739     final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
740         if (!phaseMutation.isEmpty()) {
741             phaseMutation.remove(phase, mutation);
742             cleanupPhaseMutation();
743         }
744     }
745
746     @Override
747     public final <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(
748             final Class<@NonNull N> namespace, final KT key,final StmtContext<?, ?, ?> stmt) {
749         addContextToNamespace(namespace, key, stmt);
750     }
751
752     @Override
753     public final Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
754             final QNameModule targetModule) {
755         checkEffectiveModelCompleted(this);
756         return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
757     }
758
759     private @Nullable ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
760             final QNameModule targetModule) {
761         final StatementSupport<A, D, E> support = definition.support();
762         final CopyPolicy policy = support.copyPolicy();
763         switch (policy) {
764             case EXACT_REPLICA:
765                 return replicaAsChildOf(parent);
766             case CONTEXT_INDEPENDENT:
767                 if (allSubstatementsContextIndependent()) {
768                     return replicaAsChildOf(parent);
769                 }
770
771                 // fall through
772             case DECLARED_COPY:
773                 // FIXME: ugly cast
774                 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
775             case IGNORE:
776                 return null;
777             case REJECT:
778                 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
779             default:
780                 throw new IllegalStateException("Unhandled policy " + policy);
781         }
782     }
783
784     @Override
785     final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
786             final QNameModule targetModule) {
787         final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
788         if (copy == null) {
789             // The statement fizzled, this should never happen, perhaps a verify()?
790             return null;
791         }
792
793         parent.ensureCompletedPhase(copy);
794         return canReuseCurrent(copy) ? this : copy;
795     }
796
797     private boolean canReuseCurrent(final @NonNull ReactorStmtCtx<A, D, E> copy) {
798         // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
799         // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
800         return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
801             && allSubstatementsContextIndependent();
802     }
803
804     @Override
805     public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
806             final QNameModule targetModule) {
807         checkEffectiveModelCompleted(stmt);
808         if (stmt instanceof StatementContextBase) {
809             return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
810         } else if (stmt instanceof ReplicaStatementContext) {
811             return ((ReplicaStatementContext<?, ?, ?>) stmt).replicaAsChildOf(this);
812         } else {
813             throw new IllegalArgumentException("Unsupported statement " + stmt);
814         }
815     }
816
817     private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
818             final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
819         final var implicitParent = definition.getImplicitParentFor(this, original.publicDefinition());
820
821         final StatementContextBase<X, Y, Z> result;
822         final InferredStatementContext<X, Y, Z> copy;
823
824         if (implicitParent.isPresent()) {
825             result = new UndeclaredStmtCtx(this, implicitParent.orElseThrow(), original, type);
826
827             final CopyType childCopyType;
828             switch (type) {
829                 case ADDED_BY_AUGMENTATION:
830                     childCopyType = CopyType.ORIGINAL;
831                     break;
832                 case ADDED_BY_USES_AUGMENTATION:
833                     childCopyType = CopyType.ADDED_BY_USES;
834                     break;
835                 case ADDED_BY_USES:
836                 case ORIGINAL:
837                 default:
838                     childCopyType = type;
839             }
840
841             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
842             result.addEffectiveSubstatement(copy);
843         } else {
844             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
845         }
846
847         original.definition.onStatementAdded(copy);
848         return result;
849     }
850
851     @Override
852     final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
853         return new ReplicaStatementContext<>(parent, this);
854     }
855
856     private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
857         final ModelProcessingPhase phase = stmt.getCompletedPhase();
858         checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
859                 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
860     }
861
862     @Override
863     public final boolean hasImplicitParentSupport() {
864         return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
865     }
866
867     @Override
868     public final StmtContext<?, ?, ?> wrapWithImplicit(final StmtContext<?, ?, ?> original) {
869         final var optImplicit = definition.getImplicitParentFor(this, original.publicDefinition());
870         if (optImplicit.isEmpty()) {
871             return original;
872         }
873
874         checkArgument(original instanceof StatementContextBase, "Unsupported original %s", original);
875         final var origBase = (StatementContextBase<?, ?, ?>)original;
876
877         @SuppressWarnings({ "rawtypes", "unchecked" })
878         final UndeclaredStmtCtx<?, ?, ?> result = new UndeclaredStmtCtx(origBase, optImplicit.orElseThrow());
879         result.addEffectiveSubstatement(origBase.reparent(result));
880         result.setCompletedPhase(original.getCompletedPhase());
881         return result;
882     }
883
884     abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
885
886     /**
887      * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
888      *
889      * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
890      */
891     abstract boolean hasEmptySubstatements();
892
893     // Note: these two are exposed for AbstractResumedStatement only
894     final boolean getImplicitDeclaredFlag() {
895         return implicitDeclaredFlag;
896     }
897
898     final void setImplicitDeclaredFlag() {
899         implicitDeclaredFlag = true;
900     }
901 }