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