2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.annotations.Beta;
16 import com.google.common.collect.ImmutableCollection;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.ImmutableMultimap;
19 import com.google.common.collect.Multimap;
20 import com.google.common.collect.Multimaps;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.EnumMap;
25 import java.util.EventListener;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.Optional;
30 import java.util.stream.Stream;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.opendaylight.yangtools.yang.common.QNameModule;
34 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
35 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
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 Collection<? extends StmtContext<?, ?, ?>> ctxs) {
134 if (ctxs.isEmpty()) {
138 if (effectOfStatement.isEmpty()) {
139 effectOfStatement = new ArrayList<>(ctxs.size());
141 effectOfStatement.addAll(ctxs);
145 public final CopyHistory history() {
150 public final ModelProcessingPhase getCompletedPhase() {
151 return completedPhase;
154 // FIXME: this should be propagated through a correct constructor
156 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
157 this.completedPhase = completedPhase;
161 public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
162 final Class<@NonNull N> type, final T key, final U value) {
163 addToNamespace(type, key, value);
166 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
167 final List<ReactorStmtCtx<?, ?, ?>> effective) {
168 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
171 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
172 return effective.isEmpty() ? ImmutableList.of() : effective;
175 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
177 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
178 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
179 if (effective.isEmpty()) {
183 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
184 while (iterator.hasNext()) {
185 final StmtContext<?, ?, ?> next = iterator.next();
186 if (statementDef.equals(next.publicDefinition())) {
191 return shrinkEffective(effective);
195 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
196 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
197 * definition and statement argument match with one of the effective substatements' statement definition
201 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
203 * @param statementDef statement definition of the statement context to remove
204 * @param statementArg statement argument of the statement context to remove
206 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
207 String statementArg);
209 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
210 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
211 final String statementArg) {
212 if (statementArg == null) {
213 return removeStatementFromEffectiveSubstatements(effective, statementDef);
216 if (effective.isEmpty()) {
220 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
221 while (iterator.hasNext()) {
222 final Mutable<?, ?, ?> next = iterator.next();
223 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
228 return shrinkEffective(effective);
231 // YANG example: RPC/action statements always have 'input' and 'output' defined
233 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
234 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
235 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
236 // StatementContextBase subclass.
237 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
238 ImplicitSubstatement.of(sourceReference()), rawArg);
239 support.onStatementAdded(ret);
240 addEffectiveSubstatement(ret);
245 * Adds an effective statement to collection of substatements.
247 * @param substatement substatement
248 * @throws IllegalStateException if added in declared phase
249 * @throws NullPointerException if statement parameter is null
251 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
253 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
254 final Mutable<?, ?, ?> substatement) {
255 verifyStatement(substatement);
257 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
258 final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
259 final ModelProcessingPhase phase = completedPhase;
261 ensureCompletedPhase(stmt, phase);
268 * Adds an effective statement to collection of substatements.
270 * @param statements substatements
271 * @throws IllegalStateException
272 * if added in declared phase
273 * @throws NullPointerException
274 * if statement parameter is null
276 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
277 if (!statements.isEmpty()) {
278 statements.forEach(StatementContextBase::verifyStatement);
279 addEffectiveSubstatementsImpl(statements);
283 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
285 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
286 final Collection<? extends Mutable<?, ?, ?>> statements) {
287 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
288 final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
289 (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
290 final ModelProcessingPhase phase = completedPhase;
292 for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
293 ensureCompletedPhase(stmt, phase);
297 resized.addAll(casted);
301 abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
303 // exposed for InferredStatementContext only
304 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
305 verifyStatement(stmt);
306 final ModelProcessingPhase phase = completedPhase;
308 ensureCompletedPhase((ReactorStmtCtx<?, ?, ?>) stmt, phase);
312 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
313 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
314 // any statements which did not complete the same phase as the root statement.
315 private static void ensureCompletedPhase(final ReactorStmtCtx<?, ?, ?> stmt, final ModelProcessingPhase phase) {
316 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
319 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
320 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
323 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
325 // We cannot allow statement to be further mutated
326 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
328 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
331 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
333 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
334 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
335 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
336 "Effective statement cannot be added in declared phase at: %s", sourceReference());
338 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
342 final E createEffective() {
343 final E result = createEffective(definition.getFactory());
344 if (result instanceof MutableStatement) {
345 getRoot().addMutableStmtToSeal((MutableStatement) result);
350 @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
351 return createEffective(factory, this);
354 // Creates EffectiveStatement through full materialization
355 static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
356 final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
357 return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
361 * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
362 * {@link StmtContext#buildEffective()} contract.
364 * @return Stream of supported declared statements.
366 // FIXME: we really want to unify this with streamEffective(), under its name
367 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared();
370 * Return a stream of inferred statements which can be built into an {@link EffectiveStatement}, as per
371 * {@link StmtContext#buildEffective()} contract.
373 * @return Stream of supported effective statements.
375 // FIXME: this method is currently a misnomer, but unifying with streamDeclared() would make this accurate again
376 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective();
379 final boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
380 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
381 if (completeChildren(phase) && finished) {
382 onPhaseCompleted(phase);
388 private boolean completeChildren(final ModelProcessingPhase phase) {
389 boolean finished = true;
390 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
391 finished &= child.tryToCompletePhase(phase);
393 for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
394 finished &= child.tryToCompletePhase(phase);
399 private boolean runMutations(final ModelProcessingPhase phase) {
400 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
401 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
404 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
405 boolean finished = true;
406 final Iterator<ContextMutation> it = openMutations.iterator();
407 while (it.hasNext()) {
408 final ContextMutation current = it.next();
409 if (current.isFinished()) {
416 if (openMutations.isEmpty()) {
417 phaseMutation.removeAll(phase);
418 cleanupPhaseMutation();
423 private void cleanupPhaseMutation() {
424 if (phaseMutation.isEmpty()) {
425 phaseMutation = ImmutableMultimap.of();
430 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
433 * that was to be completed (finished)
434 * @throws SourceException
435 * when an error occurred in source parsing
437 private void onPhaseCompleted(final ModelProcessingPhase phase) {
438 completedPhase = phase;
439 if (phase == ModelProcessingPhase.EFFECTIVE_MODEL) {
440 summarizeSubstatementPolicy();
443 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
444 if (!listeners.isEmpty()) {
445 runPhaseListeners(phase, listeners);
449 private void summarizeSubstatementPolicy() {
450 if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
451 setAllSubstatementsContextIndependent();
456 * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
457 * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
458 * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
459 * considered copy-insensitive.
462 * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
464 * @return True if no substatements require copy-sensitive handling
466 abstract boolean noSensitiveSubstatements();
469 * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
470 * {@link #noSensitiveSubstatements()}.
472 * @param substatements Substatements to check
473 * @return True if no substatements require context-sensitive handling
475 static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
476 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
477 if (stmt.isSupportedToBuildEffective()) {
478 if (!stmt.allSubstatementsContextIndependent()) {
479 // This is a recursive property
483 switch (stmt.definition().support().copyPolicy()) {
484 case CONTEXT_INDEPENDENT:
496 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
497 final Iterator<OnPhaseFinished> listener = listeners.iterator();
498 while (listener.hasNext()) {
499 final OnPhaseFinished next = listener.next();
500 if (next.phaseFinished(this, phase)) {
505 if (listeners.isEmpty()) {
506 phaseListeners.removeAll(phase);
507 if (phaseListeners.isEmpty()) {
508 phaseListeners = ImmutableMultimap.of();
514 * Ends declared section of current node.
516 void endDeclared(final ModelProcessingPhase phase) {
517 definition.onDeclarationFinished(this, phase);
521 final StatementDefinitionContext<A, D, E> definition() {
525 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
526 final OnNamespaceItemAdded listener) {
527 final Object potential = getFromNamespace(type, key);
528 if (potential != null) {
529 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
530 listener.namespaceItemAdded(this, type, key, potential);
534 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
536 void onValueAdded(final Object value) {
537 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
542 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
543 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
544 final OnNamespaceItemAdded listener) {
545 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
546 if (existing.isPresent()) {
547 final Entry<K, V> entry = existing.get();
548 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
549 waitForPhase(entry.getValue(), type, phase, criterion, listener);
553 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
554 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
556 boolean onValueAdded(final K key, final V value) {
557 if (criterion.match(key)) {
558 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
559 waitForPhase(value, type, phase, criterion, listener);
568 final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
569 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
570 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
571 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
573 final Entry<K, V> match = optMatch.get();
574 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
577 final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
578 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
579 final OnNamespaceItemAdded listener) {
580 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
581 (context, phaseCompleted) -> {
582 selectMatch(type, criterion, listener);
587 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
588 final Class<N> type) {
589 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
590 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
593 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
596 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
597 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
601 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
602 * the listener is notified immediately.
604 * @param phase requested completion phase
605 * @param listener listener to invoke
606 * @throws NullPointerException if any of the arguments is null
608 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
609 requireNonNull(phase, "Statement context processing phase cannot be null");
610 requireNonNull(listener, "Statement context phase listener cannot be null");
612 ModelProcessingPhase finishedPhase = completedPhase;
613 while (finishedPhase != null) {
614 if (phase.equals(finishedPhase)) {
615 listener.phaseFinished(this, finishedPhase);
618 finishedPhase = finishedPhase.getPreviousPhase();
620 if (phaseListeners.isEmpty()) {
621 phaseListeners = newMultimap();
624 phaseListeners.put(phase, listener);
628 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
630 * @throws IllegalStateException when the mutation was registered after phase was completed
632 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
633 ModelProcessingPhase finishedPhase = completedPhase;
634 while (finishedPhase != null) {
635 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
637 finishedPhase = finishedPhase.getPreviousPhase();
640 if (phaseMutation.isEmpty()) {
641 phaseMutation = newMultimap();
643 phaseMutation.put(phase, mutation);
646 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
647 if (!phaseMutation.isEmpty()) {
648 phaseMutation.remove(phase, mutation);
649 cleanupPhaseMutation();
654 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
655 final KT key,final StmtContext<?, ?, ?> stmt) {
656 addContextToNamespace(namespace, key, stmt);
660 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
661 final QNameModule targetModule) {
662 checkEffectiveModelCompleted(this);
663 return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
666 private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
667 final QNameModule targetModule) {
668 final StatementSupport<A, D, E> support = definition.support();
669 final CopyPolicy policy = support.copyPolicy();
672 return replicaAsChildOf(parent);
673 case CONTEXT_INDEPENDENT:
674 if (allSubstatementsContextIndependent()) {
675 return replicaAsChildOf(parent);
681 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
685 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
687 throw new IllegalStateException("Unhandled policy " + policy);
692 final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
693 final QNameModule targetModule) {
694 final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
696 // The statement fizzled, this should never happen, perhaps a verify()?
700 parent.ensureCompletedPhase(copy);
701 return canReuseCurrent(copy) ? this : copy;
704 private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
705 // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
706 // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
707 return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
708 && allSubstatementsContextIndependent();
712 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
713 final QNameModule targetModule) {
714 checkEffectiveModelCompleted(stmt);
715 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
716 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
719 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
720 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
721 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
722 original.publicDefinition());
724 final StatementContextBase<X, Y, Z> result;
725 final InferredStatementContext<X, Y, Z> copy;
727 if (implicitParent.isPresent()) {
728 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
729 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
730 original.argument(), type);
732 final CopyType childCopyType;
734 case ADDED_BY_AUGMENTATION:
735 childCopyType = CopyType.ORIGINAL;
737 case ADDED_BY_USES_AUGMENTATION:
738 childCopyType = CopyType.ADDED_BY_USES;
743 childCopyType = type;
746 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
747 result.addEffectiveSubstatement(copy);
749 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
752 original.definition.onStatementAdded(copy);
757 final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
758 return new ReplicaStatementContext<>(parent, this);
761 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
762 final ModelProcessingPhase phase = stmt.getCompletedPhase();
763 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
764 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
768 public final boolean hasImplicitParentSupport() {
769 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
773 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
774 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
775 original.publicDefinition());
776 if (optImplicit.isEmpty()) {
780 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
781 final CopyType type = original.history().getLastOperation();
782 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
783 original.sourceReference(), original.rawArgument(), original.argument(), type);
785 result.addEffectiveSubstatement(original.reparent(result));
786 result.setCompletedPhase(original.getCompletedPhase());
790 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
793 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
795 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
797 abstract boolean hasEmptySubstatements();