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