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