8375a46705c93cadd3a1c3cf66743511848243f6
[yangtools.git] / parser / 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.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
15
16 import com.google.common.base.VerifyException;
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.opendaylight.yangtools.yang.common.QNameModule;
34 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
35 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.ExecutionOrder;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
53 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
54 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
55 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * Core reactor statement implementation of {@link Mutable}.
61  *
62  * @param <A> Argument type
63  * @param <D> Declared Statement representation
64  * @param <E> Effective Statement representation
65  */
66 abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
67         extends ReactorStmtCtx<A, D, E> implements CopyHistory {
68     /**
69      * Event listener when an item is added to model namespace.
70      */
71     interface OnNamespaceItemAdded extends EventListener {
72         /**
73          * Invoked whenever a new item is added to a namespace.
74          */
75         void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
76     }
77
78     /**
79      * Event listener when a parsing {@link ModelProcessingPhase} is completed.
80      */
81     interface OnPhaseFinished extends EventListener {
82         /**
83          * Invoked whenever a processing phase has finished.
84          */
85         boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
86     }
87
88     /**
89      * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
90      */
91     interface ContextMutation {
92
93         boolean isFinished();
94     }
95
96     private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
97
98     // Bottom 4 bits, encoding a CopyHistory, aight?
99     private static final byte COPY_ORIGINAL              = 0x00;
100     private static final byte COPY_LAST_TYPE_MASK        = 0x03;
101     @Deprecated(since = "7.0.9", forRemoval = true)
102     private static final byte COPY_ADDED_BY_USES         = 0x04;
103     private static final byte COPY_ADDED_BY_AUGMENTATION = 0x08;
104
105     // Top four bits, of which we define the topmost two to 0. We use the bottom two to encode last CopyType, aight?
106     private static final int COPY_CHILD_TYPE_SHIFT       = 4;
107
108     private static final CopyType @NonNull [] COPY_TYPE_VALUES = CopyType.values();
109
110     static {
111         final int copyTypes = COPY_TYPE_VALUES.length;
112         // This implies CopyType.ordinal() is <= COPY_TYPE_MASK
113         verify(copyTypes == COPY_LAST_TYPE_MASK + 1, "Unexpected %s CopyType values", copyTypes);
114     }
115
116     /**
117      * 8 bits worth of instance storage. This is treated as a constant bit field with following structure:
118      * <pre>
119      *   <code>
120      * |7|6|5|4|3|2|1|0|
121      * |0 0|cct|a|u|lst|
122      *   </code>
123      * </pre>
124      *
125      * <p>
126      * The four allocated fields are:
127      * <ul>
128      *   <li>{@code lst}, encoding the four states corresponding to {@link CopyHistory#getLastOperation()}</li>
129      *   <li>{@code u}, encoding {@link #isAddedByUses()}</li>
130      *   <li>{@code a}, encoding {@link #isAugmenting()}</li>
131      *   <li>{@code cct} encoding {@link #childCopyType()}</li>
132      * </ul>
133      * We still have two unused bits.
134      */
135     private final byte bitsAight;
136
137     // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
138     //       operations, hence we want to keep it close by.
139     private final @NonNull StatementDefinitionContext<A, D, E> definition;
140
141     // TODO: consider keying by Byte equivalent of ExecutionOrder
142     private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
143     private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
144
145     private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
146
147     /**
148      * {@link ModelProcessingPhase.ExecutionOrder} value of current {@link ModelProcessingPhase} of this statement.
149      */
150     private byte executionOrder;
151
152     // Copy constructor used by subclasses to implement reparent()
153     StatementContextBase(final StatementContextBase<A, D, E> original) {
154         super(original);
155         this.bitsAight = original.bitsAight;
156         this.definition = original.definition;
157         this.executionOrder = original.executionOrder;
158     }
159
160     StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
161         this.definition = requireNonNull(def);
162         this.bitsAight = COPY_ORIGINAL;
163     }
164
165     StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyType copyType) {
166         this.definition = requireNonNull(def);
167         this.bitsAight = (byte) copyFlags(copyType);
168     }
169
170     StatementContextBase(final StatementContextBase<A, D, E> prototype, final CopyType copyType,
171             final CopyType childCopyType) {
172         this.definition = prototype.definition;
173         this.bitsAight = (byte) (copyFlags(copyType)
174             | prototype.bitsAight & ~COPY_LAST_TYPE_MASK | childCopyType.ordinal() << COPY_CHILD_TYPE_SHIFT);
175     }
176
177     private static int copyFlags(final CopyType copyType) {
178         return historyFlags(copyType) | copyType.ordinal();
179     }
180
181     private static byte historyFlags(final CopyType copyType) {
182         switch (copyType) {
183             case ADDED_BY_AUGMENTATION:
184                 return COPY_ADDED_BY_AUGMENTATION;
185             case ADDED_BY_USES:
186                 return COPY_ADDED_BY_USES;
187             case ADDED_BY_USES_AUGMENTATION:
188                 return COPY_ADDED_BY_AUGMENTATION | COPY_ADDED_BY_USES;
189             case ORIGINAL:
190                 return COPY_ORIGINAL;
191             default:
192                 throw new VerifyException("Unhandled type " + copyType);
193         }
194     }
195
196     @Override
197     public final Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
198         return effectOfStatement;
199     }
200
201     @Override
202     public final void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
203         if (ctxs.isEmpty()) {
204             return;
205         }
206
207         if (effectOfStatement.isEmpty()) {
208             effectOfStatement = new ArrayList<>(ctxs.size());
209         }
210         effectOfStatement.addAll(ctxs);
211     }
212
213     //
214     // CopyHistory integration
215     //
216
217     @Override
218     public final CopyHistory history() {
219         return this;
220     }
221
222     @Override
223     @Deprecated(since = "7.0.9", forRemoval = true)
224     public final boolean isAddedByUses() {
225         return (bitsAight & COPY_ADDED_BY_USES) != 0;
226     }
227
228     @Override
229     @Deprecated(since = "8.0.0")
230     public final boolean isAugmenting() {
231         return (bitsAight & COPY_ADDED_BY_AUGMENTATION) != 0;
232     }
233
234     @Override
235     public final CopyType getLastOperation() {
236         return COPY_TYPE_VALUES[bitsAight & COPY_LAST_TYPE_MASK];
237     }
238
239     // This method exists only for space optimization of InferredStatementContext
240     final CopyType childCopyType() {
241         return COPY_TYPE_VALUES[bitsAight >> COPY_CHILD_TYPE_SHIFT & COPY_LAST_TYPE_MASK];
242     }
243
244     //
245     // Inference completion tracking
246     //
247
248     @Override
249     final byte executionOrder() {
250         return executionOrder;
251     }
252
253     // FIXME: this should be propagated through a correct constructor
254     @Deprecated
255     final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
256         this.executionOrder = completedPhase.executionOrder();
257     }
258
259     @Override
260     public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
261             final Class<@NonNull N> type, final T key, final U value) {
262         addToNamespace(type, key, value);
263     }
264
265     static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
266             final List<ReactorStmtCtx<?, ?, ?>> effective) {
267         return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
268     }
269
270     private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
271         return effective.isEmpty() ? ImmutableList.of() : effective;
272     }
273
274     static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
275             final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
276         if (effective.isEmpty()) {
277             return effective;
278         }
279
280         final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
281         while (iterator.hasNext()) {
282             final StmtContext<?, ?, ?> next = iterator.next();
283             if (statementDef.equals(next.publicDefinition())) {
284                 iterator.remove();
285             }
286         }
287
288         return shrinkEffective(effective);
289     }
290
291     static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
292             final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
293             final String statementArg) {
294         if (statementArg == null) {
295             return removeStatementFromEffectiveSubstatements(effective, statementDef);
296         }
297
298         if (effective.isEmpty()) {
299             return effective;
300         }
301
302         final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
303         while (iterator.hasNext()) {
304             final Mutable<?, ?, ?> next = iterator.next();
305             if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
306                 iterator.remove();
307             }
308         }
309
310         return shrinkEffective(effective);
311     }
312
313     @Override
314     public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
315             Mutable<X, Y, Z> addEffectiveSubstatement(final StatementSupport<X, Y, Z> support, final X arg) {
316         // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
317         //                       StatementContextBase subclass.
318         final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
319                 ImplicitSubstatement.of(sourceReference()), arg);
320         support.onStatementAdded(ret);
321         addEffectiveSubstatement(ret);
322         return ret;
323     }
324
325     final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
326             final Mutable<?, ?, ?> substatement) {
327         verifyStatement(substatement);
328
329         final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
330         final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
331         ensureCompletedExecution(stmt);
332         resized.add(stmt);
333         return resized;
334     }
335
336     @Override
337     public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
338         if (!statements.isEmpty()) {
339             statements.forEach(StatementContextBase::verifyStatement);
340             addEffectiveSubstatementsImpl(statements);
341         }
342     }
343
344     abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
345
346     final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
347             final Collection<? extends Mutable<?, ?, ?>> statements) {
348         final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
349         final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
350             (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
351         if (executionOrder != ExecutionOrder.NULL) {
352             for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
353                 ensureCompletedExecution(stmt, executionOrder);
354             }
355         }
356
357         resized.addAll(casted);
358         return resized;
359     }
360
361     abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
362
363     // exposed for InferredStatementContext only
364     final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
365         verifyStatement(stmt);
366         ensureCompletedExecution((ReactorStmtCtx<?, ?, ?>) stmt);
367     }
368
369     // Make sure target statement has transitioned at least to our phase (if we have one). This method is just before we
370     // take allow a statement to become our substatement. This is needed to ensure that every statement tree does not
371     // contain any statements which did not complete the same phase as the root statement.
372     private void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt) {
373         if (executionOrder != ExecutionOrder.NULL) {
374             ensureCompletedExecution(stmt, executionOrder);
375         }
376     }
377
378     private static void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt, final byte executionOrder) {
379         verify(stmt.tryToCompletePhase(executionOrder), "Statement %s cannot complete phase %s", stmt, executionOrder);
380     }
381
382     private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
383         verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
384     }
385
386     private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
387             final int toAdd) {
388         // We cannot allow statement to be further mutated.
389         // TODO: we really want to say 'not NULL and not at or after EFFECTIVE_MODEL here. This will matter if we have
390         //       a phase after EFFECTIVE_MODEL
391         verify(executionOrder != ExecutionOrder.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
392             sourceReference());
393         return beforeAddEffectiveStatementUnsafe(effective, toAdd);
394     }
395
396     final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
397             final int toAdd) {
398         final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
399         checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
400                 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
401                 "Effective statement cannot be added in declared phase at: %s", sourceReference());
402
403         return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
404     }
405
406     @Override
407     final E createEffective() {
408         final E result = createEffective(definition.getFactory());
409         if (result instanceof MutableStatement) {
410             getRoot().addMutableStmtToSeal((MutableStatement) result);
411         }
412         return result;
413     }
414
415     @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
416         return createEffective(factory, this);
417     }
418
419     // Creates EffectiveStatement through full materialization
420     static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
421             final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
422         return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
423     }
424
425     /**
426      * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
427      * {@link StmtContext#buildEffective()} contract.
428      *
429      * @return Stream of supported declared statements.
430      */
431     // FIXME: we really want to unify this with streamEffective(), under its name
432     abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared();
433
434     /**
435      * Return a stream of inferred statements which can be built into an {@link EffectiveStatement}, as per
436      * {@link StmtContext#buildEffective()} contract.
437      *
438      * @return Stream of supported effective statements.
439      */
440     // FIXME: this method is currently a misnomer, but unifying with streamDeclared() would make this accurate again
441     abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective();
442
443     @Override
444     final boolean doTryToCompletePhase(final byte targetOrder) {
445         final boolean finished = phaseMutation.isEmpty() || runMutations(targetOrder);
446         if (completeChildren(targetOrder) && finished) {
447             onPhaseCompleted(targetOrder);
448             return true;
449         }
450         return false;
451     }
452
453     private boolean completeChildren(final byte targetOrder) {
454         boolean finished = true;
455         for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
456             finished &= child.tryToCompletePhase(targetOrder);
457         }
458         for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
459             finished &= child.tryToCompletePhase(targetOrder);
460         }
461         return finished;
462     }
463
464     private boolean runMutations(final byte targetOrder) {
465         final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(targetOrder));
466         final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
467         return openMutations.isEmpty() || runMutations(phase, openMutations);
468     }
469
470     private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
471         boolean finished = true;
472         final Iterator<ContextMutation> it = openMutations.iterator();
473         while (it.hasNext()) {
474             final ContextMutation current = it.next();
475             if (current.isFinished()) {
476                 it.remove();
477             } else {
478                 finished = false;
479             }
480         }
481
482         if (openMutations.isEmpty()) {
483             phaseMutation.removeAll(phase);
484             cleanupPhaseMutation();
485         }
486         return finished;
487     }
488
489     private void cleanupPhaseMutation() {
490         if (phaseMutation.isEmpty()) {
491             phaseMutation = ImmutableMultimap.of();
492         }
493     }
494
495     /**
496      * Occurs on end of {@link ModelProcessingPhase} of source parsing. This method must not be called with
497      * {@code executionOrder} equal to {@link ExecutionOrder#NULL}.
498      *
499      * @param phase that was to be completed (finished)
500      * @throws SourceException when an error occurred in source parsing
501      */
502     private void onPhaseCompleted(final byte completedOrder) {
503         executionOrder = completedOrder;
504         if (completedOrder == ExecutionOrder.EFFECTIVE_MODEL) {
505             // We have completed effective model, substatements are guaranteed not to change
506             summarizeSubstatementPolicy();
507         }
508
509         final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(completedOrder));
510         final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
511         if (!listeners.isEmpty()) {
512             runPhaseListeners(phase, listeners);
513         }
514     }
515
516     private void summarizeSubstatementPolicy() {
517         if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
518             setAllSubstatementsContextIndependent();
519         }
520     }
521
522     /**
523      * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
524      * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
525      * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
526      * considered copy-insensitive.
527      *
528      * <p>
529      * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
530      *
531      * @return True if no substatements require copy-sensitive handling
532      */
533     abstract boolean noSensitiveSubstatements();
534
535     /**
536      * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
537      * {@link #noSensitiveSubstatements()}.
538      *
539      * @param substatements Substatements to check
540      * @return True if no substatements require context-sensitive handling
541      */
542     static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
543         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
544             if (stmt.isSupportedToBuildEffective()) {
545                 if (!stmt.allSubstatementsContextIndependent()) {
546                     // This is a recursive property
547                     return false;
548                 }
549
550                 switch (stmt.definition().support().copyPolicy()) {
551                     case CONTEXT_INDEPENDENT:
552                     case EXACT_REPLICA:
553                     case IGNORE:
554                         break;
555                     default:
556                         return false;
557                 }
558             }
559         }
560         return true;
561     }
562
563     private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
564         final Iterator<OnPhaseFinished> listener = listeners.iterator();
565         while (listener.hasNext()) {
566             final OnPhaseFinished next = listener.next();
567             if (next.phaseFinished(this, phase)) {
568                 listener.remove();
569             }
570         }
571
572         if (listeners.isEmpty()) {
573             phaseListeners.removeAll(phase);
574             if (phaseListeners.isEmpty()) {
575                 phaseListeners = ImmutableMultimap.of();
576             }
577         }
578     }
579
580     @Override
581     final StatementDefinitionContext<A, D, E> definition() {
582         return definition;
583     }
584
585     final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
586             final OnNamespaceItemAdded listener) {
587         final Object potential = getFromNamespace(type, key);
588         if (potential != null) {
589             LOG.trace("Listener on {} key {} satisfied immediately", type, key);
590             listener.namespaceItemAdded(this, type, key, potential);
591             return;
592         }
593
594         getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
595             @Override
596             void onValueAdded(final Object value) {
597                 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
598             }
599         });
600     }
601
602     final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
603             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
604             final OnNamespaceItemAdded listener) {
605         final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
606         if (existing.isPresent()) {
607             final Entry<K, V> entry = existing.get();
608             LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
609             waitForPhase(entry.getValue(), type, phase, criterion, listener);
610             return;
611         }
612
613         final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
614         behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
615             @Override
616             boolean onValueAdded(final K key, final V value) {
617                 if (criterion.match(key)) {
618                     LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
619                     waitForPhase(value, type, phase, criterion, listener);
620                     return true;
621                 }
622
623                 return false;
624             }
625         });
626     }
627
628     final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
629             final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
630         final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
631         checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
632             type, this);
633         final Entry<K, V> match = optMatch.get();
634         listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
635     }
636
637     final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
638             final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
639             final OnNamespaceItemAdded listener) {
640         ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
641             (context, phaseCompleted) -> {
642                 selectMatch(type, criterion, listener);
643                 return true;
644             });
645     }
646
647     private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
648             final Class<N> type) {
649         final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
650         checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
651             type);
652
653         return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
654     }
655
656     private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
657         return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
658     }
659
660     /**
661      * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
662      * the listener is notified immediately.
663      *
664      * @param phase requested completion phase
665      * @param listener listener to invoke
666      * @throws NullPointerException if any of the arguments is null
667      */
668     void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
669         requireNonNull(phase, "Statement context processing phase cannot be null");
670         requireNonNull(listener, "Statement context phase listener cannot be null");
671
672         ModelProcessingPhase finishedPhase = ModelProcessingPhase.ofExecutionOrder(executionOrder);
673         while (finishedPhase != null) {
674             if (phase.equals(finishedPhase)) {
675                 listener.phaseFinished(this, finishedPhase);
676                 return;
677             }
678             finishedPhase = finishedPhase.getPreviousPhase();
679         }
680         if (phaseListeners.isEmpty()) {
681             phaseListeners = newMultimap();
682         }
683
684         phaseListeners.put(phase, listener);
685     }
686
687     /**
688      * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
689      *
690      * @throws IllegalStateException when the mutation was registered after phase was completed
691      */
692     final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
693         checkState(executionOrder < phase.executionOrder(), "Mutation registered after phase was completed at: %s",
694             sourceReference());
695
696         if (phaseMutation.isEmpty()) {
697             phaseMutation = newMultimap();
698         }
699         phaseMutation.put(phase, mutation);
700     }
701
702     final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
703         if (!phaseMutation.isEmpty()) {
704             phaseMutation.remove(phase, mutation);
705             cleanupPhaseMutation();
706         }
707     }
708
709     @Override
710     public final <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(
711             final Class<@NonNull N> namespace, final KT key,final StmtContext<?, ?, ?> stmt) {
712         addContextToNamespace(namespace, key, stmt);
713     }
714
715     @Override
716     public final Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
717             final QNameModule targetModule) {
718         checkEffectiveModelCompleted(this);
719         return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
720     }
721
722     private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
723             final QNameModule targetModule) {
724         final StatementSupport<A, D, E> support = definition.support();
725         final CopyPolicy policy = support.copyPolicy();
726         switch (policy) {
727             case EXACT_REPLICA:
728                 return replicaAsChildOf(parent);
729             case CONTEXT_INDEPENDENT:
730                 if (allSubstatementsContextIndependent()) {
731                     return replicaAsChildOf(parent);
732                 }
733
734                 // fall through
735             case DECLARED_COPY:
736                 // FIXME: ugly cast
737                 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
738             case IGNORE:
739                 return null;
740             case REJECT:
741                 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
742             default:
743                 throw new IllegalStateException("Unhandled policy " + policy);
744         }
745     }
746
747     @Override
748     final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
749             final QNameModule targetModule) {
750         final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
751         if (copy == null) {
752             // The statement fizzled, this should never happen, perhaps a verify()?
753             return null;
754         }
755
756         parent.ensureCompletedPhase(copy);
757         return canReuseCurrent(copy) ? this : copy;
758     }
759
760     private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
761         // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
762         // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
763         return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
764             && allSubstatementsContextIndependent();
765     }
766
767     @Override
768     public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
769             final QNameModule targetModule) {
770         checkEffectiveModelCompleted(stmt);
771         if (stmt instanceof StatementContextBase) {
772             return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
773         } else if (stmt instanceof ReplicaStatementContext) {
774             return ((ReplicaStatementContext<?, ?, ?>) stmt).replicaAsChildOf(this);
775         } else {
776             throw new IllegalArgumentException("Unsupported statement " + stmt);
777         }
778     }
779
780     private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
781             final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
782         final var implicitParent = definition.getImplicitParentFor(this, original.publicDefinition());
783
784         final StatementContextBase<X, Y, Z> result;
785         final InferredStatementContext<X, Y, Z> copy;
786
787         if (implicitParent.isPresent()) {
788             final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
789             result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
790                 original.argument(), type);
791
792             final CopyType childCopyType;
793             switch (type) {
794                 case ADDED_BY_AUGMENTATION:
795                     childCopyType = CopyType.ORIGINAL;
796                     break;
797                 case ADDED_BY_USES_AUGMENTATION:
798                     childCopyType = CopyType.ADDED_BY_USES;
799                     break;
800                 case ADDED_BY_USES:
801                 case ORIGINAL:
802                 default:
803                     childCopyType = type;
804             }
805
806             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
807             result.addEffectiveSubstatement(copy);
808         } else {
809             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
810         }
811
812         original.definition.onStatementAdded(copy);
813         return result;
814     }
815
816     @Override
817     final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
818         return new ReplicaStatementContext<>(parent, this);
819     }
820
821     private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
822         final ModelProcessingPhase phase = stmt.getCompletedPhase();
823         checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
824                 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
825     }
826
827     @Override
828     public final boolean hasImplicitParentSupport() {
829         return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
830     }
831
832     @Override
833     public final StmtContext<?, ?, ?> wrapWithImplicit(final StmtContext<?, ?, ?> original) {
834         final var optImplicit = definition.getImplicitParentFor(this, original.publicDefinition());
835         if (optImplicit.isEmpty()) {
836             return original;
837         }
838
839         final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.orElseThrow());
840         final CopyType type = original.history().getLastOperation();
841
842         checkArgument(original instanceof StatementContextBase, "Unsupported original %s", original);
843         final var origBase = (StatementContextBase<?, ?, ?>)original;
844
845         @SuppressWarnings({ "rawtypes", "unchecked"})
846         final SubstatementContext<?, ?, ?> result = new SubstatementContext(origBase.getParentContext(), def,
847             original.sourceReference(), original.rawArgument(), original.argument(), type);
848
849         result.addEffectiveSubstatement(origBase.reparent(result));
850         result.setCompletedPhase(original.getCompletedPhase());
851         return result;
852     }
853
854     abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
855
856     /**
857      * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
858      *
859      * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
860      */
861     abstract boolean hasEmptySubstatements();
862 }