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