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