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.NamespaceBehaviour;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
51 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
52 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
53 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * Core reactor statement implementation of {@link Mutable}.
60 * @param <A> Argument type
61 * @param <D> Declared Statement representation
62 * @param <E> Effective Statement representation
64 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
65 extends ReactorStmtCtx<A, D, E> {
67 * Event listener when an item is added to model namespace.
69 interface OnNamespaceItemAdded extends EventListener {
71 * Invoked whenever a new item is added to a namespace.
73 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
77 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
79 interface OnPhaseFinished extends EventListener {
81 * Invoked whenever a processing phase has finished.
83 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
87 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
89 interface ContextMutation {
94 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
96 private final CopyHistory copyHistory;
97 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
98 // operations, hence we want to keep it close by.
99 private final @NonNull StatementDefinitionContext<A, D, E> definition;
101 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
102 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
104 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
106 private @Nullable ModelProcessingPhase completedPhase;
108 // Copy constructor used by subclasses to implement reparent()
109 StatementContextBase(final StatementContextBase<A, D, E> original) {
111 this.copyHistory = original.copyHistory;
112 this.definition = original.definition;
113 this.completedPhase = original.completedPhase;
116 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
117 this.definition = requireNonNull(def);
118 this.copyHistory = CopyHistory.original();
121 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
122 this.definition = requireNonNull(def);
123 this.copyHistory = requireNonNull(copyHistory);
127 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
128 return effectOfStatement;
132 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
133 if (effectOfStatement.isEmpty()) {
134 effectOfStatement = new ArrayList<>(1);
136 effectOfStatement.add(ctx);
140 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
141 if (ctxs.isEmpty()) {
145 if (effectOfStatement.isEmpty()) {
146 effectOfStatement = new ArrayList<>(ctxs.size());
148 effectOfStatement.addAll(ctxs);
152 public CopyHistory getCopyHistory() {
157 public ModelProcessingPhase getCompletedPhase() {
158 return completedPhase;
161 // FIXME: this should be propagated through a correct constructor
163 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
164 this.completedPhase = completedPhase;
168 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
169 final Class<@NonNull N> type, final T key, final U value) {
170 addToNamespace(type, key, value);
173 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
174 final List<StatementContextBase<?, ?, ?>> effective) {
175 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
178 private static List<StatementContextBase<?, ?, ?>> shrinkEffective(
179 final List<StatementContextBase<?, ?, ?>> effective) {
180 return effective.isEmpty() ? ImmutableList.of() : effective;
183 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
185 static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
186 final List<StatementContextBase<?, ?, ?>> 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<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
218 final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef,
219 final String statementArg) {
220 if (statementArg == null) {
221 return removeStatementFromEffectiveSubstatements(effective, statementDef);
224 if (effective.isEmpty()) {
228 final Iterator<StatementContextBase<?, ?, ?>> 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<StatementContextBase<?, ?, ?>> addEffectiveSubstatement(
262 final List<StatementContextBase<?, ?, ?>> effective, final Mutable<?, ?, ?> substatement) {
263 verifyStatement(substatement);
265 final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
266 final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) 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<StatementContextBase<?, ?, ?>> addEffectiveSubstatementsImpl(
294 final List<StatementContextBase<?, ?, ?>> effective,
295 final Collection<? extends Mutable<?, ?, ?>> statements) {
296 final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
297 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
298 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
299 final ModelProcessingPhase phase = completedPhase;
301 for (StatementContextBase<?, ?, ?> stmt : casted) {
302 ensureCompletedPhase(stmt, phase);
306 resized.addAll(casted);
310 abstract Iterable<StatementContextBase<?, ?, ?>> effectiveChildrenToComplete();
312 // exposed for InferredStatementContext only
313 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
314 verifyStatement(stmt);
315 final ModelProcessingPhase phase = completedPhase;
317 ensureCompletedPhase((StatementContextBase<?, ?, ?>) stmt, phase);
321 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
322 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
323 // any statements which did not complete the same phase as the root statement.
324 private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
325 final ModelProcessingPhase phase) {
326 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
329 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
330 verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
333 private List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatement(
334 final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
335 // We cannot allow statement to be further mutated
336 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
338 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
341 final List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatementUnsafe(
342 final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
343 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
344 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
345 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
346 "Effective statement cannot be added in declared phase at: %s", sourceReference());
348 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
351 // Exposed for ReplicaStatementContext
353 E createEffective() {
354 return definition.getFactory().createEffective(new BaseCurrentEffectiveStmtCtx<>(this), streamDeclared(),
358 abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
360 abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
363 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
364 * this method does nothing.
366 * @param phase to be executed (completed)
367 * @return true if phase was successfully completed
368 * @throws SourceException when an error occurred in source parsing
370 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
371 return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
374 private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
375 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
376 if (completeChildren(phase) && finished) {
377 onPhaseCompleted(phase);
383 private boolean completeChildren(final ModelProcessingPhase phase) {
384 boolean finished = true;
385 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
386 finished &= child.tryToCompletePhase(phase);
388 for (final StatementContextBase<?, ?, ?> child : effectiveChildrenToComplete()) {
389 finished &= child.tryToCompletePhase(phase);
394 private boolean runMutations(final ModelProcessingPhase phase) {
395 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
396 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
399 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
400 boolean finished = true;
401 final Iterator<ContextMutation> it = openMutations.iterator();
402 while (it.hasNext()) {
403 final ContextMutation current = it.next();
404 if (current.isFinished()) {
411 if (openMutations.isEmpty()) {
412 phaseMutation.removeAll(phase);
413 cleanupPhaseMutation();
418 private void cleanupPhaseMutation() {
419 if (phaseMutation.isEmpty()) {
420 phaseMutation = ImmutableMultimap.of();
425 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
428 * that was to be completed (finished)
429 * @throws SourceException
430 * when an error occurred in source parsing
432 private void onPhaseCompleted(final ModelProcessingPhase phase) {
433 completedPhase = phase;
435 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
436 if (!listeners.isEmpty()) {
437 runPhaseListeners(phase, listeners);
441 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
442 final Iterator<OnPhaseFinished> listener = listeners.iterator();
443 while (listener.hasNext()) {
444 final OnPhaseFinished next = listener.next();
445 if (next.phaseFinished(this, phase)) {
450 if (listeners.isEmpty()) {
451 phaseListeners.removeAll(phase);
452 if (phaseListeners.isEmpty()) {
453 phaseListeners = ImmutableMultimap.of();
459 * Ends declared section of current node.
461 void endDeclared(final ModelProcessingPhase phase) {
462 definition.onDeclarationFinished(this, phase);
466 final StatementDefinitionContext<A, D, E> definition() {
470 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
471 final OnNamespaceItemAdded listener) {
472 final Object potential = getFromNamespace(type, key);
473 if (potential != null) {
474 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
475 listener.namespaceItemAdded(this, type, key, potential);
479 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
481 void onValueAdded(final Object value) {
482 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
487 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
488 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
489 final OnNamespaceItemAdded listener) {
490 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
491 if (existing.isPresent()) {
492 final Entry<K, V> entry = existing.get();
493 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
494 waitForPhase(entry.getValue(), type, phase, criterion, listener);
498 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
499 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
501 boolean onValueAdded(final K key, final V value) {
502 if (criterion.match(key)) {
503 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
504 waitForPhase(value, type, phase, criterion, listener);
513 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
514 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
515 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
516 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
518 final Entry<K, V> match = optMatch.get();
519 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
522 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
523 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
524 final OnNamespaceItemAdded listener) {
525 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
526 (context, phaseCompleted) -> {
527 selectMatch(type, criterion, listener);
532 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
533 final Class<N> type) {
534 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
535 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
538 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
541 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
542 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
546 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
547 * the listener is notified immediately.
549 * @param phase requested completion phase
550 * @param listener listener to invoke
551 * @throws NullPointerException if any of the arguments is null
553 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
554 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", sourceReference());
555 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", sourceReference());
557 ModelProcessingPhase finishedPhase = completedPhase;
558 while (finishedPhase != null) {
559 if (phase.equals(finishedPhase)) {
560 listener.phaseFinished(this, finishedPhase);
563 finishedPhase = finishedPhase.getPreviousPhase();
565 if (phaseListeners.isEmpty()) {
566 phaseListeners = newMultimap();
569 phaseListeners.put(phase, listener);
573 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
575 * @throws IllegalStateException when the mutation was registered after phase was completed
577 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
578 ModelProcessingPhase finishedPhase = completedPhase;
579 while (finishedPhase != null) {
580 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
582 finishedPhase = finishedPhase.getPreviousPhase();
585 if (phaseMutation.isEmpty()) {
586 phaseMutation = newMultimap();
588 phaseMutation.put(phase, mutation);
591 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
592 if (!phaseMutation.isEmpty()) {
593 phaseMutation.remove(phase, mutation);
594 cleanupPhaseMutation();
599 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
600 final KT key,final StmtContext<?, ?, ?> stmt) {
601 addContextToNamespace(namespace, key, stmt);
605 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
606 final QNameModule targetModule) {
607 checkEffectiveModelCompleted(this);
609 final StatementSupport<A, D, E> support = definition.support();
610 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
612 case CONTEXT_INDEPENDENT:
613 if (hasEmptySubstatements()) {
614 // This statement is context-independent and has no substatements -- hence it can be freely shared.
615 return Optional.of(replicaAsChildOf(parent));
617 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
620 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
621 // context, so that we can support building an effective statement without copying
622 // anything -- we will typically end up not being inferred against. In that case,
623 // this slim context should end up dealing with differences at buildContext()
624 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
625 // cannot be shared across instances).
626 return Optional.of(parent.childCopyOf(this, type, targetModule));
628 return Optional.empty();
630 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
632 throw new IllegalStateException("Unhandled policy " + policy);
637 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
638 final QNameModule targetModule) {
639 checkEffectiveModelCompleted(stmt);
640 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
641 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
644 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
645 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
646 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
647 original.publicDefinition());
649 final StatementContextBase<X, Y, Z> result;
650 final InferredStatementContext<X, Y, Z> copy;
652 if (implicitParent.isPresent()) {
653 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
654 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
655 original.argument(), type);
657 final CopyType childCopyType;
659 case ADDED_BY_AUGMENTATION:
660 childCopyType = CopyType.ORIGINAL;
662 case ADDED_BY_USES_AUGMENTATION:
663 childCopyType = CopyType.ADDED_BY_USES;
668 childCopyType = type;
671 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
672 result.addEffectiveSubstatement(copy);
674 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
677 original.definition.onStatementAdded(copy);
682 public final StatementContextBase<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
683 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
684 return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
687 final @NonNull StatementContextBase<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> stmt) {
688 return new ReplicaStatementContext<>(stmt, this);
691 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
692 final ModelProcessingPhase phase = stmt.getCompletedPhase();
693 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
694 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
698 public final boolean hasImplicitParentSupport() {
699 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
703 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
704 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
705 original.publicDefinition());
706 if (optImplicit.isEmpty()) {
710 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
711 final CopyType type = original.getCopyHistory().getLastOperation();
712 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
713 original.sourceReference(), original.rawArgument(), original.argument(), type);
715 result.addEffectiveSubstatement(original.reparent(result));
716 result.setCompletedPhase(original.getCompletedPhase());
720 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
723 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
725 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
727 abstract boolean hasEmptySubstatements();