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