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.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.source.ImplicitSubstatement;
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 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
67 extends ReactorStmtCtx<A, D, E> {
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 private final CopyHistory copyHistory;
99 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
100 // operations, hence we want to keep it close by.
101 private final @NonNull StatementDefinitionContext<A, D, E> definition;
103 // TODO: consider keying by Byte equivalent of ExecutionOrder
104 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
105 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
107 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
110 * {@link ModelProcessingPhase.ExecutionOrder} value of current {@link ModelProcessingPhase} of this statement.
112 private byte executionOrder;
114 // Copy constructor used by subclasses to implement reparent()
115 StatementContextBase(final StatementContextBase<A, D, E> original) {
117 this.copyHistory = original.copyHistory;
118 this.definition = original.definition;
119 this.executionOrder = original.executionOrder;
122 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
123 this.definition = requireNonNull(def);
124 this.copyHistory = CopyHistory.original();
127 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
128 this.definition = requireNonNull(def);
129 this.copyHistory = requireNonNull(copyHistory);
133 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
134 return effectOfStatement;
138 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
139 if (ctxs.isEmpty()) {
143 if (effectOfStatement.isEmpty()) {
144 effectOfStatement = new ArrayList<>(ctxs.size());
146 effectOfStatement.addAll(ctxs);
150 public final CopyHistory history() {
155 final byte executionOrder() {
156 return executionOrder;
159 // FIXME: this should be propagated through a correct constructor
161 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
162 this.executionOrder = completedPhase.executionOrder();
166 public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
167 final Class<@NonNull N> type, final T key, final U value) {
168 addToNamespace(type, key, value);
171 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
172 final List<ReactorStmtCtx<?, ?, ?>> effective) {
173 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
176 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
177 return effective.isEmpty() ? ImmutableList.of() : effective;
180 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
182 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
183 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
184 if (effective.isEmpty()) {
188 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
189 while (iterator.hasNext()) {
190 final StmtContext<?, ?, ?> next = iterator.next();
191 if (statementDef.equals(next.publicDefinition())) {
196 return shrinkEffective(effective);
200 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
201 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
202 * definition and statement argument match with one of the effective substatements' statement definition
206 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
208 * @param statementDef statement definition of the statement context to remove
209 * @param statementArg statement argument of the statement context to remove
211 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
212 String statementArg);
214 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
215 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
216 final String statementArg) {
217 if (statementArg == null) {
218 return removeStatementFromEffectiveSubstatements(effective, statementDef);
221 if (effective.isEmpty()) {
225 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
226 while (iterator.hasNext()) {
227 final Mutable<?, ?, ?> next = iterator.next();
228 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
233 return shrinkEffective(effective);
236 // YANG example: RPC/action statements always have 'input' and 'output' defined
238 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
239 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
240 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
241 // StatementContextBase subclass.
242 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
243 ImplicitSubstatement.of(sourceReference()), rawArg);
244 support.onStatementAdded(ret);
245 addEffectiveSubstatement(ret);
250 * Adds an effective statement to collection of substatements.
252 * @param substatement substatement
253 * @throws IllegalStateException if added in declared phase
254 * @throws NullPointerException if statement parameter is null
256 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
258 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
259 final Mutable<?, ?, ?> substatement) {
260 verifyStatement(substatement);
262 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
263 final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
264 ensureCompletedExecution(stmt);
270 * Adds an effective statement to collection of substatements.
272 * @param statements substatements
273 * @throws IllegalStateException
274 * if added in declared phase
275 * @throws NullPointerException
276 * if statement parameter is null
278 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
279 if (!statements.isEmpty()) {
280 statements.forEach(StatementContextBase::verifyStatement);
281 addEffectiveSubstatementsImpl(statements);
285 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
287 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
288 final Collection<? extends Mutable<?, ?, ?>> statements) {
289 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
290 final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
291 (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
292 if (executionOrder != ExecutionOrder.NULL) {
293 for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
294 ensureCompletedExecution(stmt, executionOrder);
298 resized.addAll(casted);
302 abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
304 // exposed for InferredStatementContext only
305 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
306 verifyStatement(stmt);
307 ensureCompletedExecution((ReactorStmtCtx<?, ?, ?>) stmt);
310 // Make sure target statement has transitioned at least to our phase (if we have one). This method is just before we
311 // take allow a statement to become our substatement. This is needed to ensure that every statement tree does not
312 // contain any statements which did not complete the same phase as the root statement.
313 private void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt) {
314 if (executionOrder != ExecutionOrder.NULL) {
315 ensureCompletedExecution(stmt, executionOrder);
319 private static void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt, final byte executionOrder) {
320 verify(stmt.tryToCompletePhase(executionOrder), "Statement %s cannot complete phase %s", stmt, executionOrder);
323 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
324 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
327 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
329 // We cannot allow statement to be further mutated.
330 // TODO: we really want to say 'not NULL and not at or after EFFECTIVE_MODEL here. This will matter if we have
331 // a phase after EFFECTIVE_MODEL
332 verify(executionOrder != ExecutionOrder.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
334 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
337 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
339 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
340 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
341 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
342 "Effective statement cannot be added in declared phase at: %s", sourceReference());
344 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
348 final E createEffective() {
349 final E result = createEffective(definition.getFactory());
350 if (result instanceof MutableStatement) {
351 getRoot().addMutableStmtToSeal((MutableStatement) result);
356 @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
357 return createEffective(factory, this);
360 // Creates EffectiveStatement through full materialization
361 static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
362 final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
363 return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
367 * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
368 * {@link StmtContext#buildEffective()} contract.
370 * @return Stream of supported declared statements.
372 // FIXME: we really want to unify this with streamEffective(), under its name
373 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared();
376 * Return a stream of inferred statements which can be built into an {@link EffectiveStatement}, as per
377 * {@link StmtContext#buildEffective()} contract.
379 * @return Stream of supported effective statements.
381 // FIXME: this method is currently a misnomer, but unifying with streamDeclared() would make this accurate again
382 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective();
385 final boolean doTryToCompletePhase(final byte targetOrder) {
386 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(targetOrder);
387 if (completeChildren(targetOrder) && finished) {
388 onPhaseCompleted(targetOrder);
394 private boolean completeChildren(final byte targetOrder) {
395 boolean finished = true;
396 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
397 finished &= child.tryToCompletePhase(targetOrder);
399 for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
400 finished &= child.tryToCompletePhase(targetOrder);
405 private boolean runMutations(final byte targetOrder) {
406 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(targetOrder));
407 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
408 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
411 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
412 boolean finished = true;
413 final Iterator<ContextMutation> it = openMutations.iterator();
414 while (it.hasNext()) {
415 final ContextMutation current = it.next();
416 if (current.isFinished()) {
423 if (openMutations.isEmpty()) {
424 phaseMutation.removeAll(phase);
425 cleanupPhaseMutation();
430 private void cleanupPhaseMutation() {
431 if (phaseMutation.isEmpty()) {
432 phaseMutation = ImmutableMultimap.of();
437 * Occurs on end of {@link ModelProcessingPhase} of source parsing. This method must not be called with
438 * {@code executionOrder} equal to {@link ExecutionOrder#NULL}.
440 * @param phase that was to be completed (finished)
441 * @throws SourceException when an error occurred in source parsing
443 private void onPhaseCompleted(final byte completedOrder) {
444 executionOrder = completedOrder;
445 if (completedOrder == ExecutionOrder.EFFECTIVE_MODEL) {
446 // We have completed effective model, substatements are guaranteed not to change
447 summarizeSubstatementPolicy();
450 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(completedOrder));
451 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
452 if (!listeners.isEmpty()) {
453 runPhaseListeners(phase, listeners);
457 private void summarizeSubstatementPolicy() {
458 if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
459 setAllSubstatementsContextIndependent();
464 * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
465 * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
466 * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
467 * considered copy-insensitive.
470 * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
472 * @return True if no substatements require copy-sensitive handling
474 abstract boolean noSensitiveSubstatements();
477 * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
478 * {@link #noSensitiveSubstatements()}.
480 * @param substatements Substatements to check
481 * @return True if no substatements require context-sensitive handling
483 static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
484 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
485 if (stmt.isSupportedToBuildEffective()) {
486 if (!stmt.allSubstatementsContextIndependent()) {
487 // This is a recursive property
491 switch (stmt.definition().support().copyPolicy()) {
492 case CONTEXT_INDEPENDENT:
504 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
505 final Iterator<OnPhaseFinished> listener = listeners.iterator();
506 while (listener.hasNext()) {
507 final OnPhaseFinished next = listener.next();
508 if (next.phaseFinished(this, phase)) {
513 if (listeners.isEmpty()) {
514 phaseListeners.removeAll(phase);
515 if (phaseListeners.isEmpty()) {
516 phaseListeners = ImmutableMultimap.of();
522 * Ends declared section of current node.
524 void endDeclared(final ModelProcessingPhase phase) {
525 definition.onDeclarationFinished(this, phase);
529 final StatementDefinitionContext<A, D, E> definition() {
533 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
534 final OnNamespaceItemAdded listener) {
535 final Object potential = getFromNamespace(type, key);
536 if (potential != null) {
537 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
538 listener.namespaceItemAdded(this, type, key, potential);
542 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
544 void onValueAdded(final Object value) {
545 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
550 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
551 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
552 final OnNamespaceItemAdded listener) {
553 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
554 if (existing.isPresent()) {
555 final Entry<K, V> entry = existing.get();
556 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
557 waitForPhase(entry.getValue(), type, phase, criterion, listener);
561 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
562 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
564 boolean onValueAdded(final K key, final V value) {
565 if (criterion.match(key)) {
566 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
567 waitForPhase(value, type, phase, criterion, listener);
576 final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
577 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
578 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
579 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
581 final Entry<K, V> match = optMatch.get();
582 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
585 final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
586 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
587 final OnNamespaceItemAdded listener) {
588 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
589 (context, phaseCompleted) -> {
590 selectMatch(type, criterion, listener);
595 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
596 final Class<N> type) {
597 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
598 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
601 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
604 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
605 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
609 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
610 * the listener is notified immediately.
612 * @param phase requested completion phase
613 * @param listener listener to invoke
614 * @throws NullPointerException if any of the arguments is null
616 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
617 requireNonNull(phase, "Statement context processing phase cannot be null");
618 requireNonNull(listener, "Statement context phase listener cannot be null");
620 ModelProcessingPhase finishedPhase = ModelProcessingPhase.ofExecutionOrder(executionOrder);
621 while (finishedPhase != null) {
622 if (phase.equals(finishedPhase)) {
623 listener.phaseFinished(this, finishedPhase);
626 finishedPhase = finishedPhase.getPreviousPhase();
628 if (phaseListeners.isEmpty()) {
629 phaseListeners = newMultimap();
632 phaseListeners.put(phase, listener);
636 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
638 * @throws IllegalStateException when the mutation was registered after phase was completed
640 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
641 checkState(executionOrder < phase.executionOrder(), "Mutation registered after phase was completed at: %s",
644 if (phaseMutation.isEmpty()) {
645 phaseMutation = newMultimap();
647 phaseMutation.put(phase, mutation);
650 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
651 if (!phaseMutation.isEmpty()) {
652 phaseMutation.remove(phase, mutation);
653 cleanupPhaseMutation();
658 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
659 final KT key,final StmtContext<?, ?, ?> stmt) {
660 addContextToNamespace(namespace, key, stmt);
664 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
665 final QNameModule targetModule) {
666 checkEffectiveModelCompleted(this);
667 return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
670 private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
671 final QNameModule targetModule) {
672 final StatementSupport<A, D, E> support = definition.support();
673 final CopyPolicy policy = support.copyPolicy();
676 return replicaAsChildOf(parent);
677 case CONTEXT_INDEPENDENT:
678 if (allSubstatementsContextIndependent()) {
679 return replicaAsChildOf(parent);
685 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
689 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
691 throw new IllegalStateException("Unhandled policy " + policy);
696 final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
697 final QNameModule targetModule) {
698 final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
700 // The statement fizzled, this should never happen, perhaps a verify()?
704 parent.ensureCompletedPhase(copy);
705 return canReuseCurrent(copy) ? this : copy;
708 private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
709 // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
710 // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
711 return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
712 && allSubstatementsContextIndependent();
716 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
717 final QNameModule targetModule) {
718 checkEffectiveModelCompleted(stmt);
719 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
720 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
723 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
724 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
725 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
726 original.publicDefinition());
728 final StatementContextBase<X, Y, Z> result;
729 final InferredStatementContext<X, Y, Z> copy;
731 if (implicitParent.isPresent()) {
732 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
733 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
734 original.argument(), type);
736 final CopyType childCopyType;
738 case ADDED_BY_AUGMENTATION:
739 childCopyType = CopyType.ORIGINAL;
741 case ADDED_BY_USES_AUGMENTATION:
742 childCopyType = CopyType.ADDED_BY_USES;
747 childCopyType = type;
750 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
751 result.addEffectiveSubstatement(copy);
753 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
756 original.definition.onStatementAdded(copy);
761 final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
762 return new ReplicaStatementContext<>(parent, this);
765 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
766 final ModelProcessingPhase phase = stmt.getCompletedPhase();
767 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
768 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
772 public final boolean hasImplicitParentSupport() {
773 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
777 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
778 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
779 original.publicDefinition());
780 if (optImplicit.isEmpty()) {
784 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
785 final CopyType type = original.history().getLastOperation();
786 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
787 original.sourceReference(), original.rawArgument(), original.argument(), type);
789 result.addEffectiveSubstatement(original.reparent(result));
790 result.setCompletedPhase(original.getCompletedPhase());
794 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
797 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
799 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
801 abstract boolean hasEmptySubstatements();