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 com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
16 import com.google.common.annotations.Beta;
17 import com.google.common.base.VerifyException;
18 import com.google.common.collect.ImmutableCollection;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMultimap;
21 import com.google.common.collect.Multimap;
22 import com.google.common.collect.Multimaps;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.EnumMap;
27 import java.util.EventListener;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32 import java.util.stream.Stream;
33 import org.eclipse.jdt.annotation.NonNull;
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.ModelProcessingPhase.ExecutionOrder;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
54 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
55 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
56 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
61 * Core reactor statement implementation of {@link Mutable}.
63 * @param <A> Argument type
64 * @param <D> Declared Statement representation
65 * @param <E> Effective Statement representation
67 public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
68 extends ReactorStmtCtx<A, D, E> implements CopyHistory {
70 * Event listener when an item is added to model namespace.
72 interface OnNamespaceItemAdded extends EventListener {
74 * Invoked whenever a new item is added to a namespace.
76 void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
80 * Event listener when a parsing {@link ModelProcessingPhase} is completed.
82 interface OnPhaseFinished extends EventListener {
84 * Invoked whenever a processing phase has finished.
86 boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
90 * Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
92 interface ContextMutation {
97 private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
99 // Bottom 4 bits, encoding a CopyHistory, aight?
100 private static final byte COPY_ORIGINAL = 0x00;
101 private static final byte COPY_LAST_TYPE_MASK = 0x03;
102 @Deprecated(since = "7.0.9")
103 private static final byte COPY_ADDED_BY_USES = 0x04;
104 private static final byte COPY_ADDED_BY_AUGMENTATION = 0x08;
106 // Top four bits, of which we define the topmost two to 0. We use the bottom two to encode last CopyType, aight?
107 private static final int COPY_CHILD_TYPE_SHIFT = 4;
110 final int copyTypes = CopyType.values().length;
111 // This implies CopyType.ordinal() is <= COPY_TYPE_MASK
112 verify(copyTypes == COPY_LAST_TYPE_MASK + 1, "Unexpected %s CopyType values", copyTypes);
116 * 8 bits worth of instance storage. This is treated as a constant bit field with following structure:
125 * The four allocated fields are:
127 * <li>{@code lst}, encoding the four states corresponding to {@link CopyHistory#getLastOperation()}</li>
128 * <li>{@code u}, encoding {@link #isAddedByUses()}</li>
129 * <li>{@code a}, encoding {@link #isAugmenting()}</li>
130 * <li>{@code cct} encoding {@link #childCopyType()}</li>
132 * We still have two unused bits.
134 private final byte bitsAight;
136 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
137 // operations, hence we want to keep it close by.
138 private final @NonNull StatementDefinitionContext<A, D, E> definition;
140 // TODO: consider keying by Byte equivalent of ExecutionOrder
141 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
142 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
144 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
147 * {@link ModelProcessingPhase.ExecutionOrder} value of current {@link ModelProcessingPhase} of this statement.
149 private byte executionOrder;
151 // Copy constructor used by subclasses to implement reparent()
152 StatementContextBase(final StatementContextBase<A, D, E> original) {
154 this.bitsAight = original.bitsAight;
155 this.definition = original.definition;
156 this.executionOrder = original.executionOrder;
159 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
160 this.definition = requireNonNull(def);
161 this.bitsAight = COPY_ORIGINAL;
164 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyType copyType) {
165 this.definition = requireNonNull(def);
166 this.bitsAight = (byte) copyFlags(copyType);
169 StatementContextBase(final StatementContextBase<A, D, E> prototype, final CopyType copyType,
170 final CopyType childCopyType) {
171 this.definition = prototype.definition;
172 this.bitsAight = (byte) (copyFlags(copyType)
173 | prototype.bitsAight & ~COPY_LAST_TYPE_MASK | childCopyType.ordinal() << COPY_CHILD_TYPE_SHIFT);
176 private static int copyFlags(final CopyType copyType) {
177 return historyFlags(copyType) | copyType.ordinal();
180 private static byte historyFlags(final CopyType copyType) {
182 case ADDED_BY_AUGMENTATION:
183 return COPY_ADDED_BY_AUGMENTATION;
185 return COPY_ADDED_BY_USES;
186 case ADDED_BY_USES_AUGMENTATION:
187 return COPY_ADDED_BY_AUGMENTATION | COPY_ADDED_BY_USES;
189 return COPY_ORIGINAL;
191 throw new VerifyException("Unhandled type " + copyType);
196 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
197 return effectOfStatement;
201 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
202 if (ctxs.isEmpty()) {
206 if (effectOfStatement.isEmpty()) {
207 effectOfStatement = new ArrayList<>(ctxs.size());
209 effectOfStatement.addAll(ctxs);
213 // CopyHistory integration
217 public final CopyHistory history() {
222 @Deprecated(since = "7.0.9")
223 public final boolean isAddedByUses() {
224 return (bitsAight & COPY_ADDED_BY_USES) != 0;
228 public final boolean isAugmenting() {
229 return (bitsAight & COPY_ADDED_BY_AUGMENTATION) != 0;
233 public final CopyType getLastOperation() {
234 return CopyType.values()[bitsAight & COPY_LAST_TYPE_MASK];
237 // This method exists only for space optimization of InferredStatementContext
238 final CopyType childCopyType() {
239 return CopyType.values()[bitsAight >> COPY_CHILD_TYPE_SHIFT & COPY_LAST_TYPE_MASK];
243 // Inference completion tracking
247 final byte executionOrder() {
248 return executionOrder;
251 // FIXME: this should be propagated through a correct constructor
253 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
254 this.executionOrder = completedPhase.executionOrder();
258 public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
259 final Class<@NonNull N> type, final T key, final U value) {
260 addToNamespace(type, key, value);
263 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
264 final List<ReactorStmtCtx<?, ?, ?>> effective) {
265 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
268 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
269 return effective.isEmpty() ? ImmutableList.of() : effective;
272 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
274 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
275 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
276 if (effective.isEmpty()) {
280 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
281 while (iterator.hasNext()) {
282 final StmtContext<?, ?, ?> next = iterator.next();
283 if (statementDef.equals(next.publicDefinition())) {
288 return shrinkEffective(effective);
292 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
293 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
294 * definition and statement argument match with one of the effective substatements' statement definition
298 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
300 * @param statementDef statement definition of the statement context to remove
301 * @param statementArg statement argument of the statement context to remove
303 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
304 String statementArg);
306 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
307 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
308 final String statementArg) {
309 if (statementArg == null) {
310 return removeStatementFromEffectiveSubstatements(effective, statementDef);
313 if (effective.isEmpty()) {
317 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
318 while (iterator.hasNext()) {
319 final Mutable<?, ?, ?> next = iterator.next();
320 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
325 return shrinkEffective(effective);
328 // YANG example: RPC/action statements always have 'input' and 'output' defined
330 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
331 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
332 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
333 // StatementContextBase subclass.
334 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
335 ImplicitSubstatement.of(sourceReference()), rawArg);
336 support.onStatementAdded(ret);
337 addEffectiveSubstatement(ret);
342 * Adds an effective statement to collection of substatements.
344 * @param substatement substatement
345 * @throws IllegalStateException if added in declared phase
346 * @throws NullPointerException if statement parameter is null
348 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
350 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
351 final Mutable<?, ?, ?> substatement) {
352 verifyStatement(substatement);
354 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
355 final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
356 ensureCompletedExecution(stmt);
362 * Adds an effective statement to collection of substatements.
364 * @param statements substatements
365 * @throws IllegalStateException
366 * if added in declared phase
367 * @throws NullPointerException
368 * if statement parameter is null
370 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
371 if (!statements.isEmpty()) {
372 statements.forEach(StatementContextBase::verifyStatement);
373 addEffectiveSubstatementsImpl(statements);
377 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
379 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
380 final Collection<? extends Mutable<?, ?, ?>> statements) {
381 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
382 final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
383 (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
384 if (executionOrder != ExecutionOrder.NULL) {
385 for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
386 ensureCompletedExecution(stmt, executionOrder);
390 resized.addAll(casted);
394 abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
396 // exposed for InferredStatementContext only
397 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
398 verifyStatement(stmt);
399 ensureCompletedExecution((ReactorStmtCtx<?, ?, ?>) stmt);
402 // Make sure target statement has transitioned at least to our phase (if we have one). This method is just before we
403 // take allow a statement to become our substatement. This is needed to ensure that every statement tree does not
404 // contain any statements which did not complete the same phase as the root statement.
405 private void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt) {
406 if (executionOrder != ExecutionOrder.NULL) {
407 ensureCompletedExecution(stmt, executionOrder);
411 private static void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt, final byte executionOrder) {
412 verify(stmt.tryToCompletePhase(executionOrder), "Statement %s cannot complete phase %s", stmt, executionOrder);
415 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
416 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
419 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
421 // We cannot allow statement to be further mutated.
422 // TODO: we really want to say 'not NULL and not at or after EFFECTIVE_MODEL here. This will matter if we have
423 // a phase after EFFECTIVE_MODEL
424 verify(executionOrder != ExecutionOrder.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
426 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
429 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
431 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
432 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
433 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
434 "Effective statement cannot be added in declared phase at: %s", sourceReference());
436 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
440 final E createEffective() {
441 final E result = createEffective(definition.getFactory());
442 if (result instanceof MutableStatement) {
443 getRoot().addMutableStmtToSeal((MutableStatement) result);
448 @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
449 return createEffective(factory, this);
452 // Creates EffectiveStatement through full materialization
453 static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
454 final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
455 return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
459 * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
460 * {@link StmtContext#buildEffective()} contract.
462 * @return Stream of supported declared statements.
464 // FIXME: we really want to unify this with streamEffective(), under its name
465 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared();
468 * Return a stream of inferred statements which can be built into an {@link EffectiveStatement}, as per
469 * {@link StmtContext#buildEffective()} contract.
471 * @return Stream of supported effective statements.
473 // FIXME: this method is currently a misnomer, but unifying with streamDeclared() would make this accurate again
474 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective();
477 final boolean doTryToCompletePhase(final byte targetOrder) {
478 final boolean finished = phaseMutation.isEmpty() || runMutations(targetOrder);
479 if (completeChildren(targetOrder) && finished) {
480 onPhaseCompleted(targetOrder);
486 private boolean completeChildren(final byte targetOrder) {
487 boolean finished = true;
488 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
489 finished &= child.tryToCompletePhase(targetOrder);
491 for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
492 finished &= child.tryToCompletePhase(targetOrder);
497 private boolean runMutations(final byte targetOrder) {
498 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(targetOrder));
499 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
500 return openMutations.isEmpty() || runMutations(phase, openMutations);
503 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
504 boolean finished = true;
505 final Iterator<ContextMutation> it = openMutations.iterator();
506 while (it.hasNext()) {
507 final ContextMutation current = it.next();
508 if (current.isFinished()) {
515 if (openMutations.isEmpty()) {
516 phaseMutation.removeAll(phase);
517 cleanupPhaseMutation();
522 private void cleanupPhaseMutation() {
523 if (phaseMutation.isEmpty()) {
524 phaseMutation = ImmutableMultimap.of();
529 * Occurs on end of {@link ModelProcessingPhase} of source parsing. This method must not be called with
530 * {@code executionOrder} equal to {@link ExecutionOrder#NULL}.
532 * @param phase that was to be completed (finished)
533 * @throws SourceException when an error occurred in source parsing
535 private void onPhaseCompleted(final byte completedOrder) {
536 executionOrder = completedOrder;
537 if (completedOrder == ExecutionOrder.EFFECTIVE_MODEL) {
538 // We have completed effective model, substatements are guaranteed not to change
539 summarizeSubstatementPolicy();
542 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(completedOrder));
543 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
544 if (!listeners.isEmpty()) {
545 runPhaseListeners(phase, listeners);
549 private void summarizeSubstatementPolicy() {
550 if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
551 setAllSubstatementsContextIndependent();
556 * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
557 * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
558 * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
559 * considered copy-insensitive.
562 * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
564 * @return True if no substatements require copy-sensitive handling
566 abstract boolean noSensitiveSubstatements();
569 * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
570 * {@link #noSensitiveSubstatements()}.
572 * @param substatements Substatements to check
573 * @return True if no substatements require context-sensitive handling
575 static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
576 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
577 if (stmt.isSupportedToBuildEffective()) {
578 if (!stmt.allSubstatementsContextIndependent()) {
579 // This is a recursive property
583 switch (stmt.definition().support().copyPolicy()) {
584 case CONTEXT_INDEPENDENT:
596 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
597 final Iterator<OnPhaseFinished> listener = listeners.iterator();
598 while (listener.hasNext()) {
599 final OnPhaseFinished next = listener.next();
600 if (next.phaseFinished(this, phase)) {
605 if (listeners.isEmpty()) {
606 phaseListeners.removeAll(phase);
607 if (phaseListeners.isEmpty()) {
608 phaseListeners = ImmutableMultimap.of();
614 * Ends declared section of current node.
616 void endDeclared(final ModelProcessingPhase phase) {
617 definition.onDeclarationFinished(this, phase);
621 final StatementDefinitionContext<A, D, E> definition() {
625 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
626 final OnNamespaceItemAdded listener) {
627 final Object potential = getFromNamespace(type, key);
628 if (potential != null) {
629 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
630 listener.namespaceItemAdded(this, type, key, potential);
634 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
636 void onValueAdded(final Object value) {
637 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
642 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
643 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
644 final OnNamespaceItemAdded listener) {
645 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
646 if (existing.isPresent()) {
647 final Entry<K, V> entry = existing.get();
648 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
649 waitForPhase(entry.getValue(), type, phase, criterion, listener);
653 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
654 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
656 boolean onValueAdded(final K key, final V value) {
657 if (criterion.match(key)) {
658 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
659 waitForPhase(value, type, phase, criterion, listener);
668 final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
669 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
670 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
671 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
673 final Entry<K, V> match = optMatch.get();
674 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
677 final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
678 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
679 final OnNamespaceItemAdded listener) {
680 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
681 (context, phaseCompleted) -> {
682 selectMatch(type, criterion, listener);
687 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
688 final Class<N> type) {
689 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
690 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
693 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
696 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
697 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
701 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
702 * the listener is notified immediately.
704 * @param phase requested completion phase
705 * @param listener listener to invoke
706 * @throws NullPointerException if any of the arguments is null
708 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
709 requireNonNull(phase, "Statement context processing phase cannot be null");
710 requireNonNull(listener, "Statement context phase listener cannot be null");
712 ModelProcessingPhase finishedPhase = ModelProcessingPhase.ofExecutionOrder(executionOrder);
713 while (finishedPhase != null) {
714 if (phase.equals(finishedPhase)) {
715 listener.phaseFinished(this, finishedPhase);
718 finishedPhase = finishedPhase.getPreviousPhase();
720 if (phaseListeners.isEmpty()) {
721 phaseListeners = newMultimap();
724 phaseListeners.put(phase, listener);
728 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
730 * @throws IllegalStateException when the mutation was registered after phase was completed
732 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
733 checkState(executionOrder < phase.executionOrder(), "Mutation registered after phase was completed at: %s",
736 if (phaseMutation.isEmpty()) {
737 phaseMutation = newMultimap();
739 phaseMutation.put(phase, mutation);
742 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
743 if (!phaseMutation.isEmpty()) {
744 phaseMutation.remove(phase, mutation);
745 cleanupPhaseMutation();
750 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
751 final KT key,final StmtContext<?, ?, ?> stmt) {
752 addContextToNamespace(namespace, key, stmt);
756 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
757 final QNameModule targetModule) {
758 checkEffectiveModelCompleted(this);
759 return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
762 private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
763 final QNameModule targetModule) {
764 final StatementSupport<A, D, E> support = definition.support();
765 final CopyPolicy policy = support.copyPolicy();
768 return replicaAsChildOf(parent);
769 case CONTEXT_INDEPENDENT:
770 if (allSubstatementsContextIndependent()) {
771 return replicaAsChildOf(parent);
777 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
781 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
783 throw new IllegalStateException("Unhandled policy " + policy);
788 final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
789 final QNameModule targetModule) {
790 final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
792 // The statement fizzled, this should never happen, perhaps a verify()?
796 parent.ensureCompletedPhase(copy);
797 return canReuseCurrent(copy) ? this : copy;
800 private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
801 // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
802 // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
803 return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
804 && allSubstatementsContextIndependent();
808 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
809 final QNameModule targetModule) {
810 checkEffectiveModelCompleted(stmt);
811 if (stmt instanceof StatementContextBase) {
812 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
813 } else if (stmt instanceof ReplicaStatementContext) {
814 return ((ReplicaStatementContext<?, ?, ?>) stmt).replicaAsChildOf(this);
816 throw new IllegalArgumentException("Unsupported statement " + stmt);
820 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
821 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
822 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
823 original.publicDefinition());
825 final StatementContextBase<X, Y, Z> result;
826 final InferredStatementContext<X, Y, Z> copy;
828 if (implicitParent.isPresent()) {
829 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
830 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
831 original.argument(), type);
833 final CopyType childCopyType;
835 case ADDED_BY_AUGMENTATION:
836 childCopyType = CopyType.ORIGINAL;
838 case ADDED_BY_USES_AUGMENTATION:
839 childCopyType = CopyType.ADDED_BY_USES;
844 childCopyType = type;
847 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
848 result.addEffectiveSubstatement(copy);
850 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
853 original.definition.onStatementAdded(copy);
858 final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
859 return new ReplicaStatementContext<>(parent, this);
862 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
863 final ModelProcessingPhase phase = stmt.getCompletedPhase();
864 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
865 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
869 // FIXME: this information should be exposed as a well-known Namespace
870 public final boolean hasImplicitParentSupport() {
871 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
875 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
876 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
877 original.publicDefinition());
878 if (optImplicit.isEmpty()) {
882 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
883 final CopyType type = original.history().getLastOperation();
884 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
885 original.sourceReference(), original.rawArgument(), original.argument(), type);
887 result.addEffectiveSubstatement(original.reparent(result));
888 result.setCompletedPhase(original.getCompletedPhase());
892 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
895 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
897 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
899 abstract boolean hasEmptySubstatements();