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