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