2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
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;
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;
61 * Core reactor statement implementation of {@link Mutable}.
63 * @param <A> Argument type
64 * @param <D> Declared Statement representation
65 * @param <E> Effective Statement representation
67 abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
68 extends ReactorStmtCtx<A, D, E> implements CopyHistory {
70 * Event listener when an item is added to model namespace.
72 interface OnNamespaceItemAdded extends EventListener {
74 * Invoked whenever a new item is added to a namespace.
76 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
80 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
82 interface OnPhaseFinished extends EventListener {
84 * Invoked whenever a processing phase has finished.
86 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
90 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
92 interface ContextMutation {
97 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
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;
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;
109 private static final CopyType @NonNull [] COPY_TYPE_VALUES = CopyType.values();
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);
118 * 8 bits worth of instance storage. This is treated as a constant bit field with following structure:
127 * The four allocated fields are:
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>
134 * We still have two unused bits.
136 private final byte bitsAight;
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;
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();
146 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
149 * {@link ModelProcessingPhase.ExecutionOrder} value of current {@link ModelProcessingPhase} of this statement.
151 private byte executionOrder;
154 * This field should live in AbstractResumedStatement, but is placed here for memory efficiency to squat in the
155 * alignment shadow of {@link #bitsAight} and {@link #executionOrder}.
157 private boolean implicitDeclaredFlag;
159 // TODO: we a single byte of alignment shadow left, we should think how we can use it to cache information we build
160 // during InferredStatementContext.tryToReusePrototype(). We usually end up being routed to
161 // copyAsChildOfImpl() -- which performs an eager instantiation and checks for changes afterwards. We should
162 // be able to capture how parent scope affects the copy in a few bits. If we can do that, than we can reap
163 // the benefits by just examining new parent context and old parent context contribution to the state. If
164 // their impact is the same, we can skip instantiation of statements and directly reuse them (individually,
165 // or as a complete file).
167 // Whatever we end up tracking, we need to track two views of that -- for the statement itself
168 // (sans substatements) and a summary of substatements. I think it should be possible to get this working
169 // with 2x5bits -- we have up to 15 mutable bits available if we share the field with implicitDeclaredFlag.
171 // Copy constructor used by subclasses to implement reparent()
172 StatementContextBase(final StatementContextBase<A, D, E> original) {
174 this.bitsAight = original.bitsAight;
175 this.definition = original.definition;
176 this.executionOrder = original.executionOrder;
179 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
180 this.definition = requireNonNull(def);
181 this.bitsAight = COPY_ORIGINAL;
184 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyType copyType) {
185 this.definition = requireNonNull(def);
186 this.bitsAight = (byte) copyFlags(copyType);
189 StatementContextBase(final StatementContextBase<A, D, E> prototype, final CopyType copyType,
190 final CopyType childCopyType) {
191 this.definition = prototype.definition;
192 this.bitsAight = (byte) (copyFlags(copyType)
193 | prototype.bitsAight & ~COPY_LAST_TYPE_MASK | childCopyType.ordinal() << COPY_CHILD_TYPE_SHIFT);
196 private static int copyFlags(final CopyType copyType) {
197 return historyFlags(copyType) | copyType.ordinal();
200 private static byte historyFlags(final CopyType copyType) {
202 case ADDED_BY_AUGMENTATION:
203 return COPY_ADDED_BY_AUGMENTATION;
205 return COPY_ADDED_BY_USES;
206 case ADDED_BY_USES_AUGMENTATION:
207 return COPY_ADDED_BY_AUGMENTATION | COPY_ADDED_BY_USES;
209 return COPY_ORIGINAL;
211 throw new VerifyException("Unhandled type " + copyType);
216 public final Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
217 return effectOfStatement;
221 public final void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
222 if (ctxs.isEmpty()) {
226 if (effectOfStatement.isEmpty()) {
227 effectOfStatement = new ArrayList<>(ctxs.size());
229 effectOfStatement.addAll(ctxs);
233 // CopyHistory integration
237 public final CopyHistory history() {
242 @Deprecated(since = "7.0.9", forRemoval = true)
243 public final boolean isAddedByUses() {
244 return (bitsAight & COPY_ADDED_BY_USES) != 0;
248 @Deprecated(since = "8.0.0")
249 public final boolean isAugmenting() {
250 return (bitsAight & COPY_ADDED_BY_AUGMENTATION) != 0;
254 public final CopyType getLastOperation() {
255 return COPY_TYPE_VALUES[bitsAight & COPY_LAST_TYPE_MASK];
258 // This method exists only for space optimization of InferredStatementContext
259 final CopyType childCopyType() {
260 return COPY_TYPE_VALUES[bitsAight >> COPY_CHILD_TYPE_SHIFT & COPY_LAST_TYPE_MASK];
264 // Inference completion tracking
268 final byte executionOrder() {
269 return executionOrder;
272 // FIXME: this should be propagated through a correct constructor
274 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
275 this.executionOrder = completedPhase.executionOrder();
279 public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
280 final Class<@NonNull N> type, final T key, final U value) {
281 addToNamespace(type, key, value);
284 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
285 final List<ReactorStmtCtx<?, ?, ?>> effective) {
286 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
289 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
290 return effective.isEmpty() ? ImmutableList.of() : effective;
293 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
294 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
295 if (effective.isEmpty()) {
299 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
300 while (iterator.hasNext()) {
301 final StmtContext<?, ?, ?> next = iterator.next();
302 if (statementDef.equals(next.publicDefinition())) {
307 return shrinkEffective(effective);
310 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
311 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
312 final String statementArg) {
313 if (statementArg == null) {
314 return removeStatementFromEffectiveSubstatements(effective, statementDef);
317 if (effective.isEmpty()) {
321 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
322 while (iterator.hasNext()) {
323 final Mutable<?, ?, ?> next = iterator.next();
324 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
329 return shrinkEffective(effective);
333 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
334 Mutable<X, Y, Z> createUndeclaredSubstatement(final StatementSupport<X, Y, Z> support, final X arg) {
335 requireNonNull(support);
336 checkArgument(support instanceof UndeclaredStatementFactory, "Unsupported statement support %s", support);
338 final var ret = new UndeclaredStmtCtx<>(this, support, arg);
339 support.onStatementAdded(ret);
343 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
344 final Mutable<?, ?, ?> substatement) {
345 final ReactorStmtCtx<?, ?, ?> stmt = verifyStatement(substatement);
346 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
347 ensureCompletedExecution(stmt);
352 static final void afterAddEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
353 // Undeclared statements still need to have 'onDeclarationFinished()' triggered
354 if (substatement instanceof UndeclaredStmtCtx) {
355 finishDeclaration((UndeclaredStmtCtx<?, ?, ?>) substatement);
359 // Split out to keep generics working without a warning
360 private static <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> void finishDeclaration(
361 final UndeclaredStmtCtx<X, Y, Z> substatement) {
362 substatement.definition().onDeclarationFinished(substatement, ModelProcessingPhase.FULL_DECLARATION);
366 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
367 if (!statements.isEmpty()) {
368 statements.forEach(StatementContextBase::verifyStatement);
369 addEffectiveSubstatementsImpl(statements);
373 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
375 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
376 final Collection<? extends Mutable<?, ?, ?>> statements) {
377 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
378 final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
379 (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
380 if (executionOrder != ExecutionOrder.NULL) {
381 for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
382 ensureCompletedExecution(stmt, executionOrder);
386 resized.addAll(casted);
390 abstract Iterator<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
392 // exposed for InferredStatementContext only
393 final ReactorStmtCtx<?, ?, ?> ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
394 final var ret = verifyStatement(stmt);
395 ensureCompletedExecution(ret);
399 // Make sure target statement has transitioned at least to our phase (if we have one). This method is just before we
400 // take allow a statement to become our substatement. This is needed to ensure that every statement tree does not
401 // contain any statements which did not complete the same phase as the root statement.
402 private void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt) {
403 if (executionOrder != ExecutionOrder.NULL) {
404 ensureCompletedExecution(stmt, executionOrder);
408 private static void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt, final byte executionOrder) {
409 verify(stmt.tryToCompletePhase(executionOrder), "Statement %s cannot complete phase %s", stmt, executionOrder);
412 private static ReactorStmtCtx<?, ?, ?> verifyStatement(final Mutable<?, ?, ?> stmt) {
413 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
414 return (ReactorStmtCtx<?, ?, ?>) stmt;
417 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
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",
424 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
427 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
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());
434 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
438 final E createEffective() {
439 final E result = createEffective(definition.getFactory());
440 if (result instanceof MutableStatement) {
441 getRoot().addMutableStmtToSeal((MutableStatement) result);
446 abstract @NonNull E createEffective(@NonNull StatementFactory<A, D, E> factory);
449 * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
450 * {@link StmtContext#buildEffective()} contract.
452 * @return Stream of supported declared statements.
454 // FIXME: we really want to unify this with streamEffective(), under its name
455 abstract Stream<? extends @NonNull ReactorStmtCtx<?, ?, ?>> streamDeclared();
458 * Return a stream of inferred statements which can be built into an {@link EffectiveStatement}, as per
459 * {@link StmtContext#buildEffective()} contract.
461 * @return Stream of supported effective statements.
463 // FIXME: this method is currently a misnomer, but unifying with streamDeclared() would make this accurate again
464 abstract Stream<? extends @NonNull ReactorStmtCtx<?, ?, ?>> streamEffective();
467 final boolean doTryToCompletePhase(final byte targetOrder) {
468 final boolean finished = phaseMutation.isEmpty() || runMutations(targetOrder);
469 if (completeChildren(targetOrder) && finished) {
470 onPhaseCompleted(targetOrder);
476 private boolean completeChildren(final byte targetOrder) {
477 boolean finished = true;
478 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
479 finished &= child.tryToCompletePhase(targetOrder);
481 final var it = effectiveChildrenToComplete();
482 while (it.hasNext()) {
483 finished &= it.next().tryToCompletePhase(targetOrder);
488 private boolean runMutations(final byte targetOrder) {
489 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(targetOrder));
490 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
491 return openMutations.isEmpty() || runMutations(phase, openMutations);
494 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
495 boolean finished = true;
496 final Iterator<ContextMutation> it = openMutations.iterator();
497 while (it.hasNext()) {
498 final ContextMutation current = it.next();
499 if (current.isFinished()) {
506 if (openMutations.isEmpty()) {
507 phaseMutation.removeAll(phase);
508 cleanupPhaseMutation();
513 private void cleanupPhaseMutation() {
514 if (phaseMutation.isEmpty()) {
515 phaseMutation = ImmutableMultimap.of();
520 * Occurs on end of {@link ModelProcessingPhase} of source parsing. This method must not be called with
521 * {@code executionOrder} equal to {@link ExecutionOrder#NULL}.
523 * @param phase that was to be completed (finished)
524 * @throws SourceException when an error occurred in source parsing
526 private void onPhaseCompleted(final byte completedOrder) {
527 executionOrder = completedOrder;
528 if (completedOrder == ExecutionOrder.EFFECTIVE_MODEL) {
529 // We have completed effective model, substatements are guaranteed not to change
530 summarizeSubstatementPolicy();
533 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(completedOrder));
534 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
535 if (!listeners.isEmpty()) {
536 runPhaseListeners(phase, listeners);
540 private void summarizeSubstatementPolicy() {
541 if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
542 setAllSubstatementsContextIndependent();
547 * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
548 * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
549 * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
550 * considered copy-insensitive.
553 * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
555 * @return True if no substatements require copy-sensitive handling
557 abstract boolean noSensitiveSubstatements();
560 * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
561 * {@link #noSensitiveSubstatements()}.
563 * @param substatements Substatements to check
564 * @return True if no substatements require context-sensitive handling
566 static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
567 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
568 if (stmt.isSupportedToBuildEffective()) {
569 if (!stmt.allSubstatementsContextIndependent()) {
570 // This is a recursive property
574 switch (stmt.definition().support().copyPolicy()) {
575 case CONTEXT_INDEPENDENT:
587 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
588 final Iterator<OnPhaseFinished> listener = listeners.iterator();
589 while (listener.hasNext()) {
590 final OnPhaseFinished next = listener.next();
591 if (next.phaseFinished(this, phase)) {
596 if (listeners.isEmpty()) {
597 phaseListeners.removeAll(phase);
598 if (phaseListeners.isEmpty()) {
599 phaseListeners = ImmutableMultimap.of();
605 final StatementDefinitionContext<A, D, E> definition() {
609 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
610 final OnNamespaceItemAdded listener) {
611 final Object potential = getFromNamespace(type, key);
612 if (potential != null) {
613 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
614 listener.namespaceItemAdded(this, type, key, potential);
618 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
620 void onValueAdded(final Object value) {
621 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
626 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
627 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
628 final OnNamespaceItemAdded listener) {
629 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
630 if (existing.isPresent()) {
631 final Entry<K, V> entry = existing.get();
632 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
633 waitForPhase(entry.getValue(), type, phase, criterion, listener);
637 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
638 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
640 boolean onValueAdded(final K key, final V value) {
641 if (criterion.match(key)) {
642 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
643 waitForPhase(value, type, phase, criterion, listener);
652 final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
653 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
654 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
655 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
657 final Entry<K, V> match = optMatch.get();
658 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
661 final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
662 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
663 final OnNamespaceItemAdded listener) {
664 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
665 (context, phaseCompleted) -> {
666 selectMatch(type, criterion, listener);
671 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
672 final Class<N> type) {
673 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
674 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
677 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
680 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
681 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
685 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
686 * the listener is notified immediately.
688 * @param phase requested completion phase
689 * @param listener listener to invoke
690 * @throws NullPointerException if any of the arguments is null
692 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
693 requireNonNull(phase, "Statement context processing phase cannot be null");
694 requireNonNull(listener, "Statement context phase listener cannot be null");
696 ModelProcessingPhase finishedPhase = ModelProcessingPhase.ofExecutionOrder(executionOrder);
697 while (finishedPhase != null) {
698 if (phase.equals(finishedPhase)) {
699 listener.phaseFinished(this, finishedPhase);
702 finishedPhase = finishedPhase.getPreviousPhase();
704 if (phaseListeners.isEmpty()) {
705 phaseListeners = newMultimap();
708 phaseListeners.put(phase, listener);
712 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
714 * @throws IllegalStateException when the mutation was registered after phase was completed
716 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
717 checkState(executionOrder < phase.executionOrder(), "Mutation registered after phase was completed at: %s",
720 if (phaseMutation.isEmpty()) {
721 phaseMutation = newMultimap();
723 phaseMutation.put(phase, mutation);
726 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
727 if (!phaseMutation.isEmpty()) {
728 phaseMutation.remove(phase, mutation);
729 cleanupPhaseMutation();
734 public final <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(
735 final Class<@NonNull N> namespace, final KT key,final StmtContext<?, ?, ?> stmt) {
736 addContextToNamespace(namespace, key, stmt);
740 public final Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
741 final QNameModule targetModule) {
742 checkEffectiveModelCompleted(this);
743 return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
746 private @Nullable ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
747 final QNameModule targetModule) {
748 final StatementSupport<A, D, E> support = definition.support();
749 final CopyPolicy policy = support.copyPolicy();
752 return replicaAsChildOf(parent);
753 case CONTEXT_INDEPENDENT:
754 if (allSubstatementsContextIndependent()) {
755 return replicaAsChildOf(parent);
761 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
765 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
767 throw new IllegalStateException("Unhandled policy " + policy);
772 final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
773 final QNameModule targetModule) {
774 final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
776 // The statement fizzled, this should never happen, perhaps a verify()?
780 parent.ensureCompletedExecution(copy);
781 return canReuseCurrent(copy) ? this : copy;
784 private boolean canReuseCurrent(final @NonNull ReactorStmtCtx<A, D, E> copy) {
785 // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
786 // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
787 return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
788 && allSubstatementsContextIndependent();
792 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
793 final QNameModule targetModule) {
794 checkEffectiveModelCompleted(stmt);
795 if (stmt instanceof StatementContextBase) {
796 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
797 } else if (stmt instanceof ReplicaStatementContext) {
798 return ((ReplicaStatementContext<?, ?, ?>) stmt).replicaAsChildOf(this);
800 throw new IllegalArgumentException("Unsupported statement " + stmt);
804 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
805 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
806 final var implicitParent = definition.getImplicitParentFor(this, original.publicDefinition());
808 final StatementContextBase<X, Y, Z> result;
809 final InferredStatementContext<X, Y, Z> copy;
811 if (implicitParent.isPresent()) {
812 result = new UndeclaredStmtCtx(this, implicitParent.orElseThrow(), original, type);
814 final CopyType childCopyType;
816 case ADDED_BY_AUGMENTATION:
817 childCopyType = CopyType.ORIGINAL;
819 case ADDED_BY_USES_AUGMENTATION:
820 childCopyType = CopyType.ADDED_BY_USES;
825 childCopyType = type;
828 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
829 result.addEffectiveSubstatement(copy);
830 result.definition.onStatementAdded(result);
832 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
835 original.definition.onStatementAdded(copy);
840 final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
841 return new ReplicaStatementContext<>(parent, this);
844 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
845 final ModelProcessingPhase phase = stmt.getCompletedPhase();
846 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
847 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
851 public final boolean hasImplicitParentSupport() {
852 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
856 public final StmtContext<?, ?, ?> wrapWithImplicit(final StmtContext<?, ?, ?> original) {
857 final var optImplicit = definition.getImplicitParentFor(this, original.publicDefinition());
858 if (optImplicit.isEmpty()) {
862 checkArgument(original instanceof StatementContextBase, "Unsupported original %s", original);
863 final var origBase = (StatementContextBase<?, ?, ?>)original;
865 @SuppressWarnings({ "rawtypes", "unchecked" })
866 final UndeclaredStmtCtx<?, ?, ?> result = new UndeclaredStmtCtx(origBase, optImplicit.orElseThrow());
867 result.addEffectiveSubstatement(origBase.reparent(result));
868 result.setCompletedPhase(original.getCompletedPhase());
872 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
875 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
877 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
879 abstract boolean hasEmptySubstatements();
881 // Note: these two are exposed for AbstractResumedStatement only
882 final boolean getImplicitDeclaredFlag() {
883 return implicitDeclaredFlag;
886 final void setImplicitDeclaredFlag() {
887 implicitDeclaredFlag = true;