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.StatementDefinition;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.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 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
104 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
106 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
108 private @Nullable ModelProcessingPhase completedPhase;
110 // Copy constructor used by subclasses to implement reparent()
111 StatementContextBase(final StatementContextBase<A, D, E> original) {
113 this.copyHistory = original.copyHistory;
114 this.definition = original.definition;
115 this.completedPhase = original.completedPhase;
118 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
119 this.definition = requireNonNull(def);
120 this.copyHistory = CopyHistory.original();
123 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
124 this.definition = requireNonNull(def);
125 this.copyHistory = requireNonNull(copyHistory);
129 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
130 return effectOfStatement;
134 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
135 if (ctxs.isEmpty()) {
139 if (effectOfStatement.isEmpty()) {
140 effectOfStatement = new ArrayList<>(ctxs.size());
142 effectOfStatement.addAll(ctxs);
146 public final CopyHistory history() {
151 public final ModelProcessingPhase getCompletedPhase() {
152 return completedPhase;
155 // FIXME: this should be propagated through a correct constructor
157 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
158 this.completedPhase = completedPhase;
162 public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
163 final Class<@NonNull N> type, final T key, final U value) {
164 addToNamespace(type, key, value);
167 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
168 final List<ReactorStmtCtx<?, ?, ?>> effective) {
169 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
172 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
173 return effective.isEmpty() ? ImmutableList.of() : effective;
176 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
178 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
179 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
180 if (effective.isEmpty()) {
184 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
185 while (iterator.hasNext()) {
186 final StmtContext<?, ?, ?> next = iterator.next();
187 if (statementDef.equals(next.publicDefinition())) {
192 return shrinkEffective(effective);
196 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
197 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
198 * definition and statement argument match with one of the effective substatements' statement definition
202 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
204 * @param statementDef statement definition of the statement context to remove
205 * @param statementArg statement argument of the statement context to remove
207 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
208 String statementArg);
210 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
211 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
212 final String statementArg) {
213 if (statementArg == null) {
214 return removeStatementFromEffectiveSubstatements(effective, statementDef);
217 if (effective.isEmpty()) {
221 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
222 while (iterator.hasNext()) {
223 final Mutable<?, ?, ?> next = iterator.next();
224 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
229 return shrinkEffective(effective);
232 // YANG example: RPC/action statements always have 'input' and 'output' defined
234 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
235 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
236 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
237 // StatementContextBase subclass.
238 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
239 ImplicitSubstatement.of(sourceReference()), rawArg);
240 support.onStatementAdded(ret);
241 addEffectiveSubstatement(ret);
246 * Adds an effective statement to collection of substatements.
248 * @param substatement substatement
249 * @throws IllegalStateException if added in declared phase
250 * @throws NullPointerException if statement parameter is null
252 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
254 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
255 final Mutable<?, ?, ?> substatement) {
256 verifyStatement(substatement);
258 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
259 final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
260 final ModelProcessingPhase phase = completedPhase;
262 ensureCompletedPhase(stmt, phase);
269 * Adds an effective statement to collection of substatements.
271 * @param statements substatements
272 * @throws IllegalStateException
273 * if added in declared phase
274 * @throws NullPointerException
275 * if statement parameter is null
277 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
278 if (!statements.isEmpty()) {
279 statements.forEach(StatementContextBase::verifyStatement);
280 addEffectiveSubstatementsImpl(statements);
284 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
286 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
287 final Collection<? extends Mutable<?, ?, ?>> statements) {
288 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
289 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
290 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
291 final ModelProcessingPhase phase = completedPhase;
293 for (StatementContextBase<?, ?, ?> stmt : casted) {
294 ensureCompletedPhase(stmt, phase);
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 final ModelProcessingPhase phase = completedPhase;
309 ensureCompletedPhase((ReactorStmtCtx<?, ?, ?>) stmt, phase);
313 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
314 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
315 // any statements which did not complete the same phase as the root statement.
316 private static void ensureCompletedPhase(final ReactorStmtCtx<?, ?, ?> stmt, final ModelProcessingPhase phase) {
317 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
320 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
321 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
324 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
326 // We cannot allow statement to be further mutated
327 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
329 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
332 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
334 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
335 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
336 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
337 "Effective statement cannot be added in declared phase at: %s", sourceReference());
339 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
343 final E createEffective() {
344 final E result = createEffective(definition.getFactory());
345 if (result instanceof MutableStatement) {
346 getRoot().addMutableStmtToSeal((MutableStatement) result);
351 @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
352 return createEffective(factory, this);
355 // Creates EffectiveStatement through full materialization
356 static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
357 final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
358 return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
361 abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
363 abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
366 final boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
367 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
368 if (completeChildren(phase) && finished) {
369 onPhaseCompleted(phase);
375 private boolean completeChildren(final ModelProcessingPhase phase) {
376 boolean finished = true;
377 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
378 finished &= child.tryToCompletePhase(phase);
380 for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
381 finished &= child.tryToCompletePhase(phase);
386 private boolean runMutations(final ModelProcessingPhase phase) {
387 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
388 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
391 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
392 boolean finished = true;
393 final Iterator<ContextMutation> it = openMutations.iterator();
394 while (it.hasNext()) {
395 final ContextMutation current = it.next();
396 if (current.isFinished()) {
403 if (openMutations.isEmpty()) {
404 phaseMutation.removeAll(phase);
405 cleanupPhaseMutation();
410 private void cleanupPhaseMutation() {
411 if (phaseMutation.isEmpty()) {
412 phaseMutation = ImmutableMultimap.of();
417 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
420 * that was to be completed (finished)
421 * @throws SourceException
422 * when an error occurred in source parsing
424 private void onPhaseCompleted(final ModelProcessingPhase phase) {
425 completedPhase = phase;
426 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
427 summarizeSubstatementPolicy();
430 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
431 if (!listeners.isEmpty()) {
432 runPhaseListeners(phase, listeners);
436 private void summarizeSubstatementPolicy() {
437 if (noSensitiveSubstatements()) {
438 setAllSubstatementsContextIndependent();
443 * Determine whether any substatements are context-sensitive as determined by {@link StatementSupport#copyPolicy()}.
444 * Only {@link CopyPolicy#CONTEXT_INDEPENDENT} and {@link CopyPolicy#IGNORE} are context-insensitive. Note that
445 * statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all considered
446 * context-insensitive.
449 * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
451 * @return True if no substatements require context-sensitive handling
453 abstract boolean noSensitiveSubstatements();
456 * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
457 * {@link #noSensitiveSubstatements()}.
459 * @param substatements Substatements to check
460 * @return True if no substatements require context-sensitive handling
462 static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
463 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
464 if (stmt.isSupportedToBuildEffective()) {
465 if (!stmt.allSubstatementsContextIndependent()) {
466 // This is a recursive property
470 switch (stmt.definition().support().copyPolicy()) {
471 case CONTEXT_INDEPENDENT:
482 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
483 final Iterator<OnPhaseFinished> listener = listeners.iterator();
484 while (listener.hasNext()) {
485 final OnPhaseFinished next = listener.next();
486 if (next.phaseFinished(this, phase)) {
491 if (listeners.isEmpty()) {
492 phaseListeners.removeAll(phase);
493 if (phaseListeners.isEmpty()) {
494 phaseListeners = ImmutableMultimap.of();
500 * Ends declared section of current node.
502 void endDeclared(final ModelProcessingPhase phase) {
503 definition.onDeclarationFinished(this, phase);
507 final StatementDefinitionContext<A, D, E> definition() {
511 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
512 final OnNamespaceItemAdded listener) {
513 final Object potential = getFromNamespace(type, key);
514 if (potential != null) {
515 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
516 listener.namespaceItemAdded(this, type, key, potential);
520 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
522 void onValueAdded(final Object value) {
523 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
528 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
529 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
530 final OnNamespaceItemAdded listener) {
531 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
532 if (existing.isPresent()) {
533 final Entry<K, V> entry = existing.get();
534 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
535 waitForPhase(entry.getValue(), type, phase, criterion, listener);
539 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
540 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
542 boolean onValueAdded(final K key, final V value) {
543 if (criterion.match(key)) {
544 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
545 waitForPhase(value, type, phase, criterion, listener);
554 final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
555 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
556 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
557 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
559 final Entry<K, V> match = optMatch.get();
560 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
563 final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
564 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
565 final OnNamespaceItemAdded listener) {
566 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
567 (context, phaseCompleted) -> {
568 selectMatch(type, criterion, listener);
573 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
574 final Class<N> type) {
575 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
576 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
579 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
582 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
583 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
587 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
588 * the listener is notified immediately.
590 * @param phase requested completion phase
591 * @param listener listener to invoke
592 * @throws NullPointerException if any of the arguments is null
594 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
595 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", sourceReference());
596 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", sourceReference());
598 ModelProcessingPhase finishedPhase = completedPhase;
599 while (finishedPhase != null) {
600 if (phase.equals(finishedPhase)) {
601 listener.phaseFinished(this, finishedPhase);
604 finishedPhase = finishedPhase.getPreviousPhase();
606 if (phaseListeners.isEmpty()) {
607 phaseListeners = newMultimap();
610 phaseListeners.put(phase, listener);
614 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
616 * @throws IllegalStateException when the mutation was registered after phase was completed
618 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
619 ModelProcessingPhase finishedPhase = completedPhase;
620 while (finishedPhase != null) {
621 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
623 finishedPhase = finishedPhase.getPreviousPhase();
626 if (phaseMutation.isEmpty()) {
627 phaseMutation = newMultimap();
629 phaseMutation.put(phase, mutation);
632 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
633 if (!phaseMutation.isEmpty()) {
634 phaseMutation.remove(phase, mutation);
635 cleanupPhaseMutation();
640 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
641 final KT key,final StmtContext<?, ?, ?> stmt) {
642 addContextToNamespace(namespace, key, stmt);
646 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
647 final QNameModule targetModule) {
648 checkEffectiveModelCompleted(this);
649 return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
652 private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
653 final QNameModule targetModule) {
654 final StatementSupport<A, D, E> support = definition.support();
655 final CopyPolicy policy = support.copyPolicy();
657 case CONTEXT_INDEPENDENT:
658 if (allSubstatementsContextIndependent()) {
659 return replicaAsChildOf(parent);
665 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
669 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
671 throw new IllegalStateException("Unhandled policy " + policy);
676 final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
677 final QNameModule targetModule) {
678 final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
680 // The statement fizzled, this should never happen, perhaps a verify()?
684 parent.ensureCompletedPhase(copy);
685 return canReuseCurrent(copy) ? replicaAsChildOf(parent) : copy;
688 private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
689 // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
690 // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
691 return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
692 && allSubstatementsContextIndependent();
696 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
697 final QNameModule targetModule) {
698 checkEffectiveModelCompleted(stmt);
699 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
700 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
703 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
704 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
705 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
706 original.publicDefinition());
708 final StatementContextBase<X, Y, Z> result;
709 final InferredStatementContext<X, Y, Z> copy;
711 if (implicitParent.isPresent()) {
712 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
713 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
714 original.argument(), type);
716 final CopyType childCopyType;
718 case ADDED_BY_AUGMENTATION:
719 childCopyType = CopyType.ORIGINAL;
721 case ADDED_BY_USES_AUGMENTATION:
722 childCopyType = CopyType.ADDED_BY_USES;
727 childCopyType = type;
730 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
731 result.addEffectiveSubstatement(copy);
733 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
736 original.definition.onStatementAdded(copy);
741 public final ReactorStmtCtx<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
742 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
743 return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
746 final @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> stmt) {
747 return new ReplicaStatementContext<>(stmt, this);
750 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
751 final ModelProcessingPhase phase = stmt.getCompletedPhase();
752 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
753 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
757 public final boolean hasImplicitParentSupport() {
758 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
762 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
763 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
764 original.publicDefinition());
765 if (optImplicit.isEmpty()) {
769 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
770 final CopyType type = original.history().getLastOperation();
771 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
772 original.sourceReference(), original.rawArgument(), original.argument(), type);
774 result.addEffectiveSubstatement(original.reparent(result));
775 result.setCompletedPhase(original.getCompletedPhase());
779 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
782 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
784 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
786 abstract boolean hasEmptySubstatements();