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.QName;
35 import org.opendaylight.yangtools.yang.common.QNameModule;
36 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
37 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
38 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
40 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
41 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
42 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
43 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
44 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
45 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
58 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
59 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
60 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
61 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
66 * Core reactor statement implementation of {@link Mutable}.
68 * @param <A> Argument type
69 * @param <D> Declared Statement representation
70 * @param <E> Effective Statement representation
72 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
73 extends ReactorStmtCtx<A, D, E> {
75 * Event listener when an item is added to model namespace.
77 interface OnNamespaceItemAdded extends EventListener {
79 * Invoked whenever a new item is added to a namespace.
81 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
85 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
87 interface OnPhaseFinished extends EventListener {
89 * Invoked whenever a processing phase has finished.
91 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
95 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
97 interface ContextMutation {
102 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
104 private final CopyHistory copyHistory;
105 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
106 // operations, hence we want to keep it close by.
107 private final @NonNull StatementDefinitionContext<A, D, E> definition;
109 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
110 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
112 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
114 private @Nullable ModelProcessingPhase completedPhase;
116 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
117 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
118 private volatile SchemaPath schemaPath;
120 // Copy constructor used by subclasses to implement reparent()
121 StatementContextBase(final StatementContextBase<A, D, E> original) {
123 this.copyHistory = original.copyHistory;
124 this.definition = original.definition;
125 this.completedPhase = original.completedPhase;
128 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
129 this.definition = requireNonNull(def);
130 this.copyHistory = CopyHistory.original();
133 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyHistory copyHistory) {
134 this.definition = requireNonNull(def);
135 this.copyHistory = requireNonNull(copyHistory);
139 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
140 return effectOfStatement;
144 public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
145 if (effectOfStatement.isEmpty()) {
146 effectOfStatement = new ArrayList<>(1);
148 effectOfStatement.add(ctx);
152 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
153 if (ctxs.isEmpty()) {
157 if (effectOfStatement.isEmpty()) {
158 effectOfStatement = new ArrayList<>(ctxs.size());
160 effectOfStatement.addAll(ctxs);
164 public CopyHistory getCopyHistory() {
169 public ModelProcessingPhase getCompletedPhase() {
170 return completedPhase;
173 // FIXME: this should be propagated through a correct constructor
175 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
176 this.completedPhase = completedPhase;
180 public final <K, V, T extends K, U extends V, N extends IdentifierNamespace<K, V>> void addToNs(
181 final Class<@NonNull N> type, final T key, final U value) {
182 addToNamespace(type, key, value);
185 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
186 final List<StatementContextBase<?, ?, ?>> effective) {
187 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
190 private static List<StatementContextBase<?, ?, ?>> shrinkEffective(
191 final List<StatementContextBase<?, ?, ?>> effective) {
192 return effective.isEmpty() ? ImmutableList.of() : effective;
195 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
197 static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
198 final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef) {
199 if (effective.isEmpty()) {
203 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
204 while (iterator.hasNext()) {
205 final StmtContext<?, ?, ?> next = iterator.next();
206 if (statementDef.equals(next.publicDefinition())) {
211 return shrinkEffective(effective);
215 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
216 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
217 * definition and statement argument match with one of the effective substatements' statement definition
221 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
223 * @param statementDef statement definition of the statement context to remove
224 * @param statementArg statement argument of the statement context to remove
226 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
227 String statementArg);
229 static final List<StatementContextBase<?, ?, ?>> removeStatementFromEffectiveSubstatements(
230 final List<StatementContextBase<?, ?, ?>> effective, final StatementDefinition statementDef,
231 final String statementArg) {
232 if (statementArg == null) {
233 return removeStatementFromEffectiveSubstatements(effective, statementDef);
236 if (effective.isEmpty()) {
240 final Iterator<StatementContextBase<?, ?, ?>> iterator = effective.iterator();
241 while (iterator.hasNext()) {
242 final Mutable<?, ?, ?> next = iterator.next();
243 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
248 return shrinkEffective(effective);
251 // YANG example: RPC/action statements always have 'input' and 'output' defined
253 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
254 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
255 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
256 // StatementContextBase subclass.
257 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
258 ImplicitSubstatement.of(sourceReference()), rawArg);
259 support.onStatementAdded(ret);
260 addEffectiveSubstatement(ret);
265 * Adds an effective statement to collection of substatements.
267 * @param substatement substatement
268 * @throws IllegalStateException if added in declared phase
269 * @throws NullPointerException if statement parameter is null
271 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
273 final List<StatementContextBase<?, ?, ?>> addEffectiveSubstatement(
274 final List<StatementContextBase<?, ?, ?>> effective, final Mutable<?, ?, ?> substatement) {
275 verifyStatement(substatement);
277 final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
278 final StatementContextBase<?, ?, ?> stmt = (StatementContextBase<?, ?, ?>) substatement;
279 final ModelProcessingPhase phase = completedPhase;
281 ensureCompletedPhase(stmt, phase);
288 * Adds an effective statement to collection of substatements.
290 * @param statements substatements
291 * @throws IllegalStateException
292 * if added in declared phase
293 * @throws NullPointerException
294 * if statement parameter is null
296 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
297 if (!statements.isEmpty()) {
298 statements.forEach(StatementContextBase::verifyStatement);
299 addEffectiveSubstatementsImpl(statements);
303 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
305 final List<StatementContextBase<?, ?, ?>> addEffectiveSubstatementsImpl(
306 final List<StatementContextBase<?, ?, ?>> effective,
307 final Collection<? extends Mutable<?, ?, ?>> statements) {
308 final List<StatementContextBase<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
309 final Collection<? extends StatementContextBase<?, ?, ?>> casted =
310 (Collection<? extends StatementContextBase<?, ?, ?>>) statements;
311 final ModelProcessingPhase phase = completedPhase;
313 for (StatementContextBase<?, ?, ?> stmt : casted) {
314 ensureCompletedPhase(stmt, phase);
318 resized.addAll(casted);
322 abstract Iterable<StatementContextBase<?, ?, ?>> effectiveChildrenToComplete();
324 // exposed for InferredStatementContext only
325 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
326 verifyStatement(stmt);
327 final ModelProcessingPhase phase = completedPhase;
329 ensureCompletedPhase((StatementContextBase<?, ?, ?>) stmt, phase);
333 // Make sure target statement has transitioned at least to specified phase. This method is just before we take
334 // allow a statement to become our substatement. This is needed to ensure that every statement tree does not contain
335 // any statements which did not complete the same phase as the root statement.
336 private static void ensureCompletedPhase(final StatementContextBase<?, ?, ?> stmt,
337 final ModelProcessingPhase phase) {
338 verify(stmt.tryToCompletePhase(phase), "Statement %s cannot complete phase %s", stmt, phase);
341 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
342 verify(stmt instanceof StatementContextBase, "Unexpected statement %s", stmt);
345 private List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatement(
346 final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
347 // We cannot allow statement to be further mutated
348 verify(completedPhase != ModelProcessingPhase.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
350 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
353 final List<StatementContextBase<?, ?, ?>> beforeAddEffectiveStatementUnsafe(
354 final List<StatementContextBase<?, ?, ?>> effective, final int toAdd) {
355 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
356 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
357 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
358 "Effective statement cannot be added in declared phase at: %s", sourceReference());
360 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
363 // Exposed for ReplicaStatementContext
365 E createEffective() {
366 return definition.getFactory().createEffective(new BaseCurrentEffectiveStmtCtx<>(this), streamDeclared(),
370 abstract Stream<? extends StmtContext<?, ?, ?>> streamDeclared();
372 abstract Stream<? extends StmtContext<?, ?, ?>> streamEffective();
375 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
376 * this method does nothing.
378 * @param phase to be executed (completed)
379 * @return true if phase was successfully completed
380 * @throws SourceException when an error occurred in source parsing
382 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
383 return phase.isCompletedBy(completedPhase) || doTryToCompletePhase(phase);
386 private boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
387 final boolean finished = phaseMutation.isEmpty() ? true : runMutations(phase);
388 if (completeChildren(phase) && finished) {
389 onPhaseCompleted(phase);
395 private boolean completeChildren(final ModelProcessingPhase phase) {
396 boolean finished = true;
397 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
398 finished &= child.tryToCompletePhase(phase);
400 for (final StatementContextBase<?, ?, ?> child : effectiveChildrenToComplete()) {
401 finished &= child.tryToCompletePhase(phase);
406 private boolean runMutations(final ModelProcessingPhase phase) {
407 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
408 return openMutations.isEmpty() ? true : runMutations(phase, openMutations);
411 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
412 boolean finished = true;
413 final Iterator<ContextMutation> it = openMutations.iterator();
414 while (it.hasNext()) {
415 final ContextMutation current = it.next();
416 if (current.isFinished()) {
423 if (openMutations.isEmpty()) {
424 phaseMutation.removeAll(phase);
425 cleanupPhaseMutation();
430 private void cleanupPhaseMutation() {
431 if (phaseMutation.isEmpty()) {
432 phaseMutation = ImmutableMultimap.of();
437 * Occurs on end of {@link ModelProcessingPhase} of source parsing.
440 * that was to be completed (finished)
441 * @throws SourceException
442 * when an error occurred in source parsing
444 private void onPhaseCompleted(final ModelProcessingPhase phase) {
445 completedPhase = phase;
447 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
448 if (!listeners.isEmpty()) {
449 runPhaseListeners(phase, listeners);
453 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
454 final Iterator<OnPhaseFinished> listener = listeners.iterator();
455 while (listener.hasNext()) {
456 final OnPhaseFinished next = listener.next();
457 if (next.phaseFinished(this, phase)) {
462 if (listeners.isEmpty()) {
463 phaseListeners.removeAll(phase);
464 if (phaseListeners.isEmpty()) {
465 phaseListeners = ImmutableMultimap.of();
471 * Ends declared section of current node.
473 void endDeclared(final ModelProcessingPhase phase) {
474 definition.onDeclarationFinished(this, phase);
478 final StatementDefinitionContext<A, D, E> definition() {
482 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
483 final OnNamespaceItemAdded listener) {
484 final Object potential = getFromNamespace(type, key);
485 if (potential != null) {
486 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
487 listener.namespaceItemAdded(this, type, key, potential);
491 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
493 void onValueAdded(final Object value) {
494 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
499 final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
500 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
501 final OnNamespaceItemAdded listener) {
502 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
503 if (existing.isPresent()) {
504 final Entry<K, V> entry = existing.get();
505 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
506 waitForPhase(entry.getValue(), type, phase, criterion, listener);
510 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
511 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
513 boolean onValueAdded(final K key, final V value) {
514 if (criterion.match(key)) {
515 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
516 waitForPhase(value, type, phase, criterion, listener);
525 final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
526 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
527 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
528 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
530 final Entry<K, V> match = optMatch.get();
531 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
534 final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
535 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
536 final OnNamespaceItemAdded listener) {
537 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
538 (context, phaseCompleted) -> {
539 selectMatch(type, criterion, listener);
544 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
545 final Class<N> type) {
546 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
547 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
550 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
553 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
554 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
558 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
559 * the listener is notified immediately.
561 * @param phase requested completion phase
562 * @param listener listener to invoke
563 * @throws NullPointerException if any of the arguments is null
565 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
566 checkNotNull(phase, "Statement context processing phase cannot be null at: %s", sourceReference());
567 checkNotNull(listener, "Statement context phase listener cannot be null at: %s", sourceReference());
569 ModelProcessingPhase finishedPhase = completedPhase;
570 while (finishedPhase != null) {
571 if (phase.equals(finishedPhase)) {
572 listener.phaseFinished(this, finishedPhase);
575 finishedPhase = finishedPhase.getPreviousPhase();
577 if (phaseListeners.isEmpty()) {
578 phaseListeners = newMultimap();
581 phaseListeners.put(phase, listener);
585 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
587 * @throws IllegalStateException when the mutation was registered after phase was completed
589 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
590 ModelProcessingPhase finishedPhase = completedPhase;
591 while (finishedPhase != null) {
592 checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
594 finishedPhase = finishedPhase.getPreviousPhase();
597 if (phaseMutation.isEmpty()) {
598 phaseMutation = newMultimap();
600 phaseMutation.put(phase, mutation);
603 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
604 if (!phaseMutation.isEmpty()) {
605 phaseMutation.remove(phase, mutation);
606 cleanupPhaseMutation();
611 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
612 final KT key,final StmtContext<?, ?, ?> stmt) {
613 addContextToNamespace(namespace, key, stmt);
617 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
618 final QNameModule targetModule) {
619 checkEffectiveModelCompleted(this);
621 final StatementSupport<A, D, E> support = definition.support();
622 final CopyPolicy policy = support.applyCopyPolicy(this, parent, type, targetModule);
624 case CONTEXT_INDEPENDENT:
625 if (hasEmptySubstatements()) {
626 // This statement is context-independent and has no substatements -- hence it can be freely shared.
627 return Optional.of(replicaAsChildOf(parent));
629 // FIXME: YANGTOOLS-694: filter out all context-independent substatements, eliminate fall-through
632 // FIXME: YANGTOOLS-694: this is still to eager, we really want to copy as a lazily-instantiated
633 // context, so that we can support building an effective statement without copying
634 // anything -- we will typically end up not being inferred against. In that case,
635 // this slim context should end up dealing with differences at buildContext()
636 // time. This is a YANGTOOLS-1067 prerequisite (which will deal with what can and
637 // cannot be shared across instances).
638 return Optional.of(parent.childCopyOf(this, type, targetModule));
640 return Optional.empty();
642 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
644 throw new IllegalStateException("Unhandled policy " + policy);
649 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
650 final QNameModule targetModule) {
651 checkEffectiveModelCompleted(stmt);
652 checkArgument(stmt instanceof StatementContextBase, "Unsupported statement %s", stmt);
653 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
656 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
657 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
658 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
659 original.publicDefinition());
661 final StatementContextBase<X, Y, Z> result;
662 final InferredStatementContext<X, Y, Z> copy;
664 if (implicitParent.isPresent()) {
665 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
666 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
667 original.argument(), type);
669 final CopyType childCopyType;
671 case ADDED_BY_AUGMENTATION:
672 childCopyType = CopyType.ORIGINAL;
674 case ADDED_BY_USES_AUGMENTATION:
675 childCopyType = CopyType.ADDED_BY_USES;
680 childCopyType = type;
683 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
684 result.addEffectiveSubstatement(copy);
686 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
689 original.definition.onStatementAdded(copy);
694 public final StatementContextBase<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
695 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
696 return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
699 final @NonNull StatementContextBase<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> stmt) {
700 return new ReplicaStatementContext<>(stmt, this);
703 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
704 final ModelProcessingPhase phase = stmt.getCompletedPhase();
705 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
706 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
710 public final boolean hasImplicitParentSupport() {
711 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
715 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
716 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
717 original.publicDefinition());
718 if (optImplicit.isEmpty()) {
722 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
723 final CopyType type = original.getCopyHistory().getLastOperation();
724 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
725 original.sourceReference(), original.rawArgument(), original.argument(), type);
727 result.addEffectiveSubstatement(original.reparent(result));
728 result.setCompletedPhase(original.getCompletedPhase());
732 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
735 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
737 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
739 abstract boolean hasEmptySubstatements();
741 abstract @NonNull Optional<SchemaPath> schemaPath();
743 // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
745 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
746 SchemaPath local = schemaPath;
748 synchronized (this) {
751 schemaPath = local = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
756 return Optional.ofNullable(local);
760 private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
761 final Optional<SchemaPath> maybeParentPath = parent.schemaPath();
762 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
763 final SchemaPath parentPath = maybeParentPath.get();
765 if (StmtContextUtils.isUnknownStatement(this)) {
766 return parentPath.createChild(publicDefinition().getStatementName());
768 final Object argument = argument();
769 if (argument instanceof QName) {
770 final QName qname = (QName) argument;
771 if (producesDeclared(UsesStatement.class)) {
772 return maybeParentPath.orElse(null);
775 return parentPath.createChild(qname);
777 if (argument instanceof String) {
778 // FIXME: This may yield illegal argument exceptions
779 final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
780 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
781 return parentPath.createChild(qname);
783 if (argument instanceof SchemaNodeIdentifier
784 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
785 || producesDeclared(DeviationStatement.class))) {
787 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
790 // FIXME: this does not look right
791 return maybeParentPath.orElse(null);