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 StmtContext<?, ?, ?> ctx) {
135 if (effectOfStatement.isEmpty()) {
136 effectOfStatement = new ArrayList<>(1);
138 effectOfStatement.add(ctx);
142 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
143 if (ctxs.isEmpty()) {
147 if (effectOfStatement.isEmpty()) {
148 effectOfStatement = new ArrayList<>(ctxs.size());
150 effectOfStatement.addAll(ctxs);
154 public final CopyHistory history() {
159 public final ModelProcessingPhase getCompletedPhase() {
160 return completedPhase;
163 // FIXME: this should be propagated through a correct constructor
165 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
166 this.completedPhase = completedPhase;
170 public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
171 final Class<@NonNull N> type, final T key, final U value) {
172 addToNamespace(type, key, value);
175 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
176 final List<ReactorStmtCtx<?, ?, ?>> effective) {
177 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
180 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
181 return effective.isEmpty() ? ImmutableList.of() : effective;
184 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
186 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
187 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
188 if (effective.isEmpty()) {
192 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
193 while (iterator.hasNext()) {
194 final StmtContext<?, ?, ?> next = iterator.next();
195 if (statementDef.equals(next.publicDefinition())) {
200 return shrinkEffective(effective);
204 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
205 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
206 * definition and statement argument match with one of the effective substatements' statement definition
210 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
212 * @param statementDef statement definition of the statement context to remove
213 * @param statementArg statement argument of the statement context to remove
215 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
216 String statementArg);
218 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
219 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
220 final String statementArg) {
221 if (statementArg == null) {
222 return removeStatementFromEffectiveSubstatements(effective, statementDef);
225 if (effective.isEmpty()) {
229 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
230 while (iterator.hasNext()) {
231 final Mutable<?, ?, ?> next = iterator.next();
232 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
237 return shrinkEffective(effective);
240 // YANG example: RPC/action statements always have 'input' and 'output' defined
242 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
243 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
244 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
245 // StatementContextBase subclass.
246 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
247 ImplicitSubstatement.of(sourceReference()), rawArg);
248 support.onStatementAdded(ret);
249 addEffectiveSubstatement(ret);
254 * Adds an effective statement to collection of substatements.
256 * @param substatement substatement
257 * @throws IllegalStateException if added in declared phase
258 * @throws NullPointerException if statement parameter is null
260 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
262 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
263 final Mutable<?, ?, ?> substatement) {
264 verifyStatement(substatement);
266 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
267 final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
268 final ModelProcessingPhase phase = completedPhase;
270 ensureCompletedPhase(stmt, phase);
277 * Adds an effective statement to collection of substatements.
279 * @param statements substatements
280 * @throws IllegalStateException
281 * if added in declared phase
282 * @throws NullPointerException
283 * if statement parameter is null
285 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
286 if (!statements.isEmpty()) {
287 statements.forEach(StatementContextBase::verifyStatement);
288 addEffectiveSubstatementsImpl(statements);
292 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
294 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
295 final Collection<? extends Mutable<?, ?, ?>> statements) {
296 final List<ReactorStmtCtx<?, ?, ?>> 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<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
312 // exposed for InferredStatementContext only
313 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
314 verifyStatement(stmt);
315 final ModelProcessingPhase phase = completedPhase;
317 ensureCompletedPhase((ReactorStmtCtx<?, ?, ?>) 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 ReactorStmtCtx<?, ?, ?> stmt, final ModelProcessingPhase phase) {
325 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
328 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
329 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
332 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
334 // We cannot allow statement to be further mutated
335 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
337 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
340 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
342 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
343 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
344 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
345 "Effective statement cannot be added in declared phase at: %s", sourceReference());
347 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
351 final E createEffective() {
352 final E result = createEffective(definition.getFactory());
353 if (result instanceof MutableStatement) {
354 getRoot().addMutableStmtToSeal((MutableStatement) result);
359 @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
360 return createEffective(factory, this);
363 // Creates EffectiveStatement through full materialization
364 static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
365 final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
366 return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
369 abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
371 abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
374 final 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 ReactorStmtCtx<?, ?, ?> 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 ParserNamespace<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 ParserNamespace<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 ParserNamespace<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 ParserNamespace<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 ParserNamespace<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);
608 return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
611 private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
612 final QNameModule targetModule) {
613 final StatementSupport<A, D, E> support = definition.support();
614 final CopyPolicy policy = support.copyPolicy();
616 case CONTEXT_INDEPENDENT:
617 if (allSubstatementsContextIndependent()) {
618 return replicaAsChildOf(parent);
624 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
628 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
630 throw new IllegalStateException("Unhandled policy " + policy);
635 final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
636 final QNameModule targetModule) {
637 final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
639 // The statement fizzled, this should never happen, perhaps a verify()?
643 parent.ensureCompletedPhase(copy);
644 return canReuseCurrent(copy) ? replicaAsChildOf(parent) : copy;
647 private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
648 // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
649 // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
650 return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
651 && allSubstatementsContextIndependent();
654 // FIXME: YANGTOOLS-1195: we really want to compute (and cache) the summary for substatements.
656 // For now we just check if there are any substatements, but we really want to ask:
658 // Are all substatements (recursively) CONTEXT_INDEPENDENT as well?
660 // Which is something we want to compute once and store. This needs to be implemented.
661 private boolean allSubstatementsContextIndependent() {
662 return hasEmptySubstatements();
666 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
667 final QNameModule targetModule) {
668 checkEffectiveModelCompleted(stmt);
669 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
670 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
673 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
674 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
675 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
676 original.publicDefinition());
678 final StatementContextBase<X, Y, Z> result;
679 final InferredStatementContext<X, Y, Z> copy;
681 if (implicitParent.isPresent()) {
682 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
683 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
684 original.argument(), type);
686 final CopyType childCopyType;
688 case ADDED_BY_AUGMENTATION:
689 childCopyType = CopyType.ORIGINAL;
691 case ADDED_BY_USES_AUGMENTATION:
692 childCopyType = CopyType.ADDED_BY_USES;
697 childCopyType = type;
700 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
701 result.addEffectiveSubstatement(copy);
703 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
706 original.definition.onStatementAdded(copy);
711 public final ReactorStmtCtx<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
712 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
713 return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
716 final @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> stmt) {
717 return new ReplicaStatementContext<>(stmt, this);
720 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
721 final ModelProcessingPhase phase = stmt.getCompletedPhase();
722 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
723 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
727 public final boolean hasImplicitParentSupport() {
728 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
732 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
733 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
734 original.publicDefinition());
735 if (optImplicit.isEmpty()) {
739 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
740 final CopyType type = original.history().getLastOperation();
741 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
742 original.sourceReference(), original.rawArgument(), original.argument(), type);
744 result.addEffectiveSubstatement(original.reparent(result));
745 result.setCompletedPhase(original.getCompletedPhase());
749 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
752 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
754 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
756 abstract boolean hasEmptySubstatements();