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