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