d26a8e9adfe06e8877ec38113735d8dba1d0ab3c
[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     abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
362
363     abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
364
365     @Override
366     final boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
367         final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
368         if (completeChildren(phase) && finished) {
369             onPhaseCompleted(phase);
370             return true;
371         }
372         return false;
373     }
374
375     private boolean completeChildren(final ModelProcessingPhase phase) {
376         boolean finished = true;
377         for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
378             finished &= child.tryToCompletePhase(phase);
379         }
380         for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
381             finished &= child.tryToCompletePhase(phase);
382         }
383         return finished;
384     }
385
386     private boolean runMutations(final ModelProcessingPhase phase) {
387         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
388         return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
389     }
390
391     private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
392         boolean finished = true;
393         final Iterator<ContextMutation> it = openMutations.iterator();
394         while (it.hasNext()) {
395             final ContextMutation current = it.next();
396             if (current.isFinished()) {
397                 it.remove();
398             } else {
399                 finished = false;
400             }
401         }
402
403         if (openMutations.isEmpty()) {
404             phaseMutation.removeAll(phase);
405             cleanupPhaseMutation();
406         }
407         return finished;
408     }
409
410     private void cleanupPhaseMutation() {
411         if (phaseMutation.isEmpty()) {
412             phaseMutation = ImmutableMultimap.of();
413         }
414     }
415
416     /**
417      * Occurs on end of {@link ModelProcessingPhase} of source parsing.
418      *
419      * @param phase
420      *            that was to be completed (finished)
421      * @throws SourceException
422      *             when an error occurred in source parsing
423      */
424     private void onPhaseCompleted(final ModelProcessingPhase phase) {
425         completedPhase = phase;
426         if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
427             summarizeSubstatementPolicy();
428         }
429
430         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
431         if (!listeners.isEmpty()) {
432             runPhaseListeners(phase, listeners);
433         }
434     }
435
436     private void summarizeSubstatementPolicy() {
437         if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
438             setAllSubstatementsContextIndependent();
439         }
440     }
441
442     /**
443      * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
444      * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
445      * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
446      * considered copy-insensitive.
447      *
448      * <p>
449      * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
450      *
451      * @return True if no substatements require copy-sensitive handling
452      */
453     abstract boolean noSensitiveSubstatements();
454
455     /**
456      * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
457      * {@link #noSensitiveSubstatements()}.
458      *
459      * @param substatements Substatements to check
460      * @return True if no substatements require context-sensitive handling
461      */
462     static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
463         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
464             if (stmt.isSupportedToBuildEffective()) {
465                 if (!stmt.allSubstatementsContextIndependent()) {
466                     // This is a recursive property
467                     return false;
468                 }
469
470                 switch (stmt.definition().support().copyPolicy()) {
471                     case CONTEXT_INDEPENDENT:
472                     case EXACT_REPLICA:
473                     case IGNORE:
474                         break;
475                     default:
476                         return false;
477                 }
478             }
479         }
480         return true;
481     }
482
483     private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
484         final Iterator<OnPhaseFinished> listener = listeners.iterator();
485         while (listener.hasNext()) {
486             final OnPhaseFinished next = listener.next();
487             if (next.phaseFinished(this, phase)) {
488                 listener.remove();
489             }
490         }
491
492         if (listeners.isEmpty()) {
493             phaseListeners.removeAll(phase);
494             if (phaseListeners.isEmpty()) {
495                 phaseListeners = ImmutableMultimap.of();
496             }
497         }
498     }
499
500     /**
501      * Ends declared section of current node.
502      */
503     void endDeclared(final ModelProcessingPhase phase) {
504         definition.onDeclarationFinished(this, phase);
505     }
506
507     @Override
508     final StatementDefinitionContext<A, D, E> definition() {
509         return definition;
510     }
511
512     final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
513             final OnNamespaceItemAdded listener) {
514         final Object potential = getFromNamespace(type, key);
515         if (potential != null) {
516             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
517             listener.namespaceItemAdded(this, type, key, potential);
518             return;
519         }
520
521         getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
522             @Override
523             void onValueAdded(final Object value) {
524                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
525             }
526         });
527     }
528
529     final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
530             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
531             final OnNamespaceItemAdded listener) {
532         final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
533         if (existing.isPresent()) {
534             final Entry<K, V> entry = existing.get();
535             LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
536             waitForPhase(entry.getValue(), type, phase, criterion, listener);
537             return;
538         }
539
540         final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
541         behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
542             @Override
543             boolean onValueAdded(final K key, final V value) {
544                 if (criterion.match(key)) {
545                     LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
546                     waitForPhase(value, type, phase, criterion, listener);
547                     return true;
548                 }
549
550                 return false;
551             }
552         });
553     }
554
555     final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
556             final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
557         final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
558         checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
559             type, this);
560         final Entry<K, V> match = optMatch.get();
561         listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
562     }
563
564     final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
565             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
566             final OnNamespaceItemAdded listener) {
567         ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
568             (context, phaseCompleted) -> {
569                 selectMatch(type, criterion, listener);
570                 return true;
571             });
572     }
573
574     private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
575             final Class<N> type) {
576         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
577         checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
578             type);
579
580         return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
581     }
582
583     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
584         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
585     }
586
587     /**
588      * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
589      * the listener is notified immediately.
590      *
591      * @param phase requested completion phase
592      * @param listener listener to invoke
593      * @throws NullPointerException if any of the arguments is null
594      */
595     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
596         checkNotNull(phase, "Statement context processing phase cannot be null at: %s", sourceReference());
597         checkNotNull(listener, "Statement context phase listener cannot be null at: %s", sourceReference());
598
599         ModelProcessingPhase finishedPhase = completedPhase;
600         while (finishedPhase != null) {
601             if (phase.equals(finishedPhase)) {
602                 listener.phaseFinished(this, finishedPhase);
603                 return;
604             }
605             finishedPhase = finishedPhase.getPreviousPhase();
606         }
607         if (phaseListeners.isEmpty()) {
608             phaseListeners = newMultimap();
609         }
610
611         phaseListeners.put(phase, listener);
612     }
613
614     /**
615      * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
616      *
617      * @throws IllegalStateException when the mutation was registered after phase was completed
618      */
619     final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
620         ModelProcessingPhase finishedPhase = completedPhase;
621         while (finishedPhase != null) {
622             checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
623                 sourceReference());
624             finishedPhase = finishedPhase.getPreviousPhase();
625         }
626
627         if (phaseMutation.isEmpty()) {
628             phaseMutation = newMultimap();
629         }
630         phaseMutation.put(phase, mutation);
631     }
632
633     final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
634         if (!phaseMutation.isEmpty()) {
635             phaseMutation.remove(phase, mutation);
636             cleanupPhaseMutation();
637         }
638     }
639
640     @Override
641     public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
642             final KT key,final StmtContext<?, ?, ?> stmt) {
643         addContextToNamespace(namespace, key, stmt);
644     }
645
646     @Override
647     public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
648             final QNameModule targetModule) {
649         checkEffectiveModelCompleted(this);
650         return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
651     }
652
653     private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
654             final QNameModule targetModule) {
655         final StatementSupport<A, D, E> support = definition.support();
656         final CopyPolicy policy = support.copyPolicy();
657         switch (policy) {
658             case EXACT_REPLICA:
659                 return replicaAsChildOf(parent);
660             case CONTEXT_INDEPENDENT:
661                 if (allSubstatementsContextIndependent()) {
662                     return replicaAsChildOf(parent);
663                 }
664
665                 // fall through
666             case DECLARED_COPY:
667                 // FIXME: ugly cast
668                 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
669             case IGNORE:
670                 return null;
671             case REJECT:
672                 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
673             default:
674                 throw new IllegalStateException("Unhandled policy " + policy);
675         }
676     }
677
678     @Override
679     final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
680             final QNameModule targetModule) {
681         final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
682         if (copy == null) {
683             // The statement fizzled, this should never happen, perhaps a verify()?
684             return null;
685         }
686
687         parent.ensureCompletedPhase(copy);
688         return canReuseCurrent(copy) ? this : copy;
689     }
690
691     private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
692         // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
693         // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
694         return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
695             && allSubstatementsContextIndependent();
696     }
697
698     @Override
699     public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
700             final QNameModule targetModule) {
701         checkEffectiveModelCompleted(stmt);
702         checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
703         return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
704     }
705
706     private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
707             final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
708         final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
709             original.publicDefinition());
710
711         final StatementContextBase<X, Y, Z> result;
712         final InferredStatementContext<X, Y, Z> copy;
713
714         if (implicitParent.isPresent()) {
715             final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
716             result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
717                 original.argument(), type);
718
719             final CopyType childCopyType;
720             switch (type) {
721                 case ADDED_BY_AUGMENTATION:
722                     childCopyType = CopyType.ORIGINAL;
723                     break;
724                 case ADDED_BY_USES_AUGMENTATION:
725                     childCopyType = CopyType.ADDED_BY_USES;
726                     break;
727                 case ADDED_BY_USES:
728                 case ORIGINAL:
729                 default:
730                     childCopyType = type;
731             }
732
733             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
734             result.addEffectiveSubstatement(copy);
735         } else {
736             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
737         }
738
739         original.definition.onStatementAdded(copy);
740         return result;
741     }
742
743     @Override
744     final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
745         return new ReplicaStatementContext<>(parent, this);
746     }
747
748     private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
749         final ModelProcessingPhase phase = stmt.getCompletedPhase();
750         checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
751                 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
752     }
753
754     @Beta
755     public final boolean hasImplicitParentSupport() {
756         return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
757     }
758
759     @Beta
760     public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
761         final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
762             original.publicDefinition());
763         if (optImplicit.isEmpty()) {
764             return original;
765         }
766
767         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
768         final CopyType type = original.history().getLastOperation();
769         final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
770             original.sourceReference(), original.rawArgument(), original.argument(), type);
771
772         result.addEffectiveSubstatement(original.reparent(result));
773         result.setCompletedPhase(original.getCompletedPhase());
774         return result;
775     }
776
777     abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
778
779     /**
780      * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
781      *
782      * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
783      */
784     abstract boolean hasEmptySubstatements();
785 }