Remost StatementContextBase.schemaPath()
[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 CopyHistory getCopyHistory() {
153         return copyHistory;
154     }
155
156     @Override
157     public 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<StatementContextBase<?, ?, ?>> effective) {
175         return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
176     }
177
178     private static List<StatementContextBase<?, ?, ?>> shrinkEffective(
179             final List<StatementContextBase<?, ?, ?>> effective) {
180         return effective.isEmpty() ? ImmutableList.of() : effective;
181     }
182
183     public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
184
185     static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
186             final List<StatementContextBase<?, ?, ?>> 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<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
218             final List<StatementContextBase<?, ?, ?>> 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<StatementContextBase<?, ?, ?>> 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<StatementContextBase<?, ?, ?>> addEffectiveSubstatement(
262             final List<StatementContextBase<?, ?, ?>> effective, final Mutable<?, ?, ?> substatement) {
263         verifyStatement(substatement);
264
265         final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
266         final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) 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<StatementContextBase<?, ?, ?>> addEffectiveSubstatementsImpl(
294             final List<StatementContextBase<?, ?, ?>> effective,
295             final Collection<? extends Mutable<?, ?, ?>> statements) {
296         final List<StatementContextBase<?, ?, ?>> 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<StatementContextBase<?, ?, ?>> 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((StatementContextBase<?, ?, ?>) 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 StatementContextBase<?, ?, ?> stmt,
325             final ModelProcessingPhase phase) {
326         verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
327     }
328
329     private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
330         verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
331     }
332
333     private List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatement(
334             final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
335         // We cannot allow statement to be further mutated
336         verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
337             sourceReference());
338         return beforeAddEffectiveStatementUnsafe(effective, toAdd);
339     }
340
341     final List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatementUnsafe(
342             final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
343         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
344         checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
345                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
346                 "Effective statement cannot be added in declared phase at: %s", sourceReference());
347
348         return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
349     }
350
351     // Exposed for ReplicaStatementContext
352     @Override
353     E createEffective() {
354         return definition.getFactory().createEffective(new BaseCurrentEffectiveStmtCtx<>(this), streamDeclared(),
355             streamEffective());
356     }
357
358     abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
359
360     abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
361
362     /**
363      * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
364      * this method does nothing.
365      *
366      * @param phase to be executed (completed)
367      * @return true if phase was successfully completed
368      * @throws SourceException when an error occurred in source parsing
369      */
370     final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
371         return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
372     }
373
374     private 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 StatementContextBase<?, ?, ?> 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 IdentifierNamespace<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 IdentifierNamespace<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 IdentifierNamespace<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 IdentifierNamespace<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 IdentifierNamespace<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
609         final StatementSupport<A, D, E> support = definition.support();
610         final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
611         switch (policy) {
612             case CONTEXT_INDEPENDENT:
613                 if (hasEmptySubstatements()) {
614                     // This statement is context-independent and has no substatements -- hence it can be freely shared.
615                     return Optional.of(replicaAsChildOf(parent));
616                 }
617                 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
618                 // fall through
619             case DECLARED_COPY:
620                 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
621                 //                       context, so that we can support building an effective statement without copying
622                 //                       anything -- we will typically end up not being inferred against. In that case,
623                 //                       this slim context should end up dealing with differences at buildContext()
624                 //                       time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
625                 //                       cannot be shared across instances).
626                 return Optional.of(parent.childCopyOf(this, type, targetModule));
627             case IGNORE:
628                 return Optional.empty();
629             case REJECT:
630                 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
631             default:
632                 throw new IllegalStateException("Unhandled policy " + policy);
633         }
634     }
635
636     @Override
637     public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
638             final QNameModule targetModule) {
639         checkEffectiveModelCompleted(stmt);
640         checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
641         return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
642     }
643
644     private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
645             final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
646         final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
647             original.publicDefinition());
648
649         final StatementContextBase<X, Y, Z> result;
650         final InferredStatementContext<X, Y, Z> copy;
651
652         if (implicitParent.isPresent()) {
653             final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
654             result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
655                 original.argument(), type);
656
657             final CopyType childCopyType;
658             switch (type) {
659                 case ADDED_BY_AUGMENTATION:
660                     childCopyType = CopyType.ORIGINAL;
661                     break;
662                 case ADDED_BY_USES_AUGMENTATION:
663                     childCopyType = CopyType.ADDED_BY_USES;
664                     break;
665                 case ADDED_BY_USES:
666                 case ORIGINAL:
667                 default:
668                     childCopyType = type;
669             }
670
671             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
672             result.addEffectiveSubstatement(copy);
673         } else {
674             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
675         }
676
677         original.definition.onStatementAdded(copy);
678         return result;
679     }
680
681     @Override
682     public final StatementContextBase<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
683         checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
684         return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
685     }
686
687     final @NonNull StatementContextBase<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> stmt) {
688         return new ReplicaStatementContext<>(stmt, this);
689     }
690
691     private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
692         final ModelProcessingPhase phase = stmt.getCompletedPhase();
693         checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
694                 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
695     }
696
697     @Beta
698     public final boolean hasImplicitParentSupport() {
699         return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
700     }
701
702     @Beta
703     public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
704         final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
705             original.publicDefinition());
706         if (optImplicit.isEmpty()) {
707             return original;
708         }
709
710         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
711         final CopyType type = original.getCopyHistory().getLastOperation();
712         final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
713             original.sourceReference(), original.rawArgument(), original.argument(), type);
714
715         result.addEffectiveSubstatement(original.reparent(result));
716         result.setCompletedPhase(original.getCompletedPhase());
717         return result;
718     }
719
720     abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
721
722     /**
723      * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
724      *
725      * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
726      */
727     abstract boolean hasEmptySubstatements();
728 }