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.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;
60 * Core reactor statement implementation of {@link Mutable}.
62 * @param <A> Argument type
63 * @param <D> Declared Statement representation
64 * @param <E> Effective Statement representation
66 abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
67 extends ReactorStmtCtx<A, D, E> implements CopyHistory {
69 * Event listener when an item is added to model namespace.
71 interface OnNamespaceItemAdded extends EventListener {
73 * Invoked whenever a new item is added to a namespace.
75 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
79 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
81 interface OnPhaseFinished extends EventListener {
83 * Invoked whenever a processing phase has finished.
85 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
89 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
91 interface ContextMutation {
96 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
98 // Bottom 4 bits, encoding a CopyHistory, aight?
99 private static final byte COPY_ORIGINAL = 0x00;
100 private static final byte COPY_LAST_TYPE_MASK = 0x03;
101 @Deprecated(since = "7.0.9", forRemoval = true)
102 private static final byte COPY_ADDED_BY_USES = 0x04;
103 private static final byte COPY_ADDED_BY_AUGMENTATION = 0x08;
105 // Top four bits, of which we define the topmost two to 0. We use the bottom two to encode last CopyType, aight?
106 private static final int COPY_CHILD_TYPE_SHIFT = 4;
108 private static final CopyType @NonNull [] COPY_TYPE_VALUES = CopyType.values();
111 final int copyTypes = COPY_TYPE_VALUES.length;
112 // This implies CopyType.ordinal() is <= COPY_TYPE_MASK
113 verify(copyTypes == COPY_LAST_TYPE_MASK + 1, "Unexpected %s CopyType values", copyTypes);
117 * 8 bits worth of instance storage. This is treated as a constant bit field with following structure:
126 * The four allocated fields are:
128 * <li>{@code lst}, encoding the four states corresponding to {@link CopyHistory#getLastOperation()}</li>
129 * <li>{@code u}, encoding {@link #isAddedByUses()}</li>
130 * <li>{@code a}, encoding {@link #isAugmenting()}</li>
131 * <li>{@code cct} encoding {@link #childCopyType()}</li>
133 * We still have two unused bits.
135 private final byte bitsAight;
137 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
138 // operations, hence we want to keep it close by.
139 private final @NonNull StatementDefinitionContext<A, D, E> definition;
141 // TODO: consider keying by Byte equivalent of ExecutionOrder
142 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
143 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
145 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
148 * {@link ModelProcessingPhase.ExecutionOrder} value of current {@link ModelProcessingPhase} of this statement.
150 private byte executionOrder;
153 * This field should live in AbstractResumedStatement, but is placed here for memory efficiency to squat in the
154 * alignment shadow of {@link #bitsAight} and {@link #executionOrder}.
156 private boolean implicitDeclaredFlag;
158 // TODO: we a single byte of alignment shadow left, we should think how we can use it to cache information we build
159 // during buildEffective()
161 // Copy constructor used by subclasses to implement reparent()
162 StatementContextBase(final StatementContextBase<A, D, E> original) {
164 this.bitsAight = original.bitsAight;
165 this.definition = original.definition;
166 this.executionOrder = original.executionOrder;
169 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
170 this.definition = requireNonNull(def);
171 this.bitsAight = COPY_ORIGINAL;
174 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyType copyType) {
175 this.definition = requireNonNull(def);
176 this.bitsAight = (byte) copyFlags(copyType);
179 StatementContextBase(final StatementContextBase<A, D, E> prototype, final CopyType copyType,
180 final CopyType childCopyType) {
181 this.definition = prototype.definition;
182 this.bitsAight = (byte) (copyFlags(copyType)
183 | prototype.bitsAight & ~COPY_LAST_TYPE_MASK | childCopyType.ordinal() << COPY_CHILD_TYPE_SHIFT);
186 private static int copyFlags(final CopyType copyType) {
187 return historyFlags(copyType) | copyType.ordinal();
190 private static byte historyFlags(final CopyType copyType) {
192 case ADDED_BY_AUGMENTATION:
193 return COPY_ADDED_BY_AUGMENTATION;
195 return COPY_ADDED_BY_USES;
196 case ADDED_BY_USES_AUGMENTATION:
197 return COPY_ADDED_BY_AUGMENTATION | COPY_ADDED_BY_USES;
199 return COPY_ORIGINAL;
201 throw new VerifyException("Unhandled type " + copyType);
206 public final Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
207 return effectOfStatement;
211 public final void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
212 if (ctxs.isEmpty()) {
216 if (effectOfStatement.isEmpty()) {
217 effectOfStatement = new ArrayList<>(ctxs.size());
219 effectOfStatement.addAll(ctxs);
223 // CopyHistory integration
227 public final CopyHistory history() {
232 @Deprecated(since = "7.0.9", forRemoval = true)
233 public final boolean isAddedByUses() {
234 return (bitsAight & COPY_ADDED_BY_USES) != 0;
238 @Deprecated(since = "8.0.0")
239 public final boolean isAugmenting() {
240 return (bitsAight & COPY_ADDED_BY_AUGMENTATION) != 0;
244 public final CopyType getLastOperation() {
245 return COPY_TYPE_VALUES[bitsAight & COPY_LAST_TYPE_MASK];
248 // This method exists only for space optimization of InferredStatementContext
249 final CopyType childCopyType() {
250 return COPY_TYPE_VALUES[bitsAight >> COPY_CHILD_TYPE_SHIFT & COPY_LAST_TYPE_MASK];
254 // Inference completion tracking
258 final byte executionOrder() {
259 return executionOrder;
262 // FIXME: this should be propagated through a correct constructor
264 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
265 this.executionOrder = completedPhase.executionOrder();
269 public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
270 final Class<@NonNull N> type, final T key, final U value) {
271 addToNamespace(type, key, value);
274 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
275 final List<ReactorStmtCtx<?, ?, ?>> effective) {
276 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
279 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
280 return effective.isEmpty() ? ImmutableList.of() : effective;
283 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
284 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
285 if (effective.isEmpty()) {
289 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
290 while (iterator.hasNext()) {
291 final StmtContext<?, ?, ?> next = iterator.next();
292 if (statementDef.equals(next.publicDefinition())) {
297 return shrinkEffective(effective);
300 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
301 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
302 final String statementArg) {
303 if (statementArg == null) {
304 return removeStatementFromEffectiveSubstatements(effective, statementDef);
307 if (effective.isEmpty()) {
311 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
312 while (iterator.hasNext()) {
313 final Mutable<?, ?, ?> next = iterator.next();
314 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
319 return shrinkEffective(effective);
323 public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
324 Mutable<X, Y, Z> addUndeclaredSubstatement(final StatementSupport<X, Y, Z> support, final X arg) {
325 requireNonNull(support);
326 checkArgument(support instanceof UndeclaredStatementFactory, "Unsupported statement support %s", support);
328 final var ret = new UndeclaredStmtCtx<>(this, support, arg);
329 support.onStatementAdded(ret);
330 addEffectiveSubstatement(ret);
334 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
335 final Mutable<?, ?, ?> substatement) {
336 verifyStatement(substatement);
338 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
339 final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
340 ensureCompletedExecution(stmt);
346 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
347 if (!statements.isEmpty()) {
348 statements.forEach(StatementContextBase::verifyStatement);
349 addEffectiveSubstatementsImpl(statements);
353 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
355 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
356 final Collection<? extends Mutable<?, ?, ?>> statements) {
357 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
358 final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
359 (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
360 if (executionOrder != ExecutionOrder.NULL) {
361 for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
362 ensureCompletedExecution(stmt, executionOrder);
366 resized.addAll(casted);
370 abstract Iterator<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
372 // exposed for InferredStatementContext only
373 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
374 verifyStatement(stmt);
375 ensureCompletedExecution((ReactorStmtCtx<?, ?, ?>) stmt);
378 // Make sure target statement has transitioned at least to our phase (if we have one). This method is just before we
379 // take allow a statement to become our substatement. This is needed to ensure that every statement tree does not
380 // contain any statements which did not complete the same phase as the root statement.
381 private void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt) {
382 if (executionOrder != ExecutionOrder.NULL) {
383 ensureCompletedExecution(stmt, executionOrder);
387 private static void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt, final byte executionOrder) {
388 verify(stmt.tryToCompletePhase(executionOrder), "Statement %s cannot complete phase %s", stmt, executionOrder);
391 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
392 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
395 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
397 // We cannot allow statement to be further mutated.
398 // TODO: we really want to say 'not NULL and not at or after EFFECTIVE_MODEL here. This will matter if we have
399 // a phase after EFFECTIVE_MODEL
400 verify(executionOrder != ExecutionOrder.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
402 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
405 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
407 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
408 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
409 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
410 "Effective statement cannot be added in declared phase at: %s", sourceReference());
412 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
416 final E createEffective() {
417 final E result = createEffective(definition.getFactory());
418 if (result instanceof MutableStatement) {
419 getRoot().addMutableStmtToSeal((MutableStatement) result);
424 abstract @NonNull E createEffective(@NonNull StatementFactory<A, D, E> factory);
427 * Routing of the request to build an effective statement from {@link InferredStatementContext} towards the original
428 * definition site. This is needed to pick the correct instantiation method: for declared statements we will
429 * eventually land in {@link AbstractResumedStatement}, for underclared statements that will be
430 * {@link UndeclaredStmtCtx}.
432 * @param factory Statement factory
433 * @param ctx Inferred statement context, i.e. where the effective statement is instantiated
434 * @return Built effective stateue
436 abstract @NonNull E createInferredEffective(@NonNull StatementFactory<A, D, E> factory,
437 @NonNull InferredStatementContext<A, D, E> ctx);
440 * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
441 * {@link StmtContext#buildEffective()} contract.
443 * @return Stream of supported declared statements.
445 // FIXME: we really want to unify this with streamEffective(), under its name
446 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared();
449 * Return a stream of inferred statements which can be built into an {@link EffectiveStatement}, as per
450 * {@link StmtContext#buildEffective()} contract.
452 * @return Stream of supported effective statements.
454 // FIXME: this method is currently a misnomer, but unifying with streamDeclared() would make this accurate again
455 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective();
458 final boolean doTryToCompletePhase(final byte targetOrder) {
459 final boolean finished = phaseMutation.isEmpty() || runMutations(targetOrder);
460 if (completeChildren(targetOrder) && finished) {
461 onPhaseCompleted(targetOrder);
467 private boolean completeChildren(final byte targetOrder) {
468 boolean finished = true;
469 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
470 finished &= child.tryToCompletePhase(targetOrder);
472 final var it = effectiveChildrenToComplete();
473 while (it.hasNext()) {
474 finished &= it.next().tryToCompletePhase(targetOrder);
479 private boolean runMutations(final byte targetOrder) {
480 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(targetOrder));
481 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
482 return openMutations.isEmpty() || runMutations(phase, openMutations);
485 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
486 boolean finished = true;
487 final Iterator<ContextMutation> it = openMutations.iterator();
488 while (it.hasNext()) {
489 final ContextMutation current = it.next();
490 if (current.isFinished()) {
497 if (openMutations.isEmpty()) {
498 phaseMutation.removeAll(phase);
499 cleanupPhaseMutation();
504 private void cleanupPhaseMutation() {
505 if (phaseMutation.isEmpty()) {
506 phaseMutation = ImmutableMultimap.of();
511 * Occurs on end of {@link ModelProcessingPhase} of source parsing. This method must not be called with
512 * {@code executionOrder} equal to {@link ExecutionOrder#NULL}.
514 * @param phase that was to be completed (finished)
515 * @throws SourceException when an error occurred in source parsing
517 private void onPhaseCompleted(final byte completedOrder) {
518 executionOrder = completedOrder;
519 if (completedOrder == ExecutionOrder.EFFECTIVE_MODEL) {
520 // We have completed effective model, substatements are guaranteed not to change
521 summarizeSubstatementPolicy();
524 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(completedOrder));
525 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
526 if (!listeners.isEmpty()) {
527 runPhaseListeners(phase, listeners);
531 private void summarizeSubstatementPolicy() {
532 if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
533 setAllSubstatementsContextIndependent();
538 * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
539 * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
540 * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
541 * considered copy-insensitive.
544 * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
546 * @return True if no substatements require copy-sensitive handling
548 abstract boolean noSensitiveSubstatements();
551 * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
552 * {@link #noSensitiveSubstatements()}.
554 * @param substatements Substatements to check
555 * @return True if no substatements require context-sensitive handling
557 static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
558 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
559 if (stmt.isSupportedToBuildEffective()) {
560 if (!stmt.allSubstatementsContextIndependent()) {
561 // This is a recursive property
565 switch (stmt.definition().support().copyPolicy()) {
566 case CONTEXT_INDEPENDENT:
578 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
579 final Iterator<OnPhaseFinished> listener = listeners.iterator();
580 while (listener.hasNext()) {
581 final OnPhaseFinished next = listener.next();
582 if (next.phaseFinished(this, phase)) {
587 if (listeners.isEmpty()) {
588 phaseListeners.removeAll(phase);
589 if (phaseListeners.isEmpty()) {
590 phaseListeners = ImmutableMultimap.of();
596 final StatementDefinitionContext<A, D, E> definition() {
600 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
601 final OnNamespaceItemAdded listener) {
602 final Object potential = getFromNamespace(type, key);
603 if (potential != null) {
604 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
605 listener.namespaceItemAdded(this, type, key, potential);
609 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
611 void onValueAdded(final Object value) {
612 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
617 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
618 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
619 final OnNamespaceItemAdded listener) {
620 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
621 if (existing.isPresent()) {
622 final Entry<K, V> entry = existing.get();
623 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
624 waitForPhase(entry.getValue(), type, phase, criterion, listener);
628 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
629 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
631 boolean onValueAdded(final K key, final V value) {
632 if (criterion.match(key)) {
633 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
634 waitForPhase(value, type, phase, criterion, listener);
643 final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
644 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
645 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
646 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
648 final Entry<K, V> match = optMatch.get();
649 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
652 final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
653 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
654 final OnNamespaceItemAdded listener) {
655 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
656 (context, phaseCompleted) -> {
657 selectMatch(type, criterion, listener);
662 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
663 final Class<N> type) {
664 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
665 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
668 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
671 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
672 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
676 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
677 * the listener is notified immediately.
679 * @param phase requested completion phase
680 * @param listener listener to invoke
681 * @throws NullPointerException if any of the arguments is null
683 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
684 requireNonNull(phase, "Statement context processing phase cannot be null");
685 requireNonNull(listener, "Statement context phase listener cannot be null");
687 ModelProcessingPhase finishedPhase = ModelProcessingPhase.ofExecutionOrder(executionOrder);
688 while (finishedPhase != null) {
689 if (phase.equals(finishedPhase)) {
690 listener.phaseFinished(this, finishedPhase);
693 finishedPhase = finishedPhase.getPreviousPhase();
695 if (phaseListeners.isEmpty()) {
696 phaseListeners = newMultimap();
699 phaseListeners.put(phase, listener);
703 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
705 * @throws IllegalStateException when the mutation was registered after phase was completed
707 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
708 checkState(executionOrder < phase.executionOrder(), "Mutation registered after phase was completed at: %s",
711 if (phaseMutation.isEmpty()) {
712 phaseMutation = newMultimap();
714 phaseMutation.put(phase, mutation);
717 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
718 if (!phaseMutation.isEmpty()) {
719 phaseMutation.remove(phase, mutation);
720 cleanupPhaseMutation();
725 public final <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(
726 final Class<@NonNull N> namespace, final KT key,final StmtContext<?, ?, ?> stmt) {
727 addContextToNamespace(namespace, key, stmt);
731 public final Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
732 final QNameModule targetModule) {
733 checkEffectiveModelCompleted(this);
734 return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
737 private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
738 final QNameModule targetModule) {
739 final StatementSupport<A, D, E> support = definition.support();
740 final CopyPolicy policy = support.copyPolicy();
743 return replicaAsChildOf(parent);
744 case CONTEXT_INDEPENDENT:
745 if (allSubstatementsContextIndependent()) {
746 return replicaAsChildOf(parent);
752 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
756 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
758 throw new IllegalStateException("Unhandled policy " + policy);
763 final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
764 final QNameModule targetModule) {
765 final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
767 // The statement fizzled, this should never happen, perhaps a verify()?
771 parent.ensureCompletedPhase(copy);
772 return canReuseCurrent(copy) ? this : copy;
775 private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
776 // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
777 // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
778 return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
779 && allSubstatementsContextIndependent();
783 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
784 final QNameModule targetModule) {
785 checkEffectiveModelCompleted(stmt);
786 if (stmt instanceof StatementContextBase) {
787 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
788 } else if (stmt instanceof ReplicaStatementContext) {
789 return ((ReplicaStatementContext<?, ?, ?>) stmt).replicaAsChildOf(this);
791 throw new IllegalArgumentException("Unsupported statement " + stmt);
795 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
796 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
797 final var implicitParent = definition.getImplicitParentFor(this, original.publicDefinition());
799 final StatementContextBase<X, Y, Z> result;
800 final InferredStatementContext<X, Y, Z> copy;
802 if (implicitParent.isPresent()) {
803 result = new UndeclaredStmtCtx(this, implicitParent.orElseThrow(), original, type);
805 final CopyType childCopyType;
807 case ADDED_BY_AUGMENTATION:
808 childCopyType = CopyType.ORIGINAL;
810 case ADDED_BY_USES_AUGMENTATION:
811 childCopyType = CopyType.ADDED_BY_USES;
816 childCopyType = type;
819 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
820 result.addEffectiveSubstatement(copy);
822 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
825 original.definition.onStatementAdded(copy);
830 final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
831 return new ReplicaStatementContext<>(parent, this);
834 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
835 final ModelProcessingPhase phase = stmt.getCompletedPhase();
836 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
837 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
841 public final boolean hasImplicitParentSupport() {
842 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
846 public final StmtContext<?, ?, ?> wrapWithImplicit(final StmtContext<?, ?, ?> original) {
847 final var optImplicit = definition.getImplicitParentFor(this, original.publicDefinition());
848 if (optImplicit.isEmpty()) {
852 checkArgument(original instanceof StatementContextBase, "Unsupported original %s", original);
853 final var origBase = (StatementContextBase<?, ?, ?>)original;
855 @SuppressWarnings({ "rawtypes", "unchecked" })
856 final UndeclaredStmtCtx<?, ?, ?> result = new UndeclaredStmtCtx(origBase, optImplicit.orElseThrow());
857 result.addEffectiveSubstatement(origBase.reparent(result));
858 result.setCompletedPhase(original.getCompletedPhase());
862 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
865 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
867 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
869 abstract boolean hasEmptySubstatements();
871 // Note: these two are exposed for AbstractResumedStatement only
872 final boolean getImplicitDeclaredFlag() {
873 return implicitDeclaredFlag;
876 final void setImplicitDeclaredFlag() {
877 implicitDeclaredFlag = true;