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 private static final byte COPY_ADDED_BY_USES = 0x04;
103 private static final byte COPY_ADDED_BY_AUGMENTATION = 0x08;
105 // Top four bits, of which we define the topmost two to 0. We use the bottom two to encode last CopyType, aight?
106 private static final int COPY_CHILD_TYPE_SHIFT = 4;
109 final int copyTypes = CopyType.values().length;
110 // This implies CopyType.ordinal() is <= COPY_TYPE_MASK
111 verify(copyTypes == COPY_LAST_TYPE_MASK + 1, "Unexpected %s CopyType values", copyTypes);
115 * 8 bits worth of instance storage. This is treated as a constant bit field with following structure:
124 * The four allocated fields are:
126 * <li>{@code lst}, encoding the four states corresponding to {@link CopyHistory#getLastOperation()}</li>
127 * <li>{@code u}, encoding {@link #isAddedByUses()}</li>
128 * <li>{@code a}, encoding {@link #isAugmenting()}</li>
129 * <li>{@code cct} encoding {@link #childCopyType()}</li>
131 * We still have two unused bits.
133 private final byte bitsAight;
135 // Note: this field can strictly be derived in InferredStatementContext, but it forms the basis of many of our
136 // operations, hence we want to keep it close by.
137 private final @NonNull StatementDefinitionContext<A, D, E> definition;
139 // TODO: consider keying by Byte equivalent of ExecutionOrder
140 private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
141 private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
143 private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
146 * {@link ModelProcessingPhase.ExecutionOrder} value of current {@link ModelProcessingPhase} of this statement.
148 private byte executionOrder;
150 // Copy constructor used by subclasses to implement reparent()
151 StatementContextBase(final StatementContextBase<A, D, E> original) {
153 this.bitsAight = original.bitsAight;
154 this.definition = original.definition;
155 this.executionOrder = original.executionOrder;
158 StatementContextBase(final StatementDefinitionContext<A, D, E> def) {
159 this.definition = requireNonNull(def);
160 this.bitsAight = COPY_ORIGINAL;
163 StatementContextBase(final StatementDefinitionContext<A, D, E> def, final CopyType copyType) {
164 this.definition = requireNonNull(def);
165 this.bitsAight = (byte) copyFlags(copyType);
168 StatementContextBase(final StatementContextBase<A, D, E> prototype, final CopyType copyType,
169 final CopyType childCopyType) {
170 this.definition = prototype.definition;
171 this.bitsAight = (byte) (copyFlags(copyType)
172 | prototype.bitsAight & ~COPY_LAST_TYPE_MASK | childCopyType.ordinal() << COPY_CHILD_TYPE_SHIFT);
175 private static int copyFlags(final CopyType copyType) {
176 return historyFlags(copyType) | copyType.ordinal();
179 private static byte historyFlags(final CopyType copyType) {
181 case ADDED_BY_AUGMENTATION:
182 return COPY_ADDED_BY_AUGMENTATION;
184 return COPY_ADDED_BY_USES;
185 case ADDED_BY_USES_AUGMENTATION:
186 return COPY_ADDED_BY_AUGMENTATION | COPY_ADDED_BY_USES;
188 return COPY_ORIGINAL;
190 throw new VerifyException("Unhandled type " + copyType);
195 public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
196 return effectOfStatement;
200 public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
201 if (ctxs.isEmpty()) {
205 if (effectOfStatement.isEmpty()) {
206 effectOfStatement = new ArrayList<>(ctxs.size());
208 effectOfStatement.addAll(ctxs);
212 // CopyHistory integration
216 public final CopyHistory history() {
221 public final boolean isAddedByUses() {
222 return (bitsAight & COPY_ADDED_BY_USES) != 0;
226 public final boolean isAugmenting() {
227 return (bitsAight & COPY_ADDED_BY_AUGMENTATION) != 0;
231 public final CopyType getLastOperation() {
232 return CopyType.values()[bitsAight & COPY_LAST_TYPE_MASK];
235 // This method exists only for space optimization of InferredStatementContext
236 final CopyType childCopyType() {
237 return CopyType.values()[bitsAight >> COPY_CHILD_TYPE_SHIFT & COPY_LAST_TYPE_MASK];
241 // Inference completion tracking
245 final byte executionOrder() {
246 return executionOrder;
249 // FIXME: this should be propagated through a correct constructor
251 final void setCompletedPhase(final ModelProcessingPhase completedPhase) {
252 this.executionOrder = completedPhase.executionOrder();
256 public final <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(
257 final Class<@NonNull N> type, final T key, final U value) {
258 addToNamespace(type, key, value);
261 static final Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements(
262 final List<ReactorStmtCtx<?, ?, ?>> effective) {
263 return effective instanceof ImmutableCollection ? effective : Collections.unmodifiableCollection(effective);
266 private static List<ReactorStmtCtx<?, ?, ?>> shrinkEffective(final List<ReactorStmtCtx<?, ?, ?>> effective) {
267 return effective.isEmpty() ? ImmutableList.of() : effective;
270 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef);
272 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
273 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef) {
274 if (effective.isEmpty()) {
278 final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
279 while (iterator.hasNext()) {
280 final StmtContext<?, ?, ?> next = iterator.next();
281 if (statementDef.equals(next.publicDefinition())) {
286 return shrinkEffective(effective);
290 * Removes a statement context from the effective substatements based on its statement definition (i.e statement
291 * keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
292 * definition and statement argument match with one of the effective substatements' statement definition
296 * If the statementArg parameter is null, the statement context is removed based only on its statement definition.
298 * @param statementDef statement definition of the statement context to remove
299 * @param statementArg statement argument of the statement context to remove
301 public abstract void removeStatementFromEffectiveSubstatements(StatementDefinition statementDef,
302 String statementArg);
304 static final List<ReactorStmtCtx<?, ?, ?>> removeStatementFromEffectiveSubstatements(
305 final List<ReactorStmtCtx<?, ?, ?>> effective, final StatementDefinition statementDef,
306 final String statementArg) {
307 if (statementArg == null) {
308 return removeStatementFromEffectiveSubstatements(effective, statementDef);
311 if (effective.isEmpty()) {
315 final Iterator<ReactorStmtCtx<?, ?, ?>> iterator = effective.iterator();
316 while (iterator.hasNext()) {
317 final Mutable<?, ?, ?> next = iterator.next();
318 if (statementDef.equals(next.publicDefinition()) && statementArg.equals(next.rawArgument())) {
323 return shrinkEffective(effective);
326 // YANG example: RPC/action statements always have 'input' and 'output' defined
328 public <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> @NonNull Mutable<X, Y, Z>
329 appendImplicitSubstatement(final StatementSupport<X, Y, Z> support, final String rawArg) {
330 // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
331 // StatementContextBase subclass.
332 final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
333 ImplicitSubstatement.of(sourceReference()), rawArg);
334 support.onStatementAdded(ret);
335 addEffectiveSubstatement(ret);
340 * Adds an effective statement to collection of substatements.
342 * @param substatement substatement
343 * @throws IllegalStateException if added in declared phase
344 * @throws NullPointerException if statement parameter is null
346 public abstract void addEffectiveSubstatement(Mutable<?, ?, ?> substatement);
348 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
349 final Mutable<?, ?, ?> substatement) {
350 verifyStatement(substatement);
352 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, 1);
353 final ReactorStmtCtx<?, ?, ?> stmt = (ReactorStmtCtx<?, ?, ?>) substatement;
354 ensureCompletedExecution(stmt);
360 * Adds an effective statement to collection of substatements.
362 * @param statements substatements
363 * @throws IllegalStateException
364 * if added in declared phase
365 * @throws NullPointerException
366 * if statement parameter is null
368 public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
369 if (!statements.isEmpty()) {
370 statements.forEach(StatementContextBase::verifyStatement);
371 addEffectiveSubstatementsImpl(statements);
375 abstract void addEffectiveSubstatementsImpl(Collection<? extends Mutable<?, ?, ?>> statements);
377 final List<ReactorStmtCtx<?, ?, ?>> addEffectiveSubstatementsImpl(final List<ReactorStmtCtx<?, ?, ?>> effective,
378 final Collection<? extends Mutable<?, ?, ?>> statements) {
379 final List<ReactorStmtCtx<?, ?, ?>> resized = beforeAddEffectiveStatement(effective, statements.size());
380 final Collection<? extends ReactorStmtCtx<?, ?, ?>> casted =
381 (Collection<? extends ReactorStmtCtx<?, ?, ?>>) statements;
382 if (executionOrder != ExecutionOrder.NULL) {
383 for (ReactorStmtCtx<?, ?, ?> stmt : casted) {
384 ensureCompletedExecution(stmt, executionOrder);
388 resized.addAll(casted);
392 abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
394 // exposed for InferredStatementContext only
395 final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
396 verifyStatement(stmt);
397 ensureCompletedExecution((ReactorStmtCtx<?, ?, ?>) stmt);
400 // Make sure target statement has transitioned at least to our phase (if we have one). This method is just before we
401 // take allow a statement to become our substatement. This is needed to ensure that every statement tree does not
402 // contain any statements which did not complete the same phase as the root statement.
403 private void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt) {
404 if (executionOrder != ExecutionOrder.NULL) {
405 ensureCompletedExecution(stmt, executionOrder);
409 private static void ensureCompletedExecution(final ReactorStmtCtx<?, ?, ?> stmt, final byte executionOrder) {
410 verify(stmt.tryToCompletePhase(executionOrder), "Statement %s cannot complete phase %s", stmt, executionOrder);
413 private static void verifyStatement(final Mutable<?, ?, ?> stmt) {
414 verify(stmt instanceof ReactorStmtCtx, "Unexpected statement %s", stmt);
417 private List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatement(final List<ReactorStmtCtx<?, ?, ?>> effective,
419 // We cannot allow statement to be further mutated.
420 // TODO: we really want to say 'not NULL and not at or after EFFECTIVE_MODEL here. This will matter if we have
421 // a phase after EFFECTIVE_MODEL
422 verify(executionOrder != ExecutionOrder.EFFECTIVE_MODEL, "Cannot modify finished statement at %s",
424 return beforeAddEffectiveStatementUnsafe(effective, toAdd);
427 final List<ReactorStmtCtx<?, ?, ?>> beforeAddEffectiveStatementUnsafe(final List<ReactorStmtCtx<?, ?, ?>> effective,
429 final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
430 checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
431 || inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
432 "Effective statement cannot be added in declared phase at: %s", sourceReference());
434 return effective.isEmpty() ? new ArrayList<>(toAdd) : effective;
438 final E createEffective() {
439 final E result = createEffective(definition.getFactory());
440 if (result instanceof MutableStatement) {
441 getRoot().addMutableStmtToSeal((MutableStatement) result);
446 @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
447 return createEffective(factory, this);
450 // Creates EffectiveStatement through full materialization
451 static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
452 final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
453 return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
457 * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
458 * {@link StmtContext#buildEffective()} contract.
460 * @return Stream of supported declared statements.
462 // FIXME: we really want to unify this with streamEffective(), under its name
463 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared();
466 * Return a stream of inferred statements which can be built into an {@link EffectiveStatement}, as per
467 * {@link StmtContext#buildEffective()} contract.
469 * @return Stream of supported effective statements.
471 // FIXME: this method is currently a misnomer, but unifying with streamDeclared() would make this accurate again
472 abstract Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective();
475 final boolean doTryToCompletePhase(final byte targetOrder) {
476 final boolean finished = phaseMutation.isEmpty() || runMutations(targetOrder);
477 if (completeChildren(targetOrder) && finished) {
478 onPhaseCompleted(targetOrder);
484 private boolean completeChildren(final byte targetOrder) {
485 boolean finished = true;
486 for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
487 finished &= child.tryToCompletePhase(targetOrder);
489 for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
490 finished &= child.tryToCompletePhase(targetOrder);
495 private boolean runMutations(final byte targetOrder) {
496 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(targetOrder));
497 final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
498 return openMutations.isEmpty() || runMutations(phase, openMutations);
501 private boolean runMutations(final ModelProcessingPhase phase, final Collection<ContextMutation> openMutations) {
502 boolean finished = true;
503 final Iterator<ContextMutation> it = openMutations.iterator();
504 while (it.hasNext()) {
505 final ContextMutation current = it.next();
506 if (current.isFinished()) {
513 if (openMutations.isEmpty()) {
514 phaseMutation.removeAll(phase);
515 cleanupPhaseMutation();
520 private void cleanupPhaseMutation() {
521 if (phaseMutation.isEmpty()) {
522 phaseMutation = ImmutableMultimap.of();
527 * Occurs on end of {@link ModelProcessingPhase} of source parsing. This method must not be called with
528 * {@code executionOrder} equal to {@link ExecutionOrder#NULL}.
530 * @param phase that was to be completed (finished)
531 * @throws SourceException when an error occurred in source parsing
533 private void onPhaseCompleted(final byte completedOrder) {
534 executionOrder = completedOrder;
535 if (completedOrder == ExecutionOrder.EFFECTIVE_MODEL) {
536 // We have completed effective model, substatements are guaranteed not to change
537 summarizeSubstatementPolicy();
540 final ModelProcessingPhase phase = verifyNotNull(ModelProcessingPhase.ofExecutionOrder(completedOrder));
541 final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
542 if (!listeners.isEmpty()) {
543 runPhaseListeners(phase, listeners);
547 private void summarizeSubstatementPolicy() {
548 if (definition().support().copyPolicy() == CopyPolicy.EXACT_REPLICA || noSensitiveSubstatements()) {
549 setAllSubstatementsContextIndependent();
554 * Determine whether any substatements are copy-sensitive as determined by {@link StatementSupport#copyPolicy()}.
555 * Only {@link CopyPolicy#CONTEXT_INDEPENDENT}, {@link CopyPolicy#EXACT_REPLICA} and {@link CopyPolicy#IGNORE} are
556 * copy-insensitive. Note that statements which are not {@link StmtContext#isSupportedToBuildEffective()} are all
557 * considered copy-insensitive.
560 * Implementations are expected to call {@link #noSensitiveSubstatements()} to actually traverse substatement sets.
562 * @return True if no substatements require copy-sensitive handling
564 abstract boolean noSensitiveSubstatements();
567 * Determine whether any of the provided substatements are context-sensitive for purposes of implementing
568 * {@link #noSensitiveSubstatements()}.
570 * @param substatements Substatements to check
571 * @return True if no substatements require context-sensitive handling
573 static boolean noSensitiveSubstatements(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
574 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
575 if (stmt.isSupportedToBuildEffective()) {
576 if (!stmt.allSubstatementsContextIndependent()) {
577 // This is a recursive property
581 switch (stmt.definition().support().copyPolicy()) {
582 case CONTEXT_INDEPENDENT:
594 private void runPhaseListeners(final ModelProcessingPhase phase, final Collection<OnPhaseFinished> listeners) {
595 final Iterator<OnPhaseFinished> listener = listeners.iterator();
596 while (listener.hasNext()) {
597 final OnPhaseFinished next = listener.next();
598 if (next.phaseFinished(this, phase)) {
603 if (listeners.isEmpty()) {
604 phaseListeners.removeAll(phase);
605 if (phaseListeners.isEmpty()) {
606 phaseListeners = ImmutableMultimap.of();
612 * Ends declared section of current node.
614 void endDeclared(final ModelProcessingPhase phase) {
615 definition.onDeclarationFinished(this, phase);
619 final StatementDefinitionContext<A, D, E> definition() {
623 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
624 final OnNamespaceItemAdded listener) {
625 final Object potential = getFromNamespace(type, key);
626 if (potential != null) {
627 LOG.trace("Listener on {} key {} satisfied immediately", type, key);
628 listener.namespaceItemAdded(this, type, key, potential);
632 getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
634 void onValueAdded(final Object value) {
635 listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
640 final <K, V, N extends ParserNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
641 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
642 final OnNamespaceItemAdded listener) {
643 final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
644 if (existing.isPresent()) {
645 final Entry<K, V> entry = existing.get();
646 LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
647 waitForPhase(entry.getValue(), type, phase, criterion, listener);
651 final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
652 behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
654 boolean onValueAdded(final K key, final V value) {
655 if (criterion.match(key)) {
656 LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
657 waitForPhase(value, type, phase, criterion, listener);
666 final <K, V, N extends ParserNamespace<K, V>> void selectMatch(final Class<N> type,
667 final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
668 final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
669 checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
671 final Entry<K, V> match = optMatch.get();
672 listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
675 final <K, V, N extends ParserNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
676 final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
677 final OnNamespaceItemAdded listener) {
678 ((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
679 (context, phaseCompleted) -> {
680 selectMatch(type, criterion, listener);
685 private <K, V, N extends ParserNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
686 final Class<N> type) {
687 final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
688 checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
691 return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
694 private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
695 return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
699 * Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
700 * the listener is notified immediately.
702 * @param phase requested completion phase
703 * @param listener listener to invoke
704 * @throws NullPointerException if any of the arguments is null
706 void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
707 requireNonNull(phase, "Statement context processing phase cannot be null");
708 requireNonNull(listener, "Statement context phase listener cannot be null");
710 ModelProcessingPhase finishedPhase = ModelProcessingPhase.ofExecutionOrder(executionOrder);
711 while (finishedPhase != null) {
712 if (phase.equals(finishedPhase)) {
713 listener.phaseFinished(this, finishedPhase);
716 finishedPhase = finishedPhase.getPreviousPhase();
718 if (phaseListeners.isEmpty()) {
719 phaseListeners = newMultimap();
722 phaseListeners.put(phase, listener);
726 * Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
728 * @throws IllegalStateException when the mutation was registered after phase was completed
730 final void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
731 checkState(executionOrder < phase.executionOrder(), "Mutation registered after phase was completed at: %s",
734 if (phaseMutation.isEmpty()) {
735 phaseMutation = newMultimap();
737 phaseMutation.put(phase, mutation);
740 final void removeMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
741 if (!phaseMutation.isEmpty()) {
742 phaseMutation.remove(phase, mutation);
743 cleanupPhaseMutation();
748 public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
749 final KT key,final StmtContext<?, ?, ?> stmt) {
750 addContextToNamespace(namespace, key, stmt);
754 public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> parent, final CopyType type,
755 final QNameModule targetModule) {
756 checkEffectiveModelCompleted(this);
757 return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
760 private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
761 final QNameModule targetModule) {
762 final StatementSupport<A, D, E> support = definition.support();
763 final CopyPolicy policy = support.copyPolicy();
766 return replicaAsChildOf(parent);
767 case CONTEXT_INDEPENDENT:
768 if (allSubstatementsContextIndependent()) {
769 return replicaAsChildOf(parent);
775 return (ReactorStmtCtx<A, D, E>) parent.childCopyOf(this, type, targetModule);
779 throw new IllegalStateException("Statement " + support.getPublicView() + " should never be copied");
781 throw new IllegalStateException("Unhandled policy " + policy);
786 final ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> parent, final CopyType type,
787 final QNameModule targetModule) {
788 final ReactorStmtCtx<A, D, E> copy = copyAsChildOfImpl(parent, type, targetModule);
790 // The statement fizzled, this should never happen, perhaps a verify()?
794 parent.ensureCompletedPhase(copy);
795 return canReuseCurrent(copy) ? this : copy;
798 private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
799 // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
800 // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
801 return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
802 && allSubstatementsContextIndependent();
806 public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
807 final QNameModule targetModule) {
808 checkEffectiveModelCompleted(stmt);
809 if (stmt instanceof StatementContextBase) {
810 return childCopyOf((StatementContextBase<?, ?, ?>) stmt, type, targetModule);
811 } else if (stmt instanceof ReplicaStatementContext) {
812 return ((ReplicaStatementContext<?, ?, ?>) stmt).replicaAsChildOf(this);
814 throw new IllegalArgumentException("Unsupported statement " + stmt);
818 private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
819 final StatementContextBase<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
820 final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
821 original.publicDefinition());
823 final StatementContextBase<X, Y, Z> result;
824 final InferredStatementContext<X, Y, Z> copy;
826 if (implicitParent.isPresent()) {
827 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
828 result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
829 original.argument(), type);
831 final CopyType childCopyType;
833 case ADDED_BY_AUGMENTATION:
834 childCopyType = CopyType.ORIGINAL;
836 case ADDED_BY_USES_AUGMENTATION:
837 childCopyType = CopyType.ADDED_BY_USES;
842 childCopyType = type;
845 copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
846 result.addEffectiveSubstatement(copy);
848 result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
851 original.definition.onStatementAdded(copy);
856 final ReplicaStatementContext<A, D, E> replicaAsChildOf(final StatementContextBase<?, ?, ?> parent) {
857 return new ReplicaStatementContext<>(parent, this);
860 private static void checkEffectiveModelCompleted(final StmtContext<?, ?, ?> stmt) {
861 final ModelProcessingPhase phase = stmt.getCompletedPhase();
862 checkState(phase == ModelProcessingPhase.EFFECTIVE_MODEL,
863 "Attempted to copy statement %s which has completed phase %s", stmt, phase);
867 // FIXME: this information should be exposed as a well-known Namespace
868 public final boolean hasImplicitParentSupport() {
869 return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
873 public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
874 final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
875 original.publicDefinition());
876 if (optImplicit.isEmpty()) {
880 final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
881 final CopyType type = original.history().getLastOperation();
882 final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
883 original.sourceReference(), original.rawArgument(), original.argument(), type);
885 result.addEffectiveSubstatement(original.reparent(result));
886 result.setCompletedPhase(original.getCompletedPhase());
890 abstract StatementContextBase<A, D, E> reparent(StatementContextBase<?, ?, ?> newParent);
893 * Indicate that the set of substatements is empty. This is a preferred shortcut to substatement stream filtering.
895 * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
897 abstract boolean hasEmptySubstatements();