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