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.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
13 import static com.google.common.base.Verify.verify;
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.eclipse.jdt.annotation.Nullable;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
36 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
38 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
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.StatementNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
51 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
52 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
53 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
54 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * Core reactor statement implementation of {@link Mutable}.
61 * @param <A> Argument type
62 * @param <D> Declared Statement representation
63 * @param <E> Effective Statement representation
65 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
66 extends ReactorStmtCtx<A, D, E> {
68 * Event listener when an item is added to model namespace.
70 interface OnNamespaceItemAdded extends EventListener {
72 * Invoked whenever a new item is added to a namespace.
74 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
78 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
80 interface OnPhaseFinished extends EventListener {
82 * Invoked whenever a processing phase has finished.
84 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
88 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
90 interface ContextMutation {
95 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
97 private final CopyHistory copyHistory;
98 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
99 // operations, hence we want to keep it close by.
100 private final @NonNull StatementDefinitionContext<A, D, E> definition;
102 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
103 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
105 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
107 private @Nullable ModelProcessingPhase completedPhase;
109 // Copy constructor used by subclasses to implement reparent()
110 StatementContextBase(final StatementContextBase<A, D, E> original) {
112 this.copyHistory = original.copyHistory;
113 this.definition = original.definition;
114 this.completedPhase = original.completedPhase;
117 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
118 this.definition = requireNonNull(def);
119 this.copyHistory = CopyHistory.original();
122 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
123 this.definition = requireNonNull(def);
124 this.copyHistory = requireNonNull(copyHistory);
128 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
129 return effectOfStatement;
133 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
134 if (effectOfStatement.isEmpty()) {
135 effectOfStatement = new ArrayList<>(1);
137 effectOfStatement.add(ctx);
141 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
142 if (ctxs.isEmpty()) {
146 if (effectOfStatement.isEmpty()) {
147 effectOfStatement = new ArrayList<>(ctxs.size());
149 effectOfStatement.addAll(ctxs);
153 public final CopyHistory history() {
158 public final ModelProcessingPhase getCompletedPhase() {
159 return completedPhase;
162 // FIXME: this should be propagated through a correct constructor
164 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
165 this.completedPhase = completedPhase;
169 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
170 final Class<@NonNull N> type, final T key, final U value) {
171 addToNamespace(type, key, value);
174 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
175 final List<ReactorStmtCtx<?, ?, ?>> effective) {
176 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
179 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
180 return effective.isEmpty() ? ImmutableList.of() : effective;
183 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
185 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
186 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
187 if (effective.isEmpty()) {
191 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
192 while (iterator.hasNext()) {
193 final StmtContext<?, ?, ?> next = iterator.next();
194 if (statementDef.equals(next.publicDefinition())) {
199 return shrinkEffective(effective);
203 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
204 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
205 * definition and statement argument match with one of the effective substatements' statement definition
209 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
211 * @param statementDef statement definition of the statement context to remove
212 * @param statementArg statement argument of the statement context to remove
214 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
215 String statementArg);
217 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
218 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
219 final String statementArg) {
220 if (statementArg == null) {
221 return removeStatementFromEffectiveSubstatements(effective, statementDef);
224 if (effective.isEmpty()) {
228 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
229 while (iterator.hasNext()) {
230 final Mutable<?, ?, ?> next = iterator.next();
231 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
236 return shrinkEffective(effective);
239 // YANG example: RPC/action statements always have 'input' and 'output' defined
241 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
242 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
243 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
244 // StatementContextBase subclass.
245 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
246 ImplicitSubstatement.of(sourceReference()), rawArg);
247 support.onStatementAdded(ret);
248 addEffectiveSubstatement(ret);
253 * Adds an effective statement to collection of substatements.
255 * @param substatement substatement
256 * @throws IllegalStateException if added in declared phase
257 * @throws NullPointerException if statement parameter is null
259 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
261 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
262 final Mutable<?, ?, ?> substatement) {
263 verifyStatement(substatement);
265 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
266 final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
267 final ModelProcessingPhase phase = completedPhase;
269 ensureCompletedPhase(stmt, phase);
276 * Adds an effective statement to collection of substatements.
278 * @param statements substatements
279 * @throws IllegalStateException
280 * if added in declared phase
281 * @throws NullPointerException
282 * if statement parameter is null
284 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
285 if (!statements.isEmpty()) {
286 statements.forEach(StatementContextBase::verifyStatement);
287 addEffectiveSubstatementsImpl(statements);
291 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
293 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
294 final Collection<? extends Mutable<?, ?, ?>> statements) {
295 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
296 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
297 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
298 final ModelProcessingPhase phase = completedPhase;
300 for (StatementContextBase<?, ?, ?> stmt : casted) {
301 ensureCompletedPhase(stmt, phase);
305 resized.addAll(casted);
309 abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
311 // exposed for InferredStatementContext only
312 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
313 verifyStatement(stmt);
314 final ModelProcessingPhase phase = completedPhase;
316 ensureCompletedPhase((ReactorStmtCtx<?, ?, ?>) stmt, phase);
320 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
321 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
322 // any statements which did not complete the same phase as the root statement.
323 private static void ensureCompletedPhase(final ReactorStmtCtx<?, ?, ?> stmt, final ModelProcessingPhase phase) {
324 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
327 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
328 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
331 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
333 // We cannot allow statement to be further mutated
334 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
336 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
339 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
341 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
342 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
343 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
344 "Effective statement cannot be added in declared phase at: %s", sourceReference());
346 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
351 final E createEffective() {
352 final E result = definition.getFactory().createEffective(this, streamDeclared(), streamEffective());
353 if (result instanceof MutableStatement) {
354 getRoot().addMutableStmtToSeal((MutableStatement) result);
359 abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
361 abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
364 final boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
365 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
366 if (completeChildren(phase) && finished) {
367 onPhaseCompleted(phase);
373 private boolean completeChildren(final ModelProcessingPhase phase) {
374 boolean finished = true;
375 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
376 finished &= child.tryToCompletePhase(phase);
378 for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
379 finished &= child.tryToCompletePhase(phase);
384 private boolean runMutations(final ModelProcessingPhase phase) {
385 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
386 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
389 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
390 boolean finished = true;
391 final Iterator<ContextMutation> it = openMutations.iterator();
392 while (it.hasNext()) {
393 final ContextMutation current = it.next();
394 if (current.isFinished()) {
401 if (openMutations.isEmpty()) {
402 phaseMutation.removeAll(phase);
403 cleanupPhaseMutation();
408 private void cleanupPhaseMutation() {
409 if (phaseMutation.isEmpty()) {
410 phaseMutation = ImmutableMultimap.of();
415 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
418 * that was to be completed (finished)
419 * @throws SourceException
420 * when an error occurred in source parsing
422 private void onPhaseCompleted(final ModelProcessingPhase phase) {
423 completedPhase = phase;
425 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
426 if (!listeners.isEmpty()) {
427 runPhaseListeners(phase, listeners);
431 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
432 final Iterator<OnPhaseFinished> listener = listeners.iterator();
433 while (listener.hasNext()) {
434 final OnPhaseFinished next = listener.next();
435 if (next.phaseFinished(this, phase)) {
440 if (listeners.isEmpty()) {
441 phaseListeners.removeAll(phase);
442 if (phaseListeners.isEmpty()) {
443 phaseListeners = ImmutableMultimap.of();
449 * Ends declared section of current node.
451 void endDeclared(final ModelProcessingPhase phase) {
452 definition.onDeclarationFinished(this, phase);
456 final StatementDefinitionContext<A, D, E> definition() {
460 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
461 final OnNamespaceItemAdded listener) {
462 final Object potential = getFromNamespace(type, key);
463 if (potential != null) {
464 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
465 listener.namespaceItemAdded(this, type, key, potential);
469 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
471 void onValueAdded(final Object value) {
472 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
477 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
478 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
479 final OnNamespaceItemAdded listener) {
480 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
481 if (existing.isPresent()) {
482 final Entry<K, V> entry = existing.get();
483 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
484 waitForPhase(entry.getValue(), type, phase, criterion, listener);
488 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
489 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
491 boolean onValueAdded(final K key, final V value) {
492 if (criterion.match(key)) {
493 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
494 waitForPhase(value, type, phase, criterion, listener);
503 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
504 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
505 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
506 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
508 final Entry<K, V> match = optMatch.get();
509 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
512 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
513 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
514 final OnNamespaceItemAdded listener) {
515 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
516 (context, phaseCompleted) -> {
517 selectMatch(type, criterion, listener);
522 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
523 final Class<N> type) {
524 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
525 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
528 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
531 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
532 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
536 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
537 * the listener is notified immediately.
539 * @param phase requested completion phase
540 * @param listener listener to invoke
541 * @throws NullPointerException if any of the arguments is null
543 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
544 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", sourceReference());
545 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", sourceReference());
547 ModelProcessingPhase finishedPhase = completedPhase;
548 while (finishedPhase != null) {
549 if (phase.equals(finishedPhase)) {
550 listener.phaseFinished(this, finishedPhase);
553 finishedPhase = finishedPhase.getPreviousPhase();
555 if (phaseListeners.isEmpty()) {
556 phaseListeners = newMultimap();
559 phaseListeners.put(phase, listener);
563 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
565 * @throws IllegalStateException when the mutation was registered after phase was completed
567 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
568 ModelProcessingPhase finishedPhase = completedPhase;
569 while (finishedPhase != null) {
570 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
572 finishedPhase = finishedPhase.getPreviousPhase();
575 if (phaseMutation.isEmpty()) {
576 phaseMutation = newMultimap();
578 phaseMutation.put(phase, mutation);
581 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
582 if (!phaseMutation.isEmpty()) {
583 phaseMutation.remove(phase, mutation);
584 cleanupPhaseMutation();
589 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
590 final KT key,final StmtContext<?, ?, ?> stmt) {
591 addContextToNamespace(namespace, key, stmt);
595 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
596 final QNameModule targetModule) {
597 checkEffectiveModelCompleted(this);
599 final StatementSupport<A, D, E> support = definition.support();
600 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
602 case CONTEXT_INDEPENDENT:
603 if (hasEmptySubstatements()) {
604 // This statement is context-independent and has no substatements -- hence it can be freely shared.
605 return Optional.of(replicaAsChildOf(parent));
607 // ascertaining substatements could be quite costly, let's just fall through to declared copy and deal
608 // shortcut it when we build the statements.
611 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
612 // context, so that we can support building an effective statement without copying
613 // anything -- we will typically end up not being inferred against. In that case,
614 // this slim context should end up dealing with differences at buildContext()
615 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
616 // cannot be shared across instances).
617 return Optional.of(parent.childCopyOf(this, type, targetModule));
619 return Optional.empty();
621 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
623 throw new IllegalStateException("Unhandled policy " + policy);
628 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
629 final QNameModule targetModule) {
630 checkEffectiveModelCompleted(stmt);
631 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
632 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
635 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
636 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
637 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
638 original.publicDefinition());
640 final StatementContextBase<X, Y, Z> result;
641 final InferredStatementContext<X, Y, Z> copy;
643 if (implicitParent.isPresent()) {
644 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
645 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
646 original.argument(), type);
648 final CopyType childCopyType;
650 case ADDED_BY_AUGMENTATION:
651 childCopyType = CopyType.ORIGINAL;
653 case ADDED_BY_USES_AUGMENTATION:
654 childCopyType = CopyType.ADDED_BY_USES;
659 childCopyType = type;
662 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
663 result.addEffectiveSubstatement(copy);
665 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
668 original.definition.onStatementAdded(copy);
673 public final ReactorStmtCtx<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
674 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
675 return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
678 final @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> stmt) {
679 return new ReplicaStatementContext<>(stmt, this);
682 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
683 final ModelProcessingPhase phase = stmt.getCompletedPhase();
684 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
685 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
689 public final boolean hasImplicitParentSupport() {
690 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
694 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
695 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
696 original.publicDefinition());
697 if (optImplicit.isEmpty()) {
701 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
702 final CopyType type = original.history().getLastOperation();
703 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
704 original.sourceReference(), original.rawArgument(), original.argument(), type);
706 result.addEffectiveSubstatement(original.reparent(result));
707 result.setCompletedPhase(original.getCompletedPhase());
711 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
714 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
716 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
718 abstract boolean hasEmptySubstatements();