c11ef99baf9ddffa5dcb58b30a6836a98f8c4615
[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.annotations.Beta;
17 import com.google.common.base.VerifyException;
18 import com.google.common.collect.ImmutableCollection;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMultimap;
21 import com.google.common.collect.Multimap;
22 import com.google.common.collect.Multimaps;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.EnumMap;
27 import java.util.EventListener;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32 import java.util.stream.Stream;
33 import org.eclipse.jdt.annotation.NonNull;
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.source.ImplicitSubstatement;
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 public 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     // Copy constructor used by subclasses to implement reparent()
154     StatementContextBase(final StatementContextBase<A, D, E> original) {
155         super(original);
156         this.bitsAight = original.bitsAight;
157         this.definition = original.definition;
158         this.executionOrder = original.executionOrder;
159     }
160
161     StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
162         this.definition = requireNonNull(def);
163         this.bitsAight = COPY_ORIGINAL;
164     }
165
166     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyType copyType) {
167         this.definition = requireNonNull(def);
168         this.bitsAight = (byte) copyFlags(copyType);
169     }
170
171     StatementContextBase(final StatementContextBase<A, D, E> prototype, final CopyType copyType,
172             final CopyType childCopyType) {
173         this.definition = prototype.definition;
174         this.bitsAight = (byte) (copyFlags(copyType)
175             | prototype.bitsAight & ~COPY_LAST_TYPE_MASK | childCopyType.ordinal() << COPY_CHILD_TYPE_SHIFT);
176     }
177
178     private static int copyFlags(final CopyType copyType) {
179         return historyFlags(copyType) | copyType.ordinal();
180     }
181
182     private static byte historyFlags(final CopyType copyType) {
183         switch (copyType) {
184             case ADDED_BY_AUGMENTATION:
185                 return COPY_ADDED_BY_AUGMENTATION;
186             case ADDED_BY_USES:
187                 return COPY_ADDED_BY_USES;
188             case ADDED_BY_USES_AUGMENTATION:
189                 return COPY_ADDED_BY_AUGMENTATION | COPY_ADDED_BY_USES;
190             case ORIGINAL:
191                 return COPY_ORIGINAL;
192             default:
193                 throw new VerifyException("Unhandled type " + copyType);
194         }
195     }
196
197     @Override
198     public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
199         return effectOfStatement;
200     }
201
202     @Override
203     public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
204         if (ctxs.isEmpty()) {
205             return;
206         }
207
208         if (effectOfStatement.isEmpty()) {
209             effectOfStatement = new ArrayList<>(ctxs.size());
210         }
211         effectOfStatement.addAll(ctxs);
212     }
213
214     //
215     // CopyHistory integration
216     //
217
218     @Override
219     public final CopyHistory history() {
220         return this;
221     }
222
223     @Override
224     @Deprecated(since = "7.0.9", forRemoval = true)
225     public final boolean isAddedByUses() {
226         return (bitsAight & COPY_ADDED_BY_USES) != 0;
227     }
228
229     @Override
230     @Deprecated(since = "8.0.0")
231     public final boolean isAugmenting() {
232         return (bitsAight & COPY_ADDED_BY_AUGMENTATION) != 0;
233     }
234
235     @Override
236     public final CopyType getLastOperation() {
237         return COPY_TYPE_VALUES[bitsAight & COPY_LAST_TYPE_MASK];
238     }
239
240     // This method exists only for space optimization of InferredStatementContext
241     final CopyType childCopyType() {
242         return COPY_TYPE_VALUES[bitsAight >> COPY_CHILD_TYPE_SHIFT & COPY_LAST_TYPE_MASK];
243     }
244
245     //
246     // Inference completion tracking
247     //
248
249     @Override
250     final byte executionOrder() {
251         return executionOrder;
252     }
253
254     // FIXME: this should be propagated through a correct constructor
255     @Deprecated
256     final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
257         this.executionOrder = completedPhase.executionOrder();
258     }
259
260     @Override
261     public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
262             final Class<@NonNull N> type, final T key, final U value) {
263         addToNamespace(type, key, value);
264     }
265
266     static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
267             final List<ReactorStmtCtx<?, ?, ?>> effective) {
268         return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
269     }
270
271     private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
272         return effective.isEmpty() ? ImmutableList.of() : effective;
273     }
274
275     public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
276
277     static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
278             final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
279         if (effective.isEmpty()) {
280             return effective;
281         }
282
283         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
284         while (iterator.hasNext()) {
285             final StmtContext<?, ?, ?> next = iterator.next();
286             if (statementDef.equals(next.publicDefinition())) {
287                 iterator.remove();
288             }
289         }
290
291         return shrinkEffective(effective);
292     }
293
294     /**
295      * Removes a statement context from the effective substatements based on its statement definition (i.e statement
296      * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
297      * definition and statement argument match with one of the effective substatements' statement definition
298      * and argument.
299      *
300      * <p>
301      * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
302      *
303      * @param statementDef statement definition of the statement context to remove
304      * @param statementArg statement argument of the statement context to remove
305      */
306     public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
307             String statementArg);
308
309     static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
310             final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
311             final String statementArg) {
312         if (statementArg == null) {
313             return removeStatementFromEffectiveSubstatements(effective, statementDef);
314         }
315
316         if (effective.isEmpty()) {
317             return effective;
318         }
319
320         final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
321         while (iterator.hasNext()) {
322             final Mutable<?, ?, ?> next = iterator.next();
323             if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
324                 iterator.remove();
325             }
326         }
327
328         return shrinkEffective(effective);
329     }
330
331     // YANG example: RPC/action statements always have 'input' and 'output' defined
332     @Beta
333     public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
334             appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
335         // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
336         //                       StatementContextBase subclass.
337         final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
338                 ImplicitSubstatement.of(sourceReference()), rawArg);
339         support.onStatementAdded(ret);
340         addEffectiveSubstatement(ret);
341         return ret;
342     }
343
344     /**
345      * Adds an effective statement to collection of substatements.
346      *
347      * @param substatement substatement
348      * @throws IllegalStateException if added in declared phase
349      * @throws NullPointerException if statement parameter is null
350      */
351     public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
352
353     final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
354             final Mutable<?, ?, ?> substatement) {
355         verifyStatement(substatement);
356
357         final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
358         final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
359         ensureCompletedExecution(stmt);
360         resized.add(stmt);
361         return resized;
362     }
363
364     /**
365      * Adds an effective statement to collection of substatements.
366      *
367      * @param statements substatements
368      * @throws IllegalStateException
369      *             if added in declared phase
370      * @throws NullPointerException
371      *             if statement parameter is null
372      */
373     public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
374         if (!statements.isEmpty()) {
375             statements.forEach(StatementContextBase::verifyStatement);
376             addEffectiveSubstatementsImpl(statements);
377         }
378     }
379
380     abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
381
382     final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
383             final Collection<? extends Mutable<?, ?, ?>> statements) {
384         final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
385         final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
386             (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
387         if (executionOrder != ExecutionOrder.NULL) {
388             for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
389                 ensureCompletedExecution(stmt, executionOrder);
390             }
391         }
392
393         resized.addAll(casted);
394         return resized;
395     }
396
397     abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
398
399     // exposed for InferredStatementContext only
400     final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
401         verifyStatement(stmt);
402         ensureCompletedExecution((ReactorStmtCtx<?, ?, ?>) stmt);
403     }
404
405     // Make sure target statement has transitioned at least to our phase (if we have one). This method is just before we
406     // take allow a statement to become our substatement. This is needed to ensure that every statement tree does not
407     // contain any statements which did not complete the same phase as the root statement.
408     private void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt) {
409         if (executionOrder != ExecutionOrder.NULL) {
410             ensureCompletedExecution(stmt, executionOrder);
411         }
412     }
413
414     private static void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt, final byte executionOrder) {
415         verify(stmt.tryToCompletePhase(executionOrder), "Statement %s cannot complete phase %s", stmt, executionOrder);
416     }
417
418     private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
419         verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
420     }
421
422     private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
423             final int toAdd) {
424         // We cannot allow statement to be further mutated.
425         // TODO: we really want to say 'not NULL and not at or after EFFECTIVE_MODEL here. This will matter if we have
426         //       a phase after EFFECTIVE_MODEL
427         verify(executionOrder != ExecutionOrder.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
428             sourceReference());
429         return beforeAddEffectiveStatementUnsafe(effective, toAdd);
430     }
431
432     final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
433             final int toAdd) {
434         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
435         checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
436                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
437                 "Effective statement cannot be added in declared phase at: %s", sourceReference());
438
439         return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
440     }
441
442     @Override
443     final E createEffective() {
444         final E result = createEffective(definition.getFactory());
445         if (result instanceof MutableStatement) {
446             getRoot().addMutableStmtToSeal((MutableStatement) result);
447         }
448         return result;
449     }
450
451     @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
452         return createEffective(factory, this);
453     }
454
455     // Creates EffectiveStatement through full materialization
456     static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
457             final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
458         return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
459     }
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         for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
495             finished &= child.tryToCompletePhase(targetOrder);
496         }
497         return finished;
498     }
499
500     private boolean runMutations(final byte targetOrder) {
501         final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(targetOrder));
502         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
503         return openMutations.isEmpty() || runMutations(phase, openMutations);
504     }
505
506     private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
507         boolean finished = true;
508         final Iterator<ContextMutation> it = openMutations.iterator();
509         while (it.hasNext()) {
510             final ContextMutation current = it.next();
511             if (current.isFinished()) {
512                 it.remove();
513             } else {
514                 finished = false;
515             }
516         }
517
518         if (openMutations.isEmpty()) {
519             phaseMutation.removeAll(phase);
520             cleanupPhaseMutation();
521         }
522         return finished;
523     }
524
525     private void cleanupPhaseMutation() {
526         if (phaseMutation.isEmpty()) {
527             phaseMutation = ImmutableMultimap.of();
528         }
529     }
530
531     /**
532      * Occurs on end of {@link ModelProcessingPhase} of source parsing. This method must not be called with
533      * {@code executionOrder} equal to {@link ExecutionOrder#NULL}.
534      *
535      * @param phase that was to be completed (finished)
536      * @throws SourceException when an error occurred in source parsing
537      */
538     private void onPhaseCompleted(final byte completedOrder) {
539         executionOrder = completedOrder;
540         if (completedOrder == ExecutionOrder.EFFECTIVE_MODEL) {
541             // We have completed effective model, substatements are guaranteed not to change
542             summarizeSubstatementPolicy();
543         }
544
545         final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(completedOrder));
546         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
547         if (!listeners.isEmpty()) {
548             runPhaseListeners(phase, listeners);
549         }
550     }
551
552     private void summarizeSubstatementPolicy() {
553         if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
554             setAllSubstatementsContextIndependent();
555         }
556     }
557
558     /**
559      * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
560      * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
561      * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
562      * considered copy-insensitive.
563      *
564      * <p>
565      * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
566      *
567      * @return True if no substatements require copy-sensitive handling
568      */
569     abstract boolean noSensitiveSubstatements();
570
571     /**
572      * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
573      * {@link #noSensitiveSubstatements()}.
574      *
575      * @param substatements Substatements to check
576      * @return True if no substatements require context-sensitive handling
577      */
578     static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
579         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
580             if (stmt.isSupportedToBuildEffective()) {
581                 if (!stmt.allSubstatementsContextIndependent()) {
582                     // This is a recursive property
583                     return false;
584                 }
585
586                 switch (stmt.definition().support().copyPolicy()) {
587                     case CONTEXT_INDEPENDENT:
588                     case EXACT_REPLICA:
589                     case IGNORE:
590                         break;
591                     default:
592                         return false;
593                 }
594             }
595         }
596         return true;
597     }
598
599     private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
600         final Iterator<OnPhaseFinished> listener = listeners.iterator();
601         while (listener.hasNext()) {
602             final OnPhaseFinished next = listener.next();
603             if (next.phaseFinished(this, phase)) {
604                 listener.remove();
605             }
606         }
607
608         if (listeners.isEmpty()) {
609             phaseListeners.removeAll(phase);
610             if (phaseListeners.isEmpty()) {
611                 phaseListeners = ImmutableMultimap.of();
612             }
613         }
614     }
615
616     /**
617      * Ends declared section of current node.
618      */
619     void endDeclared(final ModelProcessingPhase phase) {
620         definition.onDeclarationFinished(this, phase);
621     }
622
623     @Override
624     final StatementDefinitionContext<A, D, E> definition() {
625         return definition;
626     }
627
628     final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
629             final OnNamespaceItemAdded listener) {
630         final Object potential = getFromNamespace(type, key);
631         if (potential != null) {
632             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
633             listener.namespaceItemAdded(this, type, key, potential);
634             return;
635         }
636
637         getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
638             @Override
639             void onValueAdded(final Object value) {
640                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
641             }
642         });
643     }
644
645     final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
646             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
647             final OnNamespaceItemAdded listener) {
648         final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
649         if (existing.isPresent()) {
650             final Entry<K, V> entry = existing.get();
651             LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
652             waitForPhase(entry.getValue(), type, phase, criterion, listener);
653             return;
654         }
655
656         final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
657         behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
658             @Override
659             boolean onValueAdded(final K key, final V value) {
660                 if (criterion.match(key)) {
661                     LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
662                     waitForPhase(value, type, phase, criterion, listener);
663                     return true;
664                 }
665
666                 return false;
667             }
668         });
669     }
670
671     final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
672             final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
673         final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
674         checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
675             type, this);
676         final Entry<K, V> match = optMatch.get();
677         listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
678     }
679
680     final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
681             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
682             final OnNamespaceItemAdded listener) {
683         ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
684             (context, phaseCompleted) -> {
685                 selectMatch(type, criterion, listener);
686                 return true;
687             });
688     }
689
690     private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
691             final Class<N> type) {
692         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
693         checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
694             type);
695
696         return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
697     }
698
699     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
700         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
701     }
702
703     /**
704      * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
705      * the listener is notified immediately.
706      *
707      * @param phase requested completion phase
708      * @param listener listener to invoke
709      * @throws NullPointerException if any of the arguments is null
710      */
711     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
712         requireNonNull(phase, "Statement context processing phase cannot be null");
713         requireNonNull(listener, "Statement context phase listener cannot be null");
714
715         ModelProcessingPhase finishedPhase = ModelProcessingPhase.ofExecutionOrder(executionOrder);
716         while (finishedPhase != null) {
717             if (phase.equals(finishedPhase)) {
718                 listener.phaseFinished(this, finishedPhase);
719                 return;
720             }
721             finishedPhase = finishedPhase.getPreviousPhase();
722         }
723         if (phaseListeners.isEmpty()) {
724             phaseListeners = newMultimap();
725         }
726
727         phaseListeners.put(phase, listener);
728     }
729
730     /**
731      * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
732      *
733      * @throws IllegalStateException when the mutation was registered after phase was completed
734      */
735     final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
736         checkState(executionOrder < phase.executionOrder(), "Mutation registered after phase was completed at: %s",
737             sourceReference());
738
739         if (phaseMutation.isEmpty()) {
740             phaseMutation = newMultimap();
741         }
742         phaseMutation.put(phase, mutation);
743     }
744
745     final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
746         if (!phaseMutation.isEmpty()) {
747             phaseMutation.remove(phase, mutation);
748             cleanupPhaseMutation();
749         }
750     }
751
752     @Override
753     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
754             final KT key,final StmtContext<?, ?, ?> stmt) {
755         addContextToNamespace(namespace, key, stmt);
756     }
757
758     @Override
759     public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
760             final QNameModule targetModule) {
761         checkEffectiveModelCompleted(this);
762         return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
763     }
764
765     private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
766             final QNameModule targetModule) {
767         final StatementSupport<A, D, E> support = definition.support();
768         final CopyPolicy policy = support.copyPolicy();
769         switch (policy) {
770             case EXACT_REPLICA:
771                 return replicaAsChildOf(parent);
772             case CONTEXT_INDEPENDENT:
773                 if (allSubstatementsContextIndependent()) {
774                     return replicaAsChildOf(parent);
775                 }
776
777                 // fall through
778             case DECLARED_COPY:
779                 // FIXME: ugly cast
780                 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
781             case IGNORE:
782                 return null;
783             case REJECT:
784                 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
785             default:
786                 throw new IllegalStateException("Unhandled policy " + policy);
787         }
788     }
789
790     @Override
791     final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
792             final QNameModule targetModule) {
793         final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
794         if (copy == null) {
795             // The statement fizzled, this should never happen, perhaps a verify()?
796             return null;
797         }
798
799         parent.ensureCompletedPhase(copy);
800         return canReuseCurrent(copy) ? this : copy;
801     }
802
803     private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
804         // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
805         // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
806         return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
807             && allSubstatementsContextIndependent();
808     }
809
810     @Override
811     public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
812             final QNameModule targetModule) {
813         checkEffectiveModelCompleted(stmt);
814         if (stmt instanceof StatementContextBase) {
815             return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
816         } else if (stmt instanceof ReplicaStatementContext) {
817             return ((ReplicaStatementContext<?, ?, ?>) stmt).replicaAsChildOf(this);
818         } else {
819             throw new IllegalArgumentException("Unsupported statement " + stmt);
820         }
821     }
822
823     private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
824             final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
825         final var implicitParent = definition.getImplicitParentFor(this, original.publicDefinition());
826
827         final StatementContextBase<X, Y, Z> result;
828         final InferredStatementContext<X, Y, Z> copy;
829
830         if (implicitParent.isPresent()) {
831             final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
832             result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
833                 original.argument(), type);
834
835             final CopyType childCopyType;
836             switch (type) {
837                 case ADDED_BY_AUGMENTATION:
838                     childCopyType = CopyType.ORIGINAL;
839                     break;
840                 case ADDED_BY_USES_AUGMENTATION:
841                     childCopyType = CopyType.ADDED_BY_USES;
842                     break;
843                 case ADDED_BY_USES:
844                 case ORIGINAL:
845                 default:
846                     childCopyType = type;
847             }
848
849             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
850             result.addEffectiveSubstatement(copy);
851         } else {
852             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
853         }
854
855         original.definition.onStatementAdded(copy);
856         return result;
857     }
858
859     @Override
860     final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
861         return new ReplicaStatementContext<>(parent, this);
862     }
863
864     private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
865         final ModelProcessingPhase phase = stmt.getCompletedPhase();
866         checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
867                 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
868     }
869
870     @Beta
871     // FIXME: this information should be exposed as a well-known Namespace
872     public final boolean hasImplicitParentSupport() {
873         return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
874     }
875
876     @Beta
877     public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
878         final var optImplicit = definition.getImplicitParentFor(this, original.publicDefinition());
879         if (optImplicit.isEmpty()) {
880             return original;
881         }
882
883         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.orElseThrow());
884         final CopyType type = original.history().getLastOperation();
885         final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
886             original.sourceReference(), original.rawArgument(), original.argument(), type);
887
888         result.addEffectiveSubstatement(original.reparent(result));
889         result.setCompletedPhase(original.getCompletedPhase());
890         return result;
891     }
892
893     abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
894
895     /**
896      * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
897      *
898      * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
899      */
900     abstract boolean hasEmptySubstatements();
901 }