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