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.annotations.Beta;
17 import com.google.common.base.VerifyException;
18 import com.google.common.collect.ImmutableCollection;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMultimap;
21 import com.google.common.collect.Multimap;
22 import com.google.common.collect.Multimaps;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.EnumMap;
27 import java.util.EventListener;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32 import java.util.stream.Stream;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
36 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.ExecutionOrder;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
54 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
55 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
56 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
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 public 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;
153 // Copy constructor used by subclasses to implement reparent()
154 StatementContextBase(final StatementContextBase<A, D, E> original) {
156 this.bitsAight = original.bitsAight;
157 this.definition = original.definition;
158 this.executionOrder = original.executionOrder;
161 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
162 this.definition = requireNonNull(def);
163 this.bitsAight = COPY_ORIGINAL;
166 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyType copyType) {
167 this.definition = requireNonNull(def);
168 this.bitsAight = (byte) copyFlags(copyType);
171 StatementContextBase(final StatementContextBase<A, D, E> prototype, final CopyType copyType,
172 final CopyType childCopyType) {
173 this.definition = prototype.definition;
174 this.bitsAight = (byte) (copyFlags(copyType)
175 | prototype.bitsAight & ~COPY_LAST_TYPE_MASK | childCopyType.ordinal() << COPY_CHILD_TYPE_SHIFT);
178 private static int copyFlags(final CopyType copyType) {
179 return historyFlags(copyType) | copyType.ordinal();
182 private static byte historyFlags(final CopyType copyType) {
184 case ADDED_BY_AUGMENTATION:
185 return COPY_ADDED_BY_AUGMENTATION;
187 return COPY_ADDED_BY_USES;
188 case ADDED_BY_USES_AUGMENTATION:
189 return COPY_ADDED_BY_AUGMENTATION | COPY_ADDED_BY_USES;
191 return COPY_ORIGINAL;
193 throw new VerifyException("Unhandled type " + copyType);
198 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
199 return effectOfStatement;
203 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
204 if (ctxs.isEmpty()) {
208 if (effectOfStatement.isEmpty()) {
209 effectOfStatement = new ArrayList<>(ctxs.size());
211 effectOfStatement.addAll(ctxs);
215 // CopyHistory integration
219 public final CopyHistory history() {
224 @Deprecated(since = "7.0.9", forRemoval = true)
225 public final boolean isAddedByUses() {
226 return (bitsAight & COPY_ADDED_BY_USES) != 0;
230 public final boolean isAugmenting() {
231 return (bitsAight & COPY_ADDED_BY_AUGMENTATION) != 0;
235 public final CopyType getLastOperation() {
236 return COPY_TYPE_VALUES[bitsAight & COPY_LAST_TYPE_MASK];
239 // This method exists only for space optimization of InferredStatementContext
240 final CopyType childCopyType() {
241 return COPY_TYPE_VALUES[bitsAight >> COPY_CHILD_TYPE_SHIFT & COPY_LAST_TYPE_MASK];
245 // Inference completion tracking
249 final byte executionOrder() {
250 return executionOrder;
253 // FIXME: this should be propagated through a correct constructor
255 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
256 this.executionOrder = completedPhase.executionOrder();
260 public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
261 final Class<@NonNull N> type, final T key, final U value) {
262 addToNamespace(type, key, value);
265 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
266 final List<ReactorStmtCtx<?, ?, ?>> effective) {
267 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
270 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
271 return effective.isEmpty() ? ImmutableList.of() : effective;
274 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
276 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
277 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
278 if (effective.isEmpty()) {
282 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
283 while (iterator.hasNext()) {
284 final StmtContext<?, ?, ?> next = iterator.next();
285 if (statementDef.equals(next.publicDefinition())) {
290 return shrinkEffective(effective);
294 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
295 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
296 * definition and statement argument match with one of the effective substatements' statement definition
300 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
302 * @param statementDef statement definition of the statement context to remove
303 * @param statementArg statement argument of the statement context to remove
305 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
306 String statementArg);
308 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
309 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
310 final String statementArg) {
311 if (statementArg == null) {
312 return removeStatementFromEffectiveSubstatements(effective, statementDef);
315 if (effective.isEmpty()) {
319 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
320 while (iterator.hasNext()) {
321 final Mutable<?, ?, ?> next = iterator.next();
322 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
327 return shrinkEffective(effective);
330 // YANG example: RPC/action statements always have 'input' and 'output' defined
332 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
333 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
334 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
335 // StatementContextBase subclass.
336 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
337 ImplicitSubstatement.of(sourceReference()), rawArg);
338 support.onStatementAdded(ret);
339 addEffectiveSubstatement(ret);
344 * Adds an effective statement to collection of substatements.
346 * @param substatement substatement
347 * @throws IllegalStateException if added in declared phase
348 * @throws NullPointerException if statement parameter is null
350 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
352 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
353 final Mutable<?, ?, ?> substatement) {
354 verifyStatement(substatement);
356 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
357 final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
358 ensureCompletedExecution(stmt);
364 * Adds an effective statement to collection of substatements.
366 * @param statements substatements
367 * @throws IllegalStateException
368 * if added in declared phase
369 * @throws NullPointerException
370 * if statement parameter is null
372 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
373 if (!statements.isEmpty()) {
374 statements.forEach(StatementContextBase::verifyStatement);
375 addEffectiveSubstatementsImpl(statements);
379 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
381 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
382 final Collection<? extends Mutable<?, ?, ?>> statements) {
383 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
384 final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
385 (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
386 if (executionOrder != ExecutionOrder.NULL) {
387 for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
388 ensureCompletedExecution(stmt, executionOrder);
392 resized.addAll(casted);
396 abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
398 // exposed for InferredStatementContext only
399 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
400 verifyStatement(stmt);
401 ensureCompletedExecution((ReactorStmtCtx<?, ?, ?>) stmt);
404 // Make sure target statement has transitioned at least to our phase (if we have one). This method is just before we
405 // take allow a statement to become our substatement. This is needed to ensure that every statement tree does not
406 // contain any statements which did not complete the same phase as the root statement.
407 private void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt) {
408 if (executionOrder != ExecutionOrder.NULL) {
409 ensureCompletedExecution(stmt, executionOrder);
413 private static void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt, final byte executionOrder) {
414 verify(stmt.tryToCompletePhase(executionOrder), "Statement %s cannot complete phase %s", stmt, executionOrder);
417 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
418 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
421 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
423 // We cannot allow statement to be further mutated.
424 // TODO: we really want to say 'not NULL and not at or after EFFECTIVE_MODEL here. This will matter if we have
425 // a phase after EFFECTIVE_MODEL
426 verify(executionOrder != ExecutionOrder.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
428 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
431 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
433 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
434 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
435 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
436 "Effective statement cannot be added in declared phase at: %s", sourceReference());
438 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
442 final E createEffective() {
443 final E result = createEffective(definition.getFactory());
444 if (result instanceof MutableStatement) {
445 getRoot().addMutableStmtToSeal((MutableStatement) result);
450 @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
451 return createEffective(factory, this);
454 // Creates EffectiveStatement through full materialization
455 static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
456 final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
457 return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
461 * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
462 * {@link StmtContext#buildEffective()} contract.
464 * @return Stream of supported declared statements.
466 // FIXME: we really want to unify this with streamEffective(), under its name
467 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared();
470 * Return a stream of inferred statements which can be built into an {@link EffectiveStatement}, as per
471 * {@link StmtContext#buildEffective()} contract.
473 * @return Stream of supported effective statements.
475 // FIXME: this method is currently a misnomer, but unifying with streamDeclared() would make this accurate again
476 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective();
479 final boolean doTryToCompletePhase(final byte targetOrder) {
480 final boolean finished = phaseMutation.isEmpty() || runMutations(targetOrder);
481 if (completeChildren(targetOrder) && finished) {
482 onPhaseCompleted(targetOrder);
488 private boolean completeChildren(final byte targetOrder) {
489 boolean finished = true;
490 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
491 finished &= child.tryToCompletePhase(targetOrder);
493 for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
494 finished &= child.tryToCompletePhase(targetOrder);
499 private boolean runMutations(final byte targetOrder) {
500 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(targetOrder));
501 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
502 return openMutations.isEmpty() || runMutations(phase, openMutations);
505 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
506 boolean finished = true;
507 final Iterator<ContextMutation> it = openMutations.iterator();
508 while (it.hasNext()) {
509 final ContextMutation current = it.next();
510 if (current.isFinished()) {
517 if (openMutations.isEmpty()) {
518 phaseMutation.removeAll(phase);
519 cleanupPhaseMutation();
524 private void cleanupPhaseMutation() {
525 if (phaseMutation.isEmpty()) {
526 phaseMutation = ImmutableMultimap.of();
531 * Occurs on end of {@link ModelProcessingPhase} of source parsing. This method must not be called with
532 * {@code executionOrder} equal to {@link ExecutionOrder#NULL}.
534 * @param phase that was to be completed (finished)
535 * @throws SourceException when an error occurred in source parsing
537 private void onPhaseCompleted(final byte completedOrder) {
538 executionOrder = completedOrder;
539 if (completedOrder == ExecutionOrder.EFFECTIVE_MODEL) {
540 // We have completed effective model, substatements are guaranteed not to change
541 summarizeSubstatementPolicy();
544 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(completedOrder));
545 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
546 if (!listeners.isEmpty()) {
547 runPhaseListeners(phase, listeners);
551 private void summarizeSubstatementPolicy() {
552 if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
553 setAllSubstatementsContextIndependent();
558 * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
559 * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
560 * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
561 * considered copy-insensitive.
564 * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
566 * @return True if no substatements require copy-sensitive handling
568 abstract boolean noSensitiveSubstatements();
571 * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
572 * {@link #noSensitiveSubstatements()}.
574 * @param substatements Substatements to check
575 * @return True if no substatements require context-sensitive handling
577 static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
578 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
579 if (stmt.isSupportedToBuildEffective()) {
580 if (!stmt.allSubstatementsContextIndependent()) {
581 // This is a recursive property
585 switch (stmt.definition().support().copyPolicy()) {
586 case CONTEXT_INDEPENDENT:
598 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
599 final Iterator<OnPhaseFinished> listener = listeners.iterator();
600 while (listener.hasNext()) {
601 final OnPhaseFinished next = listener.next();
602 if (next.phaseFinished(this, phase)) {
607 if (listeners.isEmpty()) {
608 phaseListeners.removeAll(phase);
609 if (phaseListeners.isEmpty()) {
610 phaseListeners = ImmutableMultimap.of();
616 * Ends declared section of current node.
618 void endDeclared(final ModelProcessingPhase phase) {
619 definition.onDeclarationFinished(this, phase);
623 final StatementDefinitionContext<A, D, E> definition() {
627 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
628 final OnNamespaceItemAdded listener) {
629 final Object potential = getFromNamespace(type, key);
630 if (potential != null) {
631 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
632 listener.namespaceItemAdded(this, type, key, potential);
636 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
638 void onValueAdded(final Object value) {
639 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
644 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
645 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
646 final OnNamespaceItemAdded listener) {
647 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
648 if (existing.isPresent()) {
649 final Entry<K, V> entry = existing.get();
650 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
651 waitForPhase(entry.getValue(), type, phase, criterion, listener);
655 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
656 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
658 boolean onValueAdded(final K key, final V value) {
659 if (criterion.match(key)) {
660 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
661 waitForPhase(value, type, phase, criterion, listener);
670 final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
671 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
672 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
673 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
675 final Entry<K, V> match = optMatch.get();
676 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
679 final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
680 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
681 final OnNamespaceItemAdded listener) {
682 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
683 (context, phaseCompleted) -> {
684 selectMatch(type, criterion, listener);
689 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
690 final Class<N> type) {
691 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
692 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
695 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
698 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
699 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
703 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
704 * the listener is notified immediately.
706 * @param phase requested completion phase
707 * @param listener listener to invoke
708 * @throws NullPointerException if any of the arguments is null
710 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
711 requireNonNull(phase, "Statement context processing phase cannot be null");
712 requireNonNull(listener, "Statement context phase listener cannot be null");
714 ModelProcessingPhase finishedPhase = ModelProcessingPhase.ofExecutionOrder(executionOrder);
715 while (finishedPhase != null) {
716 if (phase.equals(finishedPhase)) {
717 listener.phaseFinished(this, finishedPhase);
720 finishedPhase = finishedPhase.getPreviousPhase();
722 if (phaseListeners.isEmpty()) {
723 phaseListeners = newMultimap();
726 phaseListeners.put(phase, listener);
730 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
732 * @throws IllegalStateException when the mutation was registered after phase was completed
734 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
735 checkState(executionOrder < phase.executionOrder(), "Mutation registered after phase was completed at: %s",
738 if (phaseMutation.isEmpty()) {
739 phaseMutation = newMultimap();
741 phaseMutation.put(phase, mutation);
744 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
745 if (!phaseMutation.isEmpty()) {
746 phaseMutation.remove(phase, mutation);
747 cleanupPhaseMutation();
752 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
753 final KT key,final StmtContext<?, ?, ?> stmt) {
754 addContextToNamespace(namespace, key, stmt);
758 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
759 final QNameModule targetModule) {
760 checkEffectiveModelCompleted(this);
761 return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
764 private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
765 final QNameModule targetModule) {
766 final StatementSupport<A, D, E> support = definition.support();
767 final CopyPolicy policy = support.copyPolicy();
770 return replicaAsChildOf(parent);
771 case CONTEXT_INDEPENDENT:
772 if (allSubstatementsContextIndependent()) {
773 return replicaAsChildOf(parent);
779 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
783 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
785 throw new IllegalStateException("Unhandled policy " + policy);
790 final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
791 final QNameModule targetModule) {
792 final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
794 // The statement fizzled, this should never happen, perhaps a verify()?
798 parent.ensureCompletedPhase(copy);
799 return canReuseCurrent(copy) ? this : copy;
802 private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
803 // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
804 // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
805 return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
806 && allSubstatementsContextIndependent();
810 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
811 final QNameModule targetModule) {
812 checkEffectiveModelCompleted(stmt);
813 if (stmt instanceof StatementContextBase) {
814 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
815 } else if (stmt instanceof ReplicaStatementContext) {
816 return ((ReplicaStatementContext<?, ?, ?>) stmt).replicaAsChildOf(this);
818 throw new IllegalArgumentException("Unsupported statement " + stmt);
822 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
823 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
824 final var implicitParent = definition.getImplicitParentFor(this, original.publicDefinition());
826 final StatementContextBase<X, Y, Z> result;
827 final InferredStatementContext<X, Y, Z> copy;
829 if (implicitParent.isPresent()) {
830 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
831 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
832 original.argument(), type);
834 final CopyType childCopyType;
836 case ADDED_BY_AUGMENTATION:
837 childCopyType = CopyType.ORIGINAL;
839 case ADDED_BY_USES_AUGMENTATION:
840 childCopyType = CopyType.ADDED_BY_USES;
845 childCopyType = type;
848 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
849 result.addEffectiveSubstatement(copy);
851 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
854 original.definition.onStatementAdded(copy);
859 final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
860 return new ReplicaStatementContext<>(parent, this);
863 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
864 final ModelProcessingPhase phase = stmt.getCompletedPhase();
865 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
866 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
870 // FIXME: this information should be exposed as a well-known Namespace
871 public final boolean hasImplicitParentSupport() {
872 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
876 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
877 final var optImplicit = definition.getImplicitParentFor(this, original.publicDefinition());
878 if (optImplicit.isEmpty()) {
882 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.orElseThrow());
883 final CopyType type = original.history().getLastOperation();
884 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
885 original.sourceReference(), original.rawArgument(), original.argument(), type);
887 result.addEffectiveSubstatement(original.reparent(result));
888 result.setCompletedPhase(original.getCompletedPhase());
892 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
895 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
897 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
899 abstract boolean hasEmptySubstatements();