2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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.Verify.verify;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.base.VerifyException;
16 import java.util.Collection;
18 import java.util.Optional;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.yangtools.yang.common.Empty;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.common.QNameModule;
25 import org.opendaylight.yangtools.yang.common.YangVersion;
26 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
29 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
34 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
35 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStatementState;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.ExecutionOrder;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
48 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
49 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * Real "core" reactor statement implementation of {@link Mutable}, supporting basic reactor lifecycle.
56 * @param <A> Argument type
57 * @param <D> Declared Statement representation
58 * @param <E> Effective Statement representation
60 abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
61 extends NamespaceStorageSupport implements Mutable<A, D, E>, Current<A, D> {
62 private static final Logger LOG = LoggerFactory.getLogger(ReactorStmtCtx.class);
65 * Substatement refcount tracking. This mechanics deals with retaining substatements for the purposes of
66 * instantiating their lazy copies in InferredStatementContext. It works in concert with {@link #buildEffective()}
67 * and {@link #declared()}: declared/effective statement views hold an implicit reference and refcount-based
68 * sweep is not activated until they are done (or this statement is not {@link #isSupportedToBuildEffective}).
71 * Reference count is hierarchical in that parent references also pin down their child statements and do not allow
75 * The counter's positive values are tracking incoming references via {@link #incRef()}/{@link #decRef()} methods.
76 * Once we transition to sweeping, this value becomes negative counting upwards to {@link #REFCOUNT_NONE} based on
77 * {@link #sweepOnChildDone()}. Once we reach that, we transition to {@link #REFCOUNT_SWEPT}.
79 private int refcount = REFCOUNT_NONE;
81 * No outstanding references, this statement is a potential candidate for sweeping, provided it has populated its
82 * declared and effective views and {@link #parentRef} is known to be absent.
84 private static final int REFCOUNT_NONE = 0;
86 * Reference count overflow or some other recoverable logic error. Do not rely on refcounts and do not sweep
90 * Note on value assignment:
91 * This allow our incRef() to naturally progress to being saturated. Others jump there directly.
92 * It also makes it it impossible to observe {@code Interger.MAX_VALUE} children, which we take advantage of for
93 * {@link #REFCOUNT_SWEEPING}.
95 private static final int REFCOUNT_DEFUNCT = Integer.MAX_VALUE;
97 * This statement is being actively swept. This is a transient value set when we are sweeping our children, so that
98 * we prevent re-entering this statement.
101 * Note on value assignment:
102 * The value is lower than any legal child refcount due to {@link #REFCOUNT_DEFUNCT} while still being higher than
103 * {@link #REFCOUNT_SWEPT}.
105 private static final int REFCOUNT_SWEEPING = -Integer.MAX_VALUE;
107 * This statement, along with its entire subtree has been swept and we positively know all our children have reached
108 * this state. We {@link #sweepNamespaces()} upon reaching this state.
111 * Note on value assignment:
112 * This is the lowest value observable, making it easier on checking others on equality.
114 private static final int REFCOUNT_SWEPT = Integer.MIN_VALUE;
117 * Effective instance built from this context. This field as dual types. Under normal circumstances in matches the
118 * {@link #buildEffective()} instance. If this context is reused, it can be inflated to {@link EffectiveInstances}
119 * and also act as a common instance reuse site.
121 private @Nullable Object effectiveInstance;
123 // Master flag controlling whether this context can yield an effective statement
124 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
125 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
126 private boolean isSupportedToBuildEffective = true;
128 // EffectiveConfig mapping
129 private static final int MASK_CONFIG = 0x03;
130 private static final int HAVE_CONFIG = 0x04;
131 // Effective instantiation mechanics for StatementContextBase: if this flag is set all substatements are known not
132 // change when instantiated. This includes context-independent statements as well as any statements which are
133 // ignored during copy instantiation.
134 private static final int ALL_INDEPENDENT = 0x08;
135 // Flag bit assignments
136 private static final int IS_SUPPORTED_BY_FEATURES = 0x10;
137 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x20;
138 private static final int IS_IGNORE_IF_FEATURE = 0x40;
139 private static final int HAVE_IGNORE_IF_FEATURE = 0x80;
140 // Have-and-set flag constants, also used as masks
141 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
142 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
144 private static final EffectiveConfig[] EFFECTIVE_CONFIGS;
147 final EffectiveConfig[] values = EffectiveConfig.values();
148 final int length = values.length;
149 verify(length == 4, "Unexpected EffectiveConfig cardinality %s", length);
150 EFFECTIVE_CONFIGS = values;
153 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
154 // hence improve memory layout.
157 // Flag for use by AbstractResumedStatement, ReplicaStatementContext and InferredStatementContext. Each of them
158 // uses it to indicated a different condition. This is hiding in the alignment shadow created by
159 // 'isSupportedToBuildEffective'.
160 // FIXME: move this out once we have JDK15+
161 private boolean boolFlag;
167 ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
168 isSupportedToBuildEffective = original.isSupportedToBuildEffective;
169 boolFlag = original.boolFlag;
170 flags = original.flags;
173 // Used by ReplicaStatementContext only
174 ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original, final Void dummy) {
175 boolFlag = isSupportedToBuildEffective = original.isSupportedToBuildEffective;
176 flags = original.flags;
181 // Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
182 // up mixing concerns and simple details with more complex logic.
187 public abstract StatementContextBase<?, ?, ?> getParentContext();
190 public abstract RootStatementContext<?, ?, ?> getRoot();
193 public abstract Collection<? extends @NonNull StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
196 public final Registry getBehaviourRegistry() {
197 return getRoot().getBehaviourRegistryImpl();
201 public final YangVersion yangVersion() {
202 return getRoot().getRootVersionImpl();
206 public final void setRootVersion(final YangVersion version) {
207 getRoot().setRootVersionImpl(version);
211 public final void addRequiredSource(final SourceIdentifier dependency) {
212 getRoot().addRequiredSourceImpl(dependency);
216 public final void setRootIdentifier(final SourceIdentifier identifier) {
217 getRoot().setRootIdentifierImpl(identifier);
221 public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
222 return getRoot().getSourceContext().newInferenceAction(phase);
226 public final StatementDefinition publicDefinition() {
227 return definition().getPublicView();
231 public final Parent effectiveParent() {
232 return getParentContext();
236 public final QName moduleName() {
237 final RootStatementContext<?, ?, ?> root = getRoot();
238 return QName.create(StmtContextUtils.getRootModuleQName(root), root.getRawArgument());
242 // In the next two methods we are looking for an effective statement. If we already have an effective instance,
243 // defer to it's implementation of the equivalent search. Otherwise we search our substatement contexts.
245 // Note that the search function is split, so as to allow InferredStatementContext to do its own thing first.
249 public final <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
250 final @NonNull Class<Z> type) {
251 final E existing = effectiveInstance();
252 return existing != null ? existing.findFirstEffectiveSubstatementArgument(type)
253 : findSubstatementArgumentImpl(type);
257 public final boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
258 final E existing = effectiveInstance();
259 return existing != null ? existing.findFirstEffectiveSubstatement(type).isPresent() : hasSubstatementImpl(type);
262 private E effectiveInstance() {
263 final Object existing = effectiveInstance;
264 return existing != null ? EffectiveInstances.local(existing) : null;
267 // Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
268 <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
269 final @NonNull Class<Z> type) {
270 return allSubstatementsStream()
271 .filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
273 .map(ctx -> (X) ctx.getArgument());
276 // Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
277 boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
278 return allSubstatementsStream()
279 .anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
284 @SuppressWarnings("unchecked")
285 public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
286 return (StmtContext<A, D, Z>) this;
290 public final String toString() {
291 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
294 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
295 return toStringHelper.add("definition", definition()).add("argument", argument()).add("refCount", refString());
298 private String refString() {
299 final int current = refcount;
301 case REFCOUNT_DEFUNCT:
303 case REFCOUNT_SWEEPING:
308 return String.valueOf(refcount);
313 * Return the context in which this statement was defined.
315 * @return statement definition
317 abstract @NonNull StatementDefinitionContext<A, D, E> definition();
321 // NamespaceStorageSupport/Mutable integration methods. Keep these together.
326 public final <K, V, T extends K, N extends ParserNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
328 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
332 public final <K, V, N extends ParserNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
333 return getNamespace(type);
337 public final <K, V, N extends ParserNamespace<K, V>>
338 Map<K, V> localNamespacePortion(final Class<@NonNull N> type) {
339 return getLocalNamespace(type);
343 protected <K, V, N extends ParserNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
345 // definition().onNamespaceElementAdded(this, type, key, value);
349 * Return the effective statement view of a copy operation. This method may return one of:
351 * <li>{@code this}, when the effective view did not change</li>
352 * <li>an InferredStatementContext, when there is a need for inference-equivalent copy</li>
353 * <li>{@code null}, when the statement failed to materialize</li>
356 * @param parent Proposed new parent
357 * @param type Copy operation type
358 * @param targetModule New target module
359 * @return {@link ReactorStmtCtx} holding effective view
361 abstract @Nullable ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(StatementContextBase<?, ?, ?> parent, CopyType type,
362 QNameModule targetModule);
365 public final ReplicaStatementContext<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
366 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
367 final var ret = replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
368 definition().onStatementAdded(ret);
372 abstract @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(@NonNull StatementContextBase<?, ?, ?> parent);
376 // Statement build entry points -- both public and package-private.
381 public final E buildEffective() {
382 final Object existing;
383 return (existing = effectiveInstance) != null ? EffectiveInstances.local(existing) : loadEffective();
386 private @NonNull E loadEffective() {
387 final E ret = createEffective();
388 effectiveInstance = ret;
389 // we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
391 if (refcount == REFCOUNT_NONE) {
397 abstract @NonNull E createEffective();
400 * Attach an effective copy of this statement. This essentially acts as a map, where we make a few assumptions:
402 * <li>{@code copy} and {@code this} statement share {@link #getOriginalCtx()} if it exists</li>
403 * <li>{@code copy} did not modify any statements relative to {@code this}</li>
406 * @param state effective statement state, acting as a lookup key
407 * @param stmt New copy to append
408 * @return {@code stmt} or a previously-created instances with the same {@code state}
410 @SuppressWarnings("unchecked")
411 final @NonNull E attachEffectiveCopy(final @NonNull EffectiveStatementState state, final @NonNull E stmt) {
412 final Object local = effectiveInstance;
413 final EffectiveInstances<E> instances;
414 if (local instanceof EffectiveInstances) {
415 instances = (EffectiveInstances<E>) local;
417 effectiveInstance = instances = new EffectiveInstances<>((E) local);
419 return instances.attachCopy(state, stmt);
423 * Walk this statement's copy history and return the statement closest to original which has not had its effective
424 * statements modified. This statement and returned substatement logically have the same set of substatements, hence
425 * share substatement-derived state.
427 * @return Closest {@link ReactorStmtCtx} with equivalent effective substatements
429 abstract @NonNull ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource();
432 public final ModelProcessingPhase getCompletedPhase() {
433 return ModelProcessingPhase.ofExecutionOrder(executionOrder());
436 abstract byte executionOrder();
439 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
440 * this method does nothing. This must not be called with {@link ExecutionOrder#NULL}.
442 * @param phase to be executed (completed)
443 * @return true if phase was successfully completed
444 * @throws SourceException when an error occurred in source parsing
446 final boolean tryToCompletePhase(final byte executionOrder) {
447 return executionOrder() >= executionOrder || doTryToCompletePhase(executionOrder);
450 abstract boolean doTryToCompletePhase(byte targetOrder);
454 // Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
460 public final boolean isSupportedToBuildEffective() {
461 return isSupportedToBuildEffective;
465 public final void setUnsupported() {
466 this.isSupportedToBuildEffective = false;
470 public final boolean isSupportedByFeatures() {
471 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
473 return fl == SET_SUPPORTED_BY_FEATURES;
475 if (isIgnoringIfFeatures()) {
476 flags |= SET_SUPPORTED_BY_FEATURES;
481 * If parent is supported, we need to check if-features statements of this context.
483 if (isParentSupportedByFeatures()) {
484 // If the set of supported features has not been provided, all features are supported by default.
485 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class, Empty.value());
486 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
487 flags |= SET_SUPPORTED_BY_FEATURES;
492 // Either parent is not supported or this statement is not supported
493 flags |= HAVE_SUPPORTED_BY_FEATURES;
497 protected abstract boolean isParentSupportedByFeatures();
500 * Config statements are not all that common which means we are performing a recursive search towards the root
501 * every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
502 * for the (usually non-existent) config statement.
505 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
506 * result without performing any lookups, solely to support {@link #effectiveConfig()}.
509 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
510 * {@link #isIgnoringConfig(StatementContextBase)}.
512 final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
513 return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
516 private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
517 final EffectiveConfig parentConfig = parent.effectiveConfig();
519 final EffectiveConfig myConfig;
520 if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
521 final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
522 if (optConfig.isPresent()) {
523 if (optConfig.orElseThrow()) {
524 // Validity check: if parent is config=false this cannot be a config=true
525 InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
526 "Parent node has config=false, this node must not be specifed as config=true");
527 myConfig = EffectiveConfig.TRUE;
529 myConfig = EffectiveConfig.FALSE;
532 // If "config" statement is not specified, the default is the same as the parent's "config" value.
533 myConfig = parentConfig;
536 myConfig = EffectiveConfig.IGNORED;
539 flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
543 protected abstract boolean isIgnoringConfig();
546 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
547 * keep on returning the same result without performing any lookups. Exists only to support
548 * {@link SubstatementContext#isIgnoringConfig()}.
551 * Note: use of this method implies that {@link #isConfiguration()} is realized with
552 * {@link #effectiveConfig(StatementContextBase)}.
554 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
555 return EffectiveConfig.IGNORED == effectiveConfig(parent);
558 protected abstract boolean isIgnoringIfFeatures();
561 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
562 * keep on returning the same result without performing any lookups. Exists only to support
563 * {@link SubstatementContext#isIgnoringIfFeatures()}.
565 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
566 final int fl = flags & SET_IGNORE_IF_FEATURE;
568 return fl == SET_IGNORE_IF_FEATURE;
570 if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
571 flags |= SET_IGNORE_IF_FEATURE;
575 flags |= HAVE_IGNORE_IF_FEATURE;
579 // These two exist only due to memory optimization, should live in AbstractResumedStatement.
580 final boolean fullyDefined() {
584 final void setFullyDefined() {
588 // This exists only due to memory optimization, should live in ReplicaStatementContext. In this context the flag
589 // indicates the need to drop source's reference count when we are being swept.
590 final boolean haveSourceReference() {
594 // These three exist due to memory optimization, should live in InferredStatementContext. In this context the flag
595 // indicates whether or not this statement's substatement file was modified, i.e. it is not quite the same as the
597 final boolean isModified() {
601 final void setModified() {
605 final void setUnmodified() {
609 // These two exist only for StatementContextBase. Since we are squeezed for size, with only a single bit available
610 // in flags, we default to 'false' and only set the flag to true when we are absolutely sure -- and all other cases
611 // err on the side of caution by taking the time to evaluate each substatement separately.
612 final boolean allSubstatementsContextIndependent() {
613 return (flags & ALL_INDEPENDENT) != 0;
616 final void setAllSubstatementsContextIndependent() {
617 flags |= ALL_INDEPENDENT;
622 // Various functionality from AbstractTypeStatementSupport. This used to work on top of SchemaPath, now it still
623 // lives here. Ultimate future is either proper graduation or (more likely) move to AbstractTypeStatementSupport.
628 public final QName argumentAsTypeQName() {
629 // FIXME: This may yield illegal argument exceptions
630 return StmtContextUtils.qnameFromArgument(getOriginalCtx().orElse(this), getRawArgument());
634 public final QNameModule effectiveNamespace() {
635 if (StmtContextUtils.isUnknownStatement(this)) {
636 return publicDefinition().getStatementName().getModule();
638 if (producesDeclared(UsesStatement.class)) {
639 return coerceParent().effectiveNamespace();
642 final Object argument = argument();
643 if (argument instanceof QName) {
644 return ((QName) argument).getModule();
646 if (argument instanceof String) {
647 // FIXME: This may yield illegal argument exceptions
648 return StmtContextUtils.qnameFromArgument(getOriginalCtx().orElse(this), (String) argument).getModule();
650 if (argument instanceof SchemaNodeIdentifier
651 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
652 || producesDeclared(DeviationStatement.class))) {
653 return ((SchemaNodeIdentifier) argument).lastNodeIdentifier().getModule();
656 return coerceParent().effectiveNamespace();
659 private ReactorStmtCtx<?, ?, ?> coerceParent() {
660 return (ReactorStmtCtx<?, ?, ?>) coerceParentContext();
665 // Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
666 // contribute to state visible outside of this package.
671 * Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
672 * in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
673 * knowledge and update it when {@link #sweep()} is invoked.
675 private byte parentRef = PARENTREF_UNKNOWN;
676 private static final byte PARENTREF_UNKNOWN = -1;
677 private static final byte PARENTREF_ABSENT = 0;
678 private static final byte PARENTREF_PRESENT = 1;
681 * Acquire a reference on this context. As long as there is at least one reference outstanding,
682 * {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
684 * @throws VerifyException if {@link #effectiveSubstatements()} has already been discarded
686 final void incRef() {
687 final int current = refcount;
688 verify(current >= REFCOUNT_NONE, "Attempted to access reference count of %s", this);
689 if (current != REFCOUNT_DEFUNCT) {
690 // Note: can end up becoming REFCOUNT_DEFUNCT on overflow
691 refcount = current + 1;
693 LOG.debug("Disabled refcount increment of {}", this);
698 * Release a reference on this context. This call may result in {@link #effectiveSubstatements()} becoming
701 final void decRef() {
702 final int current = refcount;
703 if (current == REFCOUNT_DEFUNCT) {
705 LOG.debug("Disabled refcount decrement of {}", this);
708 if (current <= REFCOUNT_NONE) {
709 // Underflow, become defunct
710 // FIXME: add a global 'warn once' flag
711 LOG.warn("Statement refcount underflow, reference counting disabled for {}", this, new Throwable());
712 refcount = REFCOUNT_DEFUNCT;
716 refcount = current - 1;
717 LOG.trace("Refcount {} on {}", refcount, this);
719 if (refcount == REFCOUNT_NONE) {
725 * Return {@code true} if this context has no outstanding references.
727 * @return True if this context has no outstanding references.
729 final boolean noRefs() {
730 final int local = refcount;
731 return local < REFCOUNT_NONE || local == REFCOUNT_NONE && noParentRef();
734 private void lastDecRef() {
735 if (noImplictRef()) {
736 // We are no longer guarded by effective instance
741 final byte prevRefs = parentRef;
742 if (prevRefs == PARENTREF_ABSENT) {
743 // We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
746 } else if (prevRefs == PARENTREF_UNKNOWN) {
747 // Noone observed our parentRef, just update it
748 loadParentRefcount();
752 static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
753 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
754 final byte prevRef = stmt.parentRef;
755 stmt.parentRef = PARENTREF_ABSENT;
756 if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
757 // Child thinks it is pinned down, update its perspective
758 stmt.markNoParentRef();
763 abstract void markNoParentRef();
765 static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
766 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
772 * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
774 private void sweep() {
775 parentRef = PARENTREF_ABSENT;
776 if (refcount == REFCOUNT_NONE && noImplictRef()) {
777 LOG.trace("Releasing {}", this);
782 static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
784 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
785 if (stmt.refcount > REFCOUNT_NONE || !stmt.noImplictRef()) {
793 * Implementation-specific sweep action. This is expected to perform a recursive {@link #sweep(Collection)} on all
794 * {@link #declaredSubstatements()} and {@link #effectiveSubstatements()} and report the result of the sweep
798 * {@link #effectiveSubstatements()} as well as namespaces may become inoperable as a result of this operation.
800 * @return True if the entire tree has been completely swept, false otherwise.
802 abstract int sweepSubstatements();
804 // Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
805 private void sweepOnDecrement() {
806 LOG.trace("Sweeping on decrement {}", this);
808 // No further parent references, sweep our state.
812 // Propagate towards parent if there is one
816 private void sweepParent() {
817 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
818 if (parent != null) {
819 parent.sweepOnChildDecrement();
823 // Called from child when it has lost its final reference
824 private void sweepOnChildDecrement() {
825 if (isAwaitingChildren()) {
826 // We are a child for which our parent is waiting. Notify it and we are done.
831 // Check parent reference count
832 final int refs = refcount;
833 if (refs > REFCOUNT_NONE || refs <= REFCOUNT_SWEEPING || !noImplictRef()) {
838 // parent is potentially reclaimable
840 LOG.trace("Cleanup {} of parent {}", refs, this);
847 private boolean noImplictRef() {
848 return effectiveInstance != null || !isSupportedToBuildEffective();
851 private boolean noParentRef() {
852 return parentRefcount() == PARENTREF_ABSENT;
855 private byte parentRefcount() {
857 return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
860 private byte loadParentRefcount() {
861 return parentRef = calculateParentRefcount();
864 private byte calculateParentRefcount() {
865 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
866 if (parent == null) {
867 return PARENTREF_ABSENT;
870 // A slight wrinkle here is that our machinery handles only PRESENT -> ABSENT invalidation and we can reach here
871 // while inference is still ongoing and hence we may not have a complete picture about existing references. We
872 // could therefore end up caching an ABSENT result and then that information becoming stale as a new reference
874 if (parent.executionOrder() < ExecutionOrder.EFFECTIVE_MODEL) {
875 return PARENTREF_UNKNOWN;
878 // There are three possibilities:
879 // - REFCOUNT_NONE, in which case we need to search next parent
880 // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
882 // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
883 final int refs = parent.refcount;
884 if (refs == REFCOUNT_NONE) {
885 return parent.parentRefcount();
887 return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
890 private boolean isAwaitingChildren() {
891 return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
894 private void sweepOnChildDone() {
895 LOG.trace("Sweeping on child done {}", this);
896 final int current = refcount;
897 if (current >= REFCOUNT_NONE) {
898 // no-op, perhaps we want to handle some cases differently?
899 LOG.trace("Ignoring child sweep of {} for {}", this, current);
902 verify(current != REFCOUNT_SWEPT, "Attempt to sweep a child of swept %s", this);
904 refcount = current + 1;
905 LOG.trace("Child refcount {}", refcount);
906 if (refcount == REFCOUNT_NONE) {
908 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
909 LOG.trace("Propagating to parent {}", parent);
910 if (parent != null && parent.isAwaitingChildren()) {
911 parent.sweepOnChildDone();
916 private void sweepDone() {
917 LOG.trace("Sweep done for {}", this);
918 refcount = REFCOUNT_SWEPT;
922 private boolean sweepState() {
923 refcount = REFCOUNT_SWEEPING;
924 final int childRefs = sweepSubstatements();
925 if (childRefs == 0) {
929 if (childRefs < 0 || childRefs >= REFCOUNT_DEFUNCT) {
930 // FIXME: add a global 'warn once' flag
931 LOG.warn("Negative child refcount {} cannot be stored, reference counting disabled for {}", childRefs, this,
933 refcount = REFCOUNT_DEFUNCT;
935 LOG.trace("Still {} outstanding children of {}", childRefs, this);
936 refcount = -childRefs;