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