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