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 final CopyHistory history() {
157 public final 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<ReactorStmtCtx<?, ?, ?>> effective) {
175 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
178 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
179 return effective.isEmpty() ? ImmutableList.of() : effective;
182 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
184 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
185 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
186 if (effective.isEmpty()) {
190 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
191 while (iterator.hasNext()) {
192 final StmtContext<?, ?, ?> next = iterator.next();
193 if (statementDef.equals(next.publicDefinition())) {
198 return shrinkEffective(effective);
202 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
203 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
204 * definition and statement argument match with one of the effective substatements' statement definition
208 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
210 * @param statementDef statement definition of the statement context to remove
211 * @param statementArg statement argument of the statement context to remove
213 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
214 String statementArg);
216 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
217 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
218 final String statementArg) {
219 if (statementArg == null) {
220 return removeStatementFromEffectiveSubstatements(effective, statementDef);
223 if (effective.isEmpty()) {
227 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
228 while (iterator.hasNext()) {
229 final Mutable<?, ?, ?> next = iterator.next();
230 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
235 return shrinkEffective(effective);
238 // YANG example: RPC/action statements always have 'input' and 'output' defined
240 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
241 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
242 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
243 // StatementContextBase subclass.
244 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
245 ImplicitSubstatement.of(sourceReference()), rawArg);
246 support.onStatementAdded(ret);
247 addEffectiveSubstatement(ret);
252 * Adds an effective statement to collection of substatements.
254 * @param substatement substatement
255 * @throws IllegalStateException if added in declared phase
256 * @throws NullPointerException if statement parameter is null
258 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
260 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
261 final Mutable<?, ?, ?> substatement) {
262 verifyStatement(substatement);
264 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
265 final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
266 final ModelProcessingPhase phase = completedPhase;
268 ensureCompletedPhase(stmt, phase);
275 * Adds an effective statement to collection of substatements.
277 * @param statements substatements
278 * @throws IllegalStateException
279 * if added in declared phase
280 * @throws NullPointerException
281 * if statement parameter is null
283 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
284 if (!statements.isEmpty()) {
285 statements.forEach(StatementContextBase::verifyStatement);
286 addEffectiveSubstatementsImpl(statements);
290 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
292 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
293 final Collection<? extends Mutable<?, ?, ?>> statements) {
294 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
295 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
296 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
297 final ModelProcessingPhase phase = completedPhase;
299 for (StatementContextBase<?, ?, ?> stmt : casted) {
300 ensureCompletedPhase(stmt, phase);
304 resized.addAll(casted);
308 abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
310 // exposed for InferredStatementContext only
311 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
312 verifyStatement(stmt);
313 final ModelProcessingPhase phase = completedPhase;
315 ensureCompletedPhase((ReactorStmtCtx<?, ?, ?>) stmt, phase);
319 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
320 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
321 // any statements which did not complete the same phase as the root statement.
322 private static void ensureCompletedPhase(final ReactorStmtCtx<?, ?, ?> stmt, final ModelProcessingPhase phase) {
323 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
326 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
327 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
330 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
332 // We cannot allow statement to be further mutated
333 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
335 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
338 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
340 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
341 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
342 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
343 "Effective statement cannot be added in declared phase at: %s", sourceReference());
345 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
348 // Exposed for ReplicaStatementContext
350 E createEffective() {
351 return definition.getFactory().createEffective(this, streamDeclared(), streamEffective());
354 abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
356 abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
359 final boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
360 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
361 if (completeChildren(phase) && finished) {
362 onPhaseCompleted(phase);
368 private boolean completeChildren(final ModelProcessingPhase phase) {
369 boolean finished = true;
370 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
371 finished &= child.tryToCompletePhase(phase);
373 for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
374 finished &= child.tryToCompletePhase(phase);
379 private boolean runMutations(final ModelProcessingPhase phase) {
380 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
381 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
384 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
385 boolean finished = true;
386 final Iterator<ContextMutation> it = openMutations.iterator();
387 while (it.hasNext()) {
388 final ContextMutation current = it.next();
389 if (current.isFinished()) {
396 if (openMutations.isEmpty()) {
397 phaseMutation.removeAll(phase);
398 cleanupPhaseMutation();
403 private void cleanupPhaseMutation() {
404 if (phaseMutation.isEmpty()) {
405 phaseMutation = ImmutableMultimap.of();
410 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
413 * that was to be completed (finished)
414 * @throws SourceException
415 * when an error occurred in source parsing
417 private void onPhaseCompleted(final ModelProcessingPhase phase) {
418 completedPhase = phase;
420 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
421 if (!listeners.isEmpty()) {
422 runPhaseListeners(phase, listeners);
426 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
427 final Iterator<OnPhaseFinished> listener = listeners.iterator();
428 while (listener.hasNext()) {
429 final OnPhaseFinished next = listener.next();
430 if (next.phaseFinished(this, phase)) {
435 if (listeners.isEmpty()) {
436 phaseListeners.removeAll(phase);
437 if (phaseListeners.isEmpty()) {
438 phaseListeners = ImmutableMultimap.of();
444 * Ends declared section of current node.
446 void endDeclared(final ModelProcessingPhase phase) {
447 definition.onDeclarationFinished(this, phase);
451 final StatementDefinitionContext<A, D, E> definition() {
455 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
456 final OnNamespaceItemAdded listener) {
457 final Object potential = getFromNamespace(type, key);
458 if (potential != null) {
459 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
460 listener.namespaceItemAdded(this, type, key, potential);
464 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
466 void onValueAdded(final Object value) {
467 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
472 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
473 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
474 final OnNamespaceItemAdded listener) {
475 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
476 if (existing.isPresent()) {
477 final Entry<K, V> entry = existing.get();
478 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
479 waitForPhase(entry.getValue(), type, phase, criterion, listener);
483 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
484 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
486 boolean onValueAdded(final K key, final V value) {
487 if (criterion.match(key)) {
488 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
489 waitForPhase(value, type, phase, criterion, listener);
498 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
499 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
500 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
501 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
503 final Entry<K, V> match = optMatch.get();
504 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
507 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
508 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
509 final OnNamespaceItemAdded listener) {
510 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
511 (context, phaseCompleted) -> {
512 selectMatch(type, criterion, listener);
517 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
518 final Class<N> type) {
519 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
520 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
523 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
526 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
527 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
531 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
532 * the listener is notified immediately.
534 * @param phase requested completion phase
535 * @param listener listener to invoke
536 * @throws NullPointerException if any of the arguments is null
538 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
539 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", sourceReference());
540 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", sourceReference());
542 ModelProcessingPhase finishedPhase = completedPhase;
543 while (finishedPhase != null) {
544 if (phase.equals(finishedPhase)) {
545 listener.phaseFinished(this, finishedPhase);
548 finishedPhase = finishedPhase.getPreviousPhase();
550 if (phaseListeners.isEmpty()) {
551 phaseListeners = newMultimap();
554 phaseListeners.put(phase, listener);
558 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
560 * @throws IllegalStateException when the mutation was registered after phase was completed
562 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
563 ModelProcessingPhase finishedPhase = completedPhase;
564 while (finishedPhase != null) {
565 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
567 finishedPhase = finishedPhase.getPreviousPhase();
570 if (phaseMutation.isEmpty()) {
571 phaseMutation = newMultimap();
573 phaseMutation.put(phase, mutation);
576 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
577 if (!phaseMutation.isEmpty()) {
578 phaseMutation.remove(phase, mutation);
579 cleanupPhaseMutation();
584 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
585 final KT key,final StmtContext<?, ?, ?> stmt) {
586 addContextToNamespace(namespace, key, stmt);
590 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
591 final QNameModule targetModule) {
592 checkEffectiveModelCompleted(this);
594 final StatementSupport<A, D, E> support = definition.support();
595 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
597 case CONTEXT_INDEPENDENT:
598 if (hasEmptySubstatements()) {
599 // This statement is context-independent and has no substatements -- hence it can be freely shared.
600 return Optional.of(replicaAsChildOf(parent));
602 // ascertaining substatements could be quite costly, let's just fall through to declared copy and deal
603 // shortcut it when we build the statements.
606 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
607 // context, so that we can support building an effective statement without copying
608 // anything -- we will typically end up not being inferred against. In that case,
609 // this slim context should end up dealing with differences at buildContext()
610 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
611 // cannot be shared across instances).
612 return Optional.of(parent.childCopyOf(this, type, targetModule));
614 return Optional.empty();
616 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
618 throw new IllegalStateException("Unhandled policy " + policy);
623 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
624 final QNameModule targetModule) {
625 checkEffectiveModelCompleted(stmt);
626 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
627 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
630 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
631 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
632 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
633 original.publicDefinition());
635 final StatementContextBase<X, Y, Z> result;
636 final InferredStatementContext<X, Y, Z> copy;
638 if (implicitParent.isPresent()) {
639 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
640 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
641 original.argument(), type);
643 final CopyType childCopyType;
645 case ADDED_BY_AUGMENTATION:
646 childCopyType = CopyType.ORIGINAL;
648 case ADDED_BY_USES_AUGMENTATION:
649 childCopyType = CopyType.ADDED_BY_USES;
654 childCopyType = type;
657 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
658 result.addEffectiveSubstatement(copy);
660 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
663 original.definition.onStatementAdded(copy);
668 public final ReactorStmtCtx<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
669 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
670 return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
673 final @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> stmt) {
674 return new ReplicaStatementContext<>(stmt, this);
677 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
678 final ModelProcessingPhase phase = stmt.getCompletedPhase();
679 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
680 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
684 public final boolean hasImplicitParentSupport() {
685 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
689 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
690 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
691 original.publicDefinition());
692 if (optImplicit.isEmpty()) {
696 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
697 final CopyType type = original.history().getLastOperation();
698 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
699 original.sourceReference(), original.rawArgument(), original.argument(), type);
701 result.addEffectiveSubstatement(original.reparent(result));
702 result.setCompletedPhase(original.getCompletedPhase());
706 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
709 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
711 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
713 abstract boolean hasEmptySubstatements();