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.Verify.verify;
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.VerifyException;
15 import java.util.Collection;
17 import java.util.Optional;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.common.QNameModule;
23 import org.opendaylight.yangtools.yang.common.YangVersion;
24 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
25 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
28 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
33 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
34 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
46 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
47 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Real "core" reactor statement implementation of {@link Mutable}, supporting basic reactor lifecycle.
54 * @param <A> Argument type
55 * @param <D> Declared Statement representation
56 * @param <E> Effective Statement representation
58 abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
59 extends NamespaceStorageSupport implements Mutable<A, D, E>, Current<A, D> {
60 private static final Logger LOG = LoggerFactory.getLogger(ReactorStmtCtx.class);
63 * Substatement refcount tracking. This mechanics deals with retaining substatements for the purposes of
64 * instantiating their lazy copies in InferredStatementContext. It works in concert with {@link #buildEffective()}
65 * and {@link #declared()}: declared/effective statement views hold an implicit reference and refcount-based
66 * sweep is not activated until they are done (or this statement is not {@link #isSupportedToBuildEffective}).
69 * Reference count is hierarchical in that parent references also pin down their child statements and do not allow
73 * The counter's positive values are tracking incoming references via {@link #incRef()}/{@link #decRef()} methods.
74 * Once we transition to sweeping, this value becomes negative counting upwards to {@link #REFCOUNT_NONE} based on
75 * {@link #sweepOnChildDone()}. Once we reach that, we transition to {@link #REFCOUNT_SWEPT}.
77 private int refcount = REFCOUNT_NONE;
79 * No outstanding references, this statement is a potential candidate for sweeping, provided it has populated its
80 * declared and effective views and {@link #parentRef} is known to be absent.
82 private static final int REFCOUNT_NONE = 0;
84 * Reference count overflow or some other recoverable logic error. Do not rely on refcounts and do not sweep
88 * Note on value assignment:
89 * This allow our incRef() to naturally progress to being saturated. Others jump there directly.
90 * It also makes it it impossible to observe {@code Interger.MAX_VALUE} children, which we take advantage of for
91 * {@link #REFCOUNT_SWEEPING}.
93 private static final int REFCOUNT_DEFUNCT = Integer.MAX_VALUE;
95 * This statement is being actively swept. This is a transient value set when we are sweeping our children, so that
96 * we prevent re-entering this statement.
99 * Note on value assignment:
100 * The value is lower than any legal child refcount due to {@link #REFCOUNT_DEFUNCT} while still being higher than
101 * {@link #REFCOUNT_SWEPT}.
103 private static final int REFCOUNT_SWEEPING = -Integer.MAX_VALUE;
105 * This statement, along with its entire subtree has been swept and we positively know all our children have reached
106 * this state. We {@link #sweepNamespaces()} upon reaching this state.
109 * Note on value assignment:
110 * This is the lowest value observable, making it easier on checking others on equality.
112 private static final int REFCOUNT_SWEPT = Integer.MIN_VALUE;
114 private @Nullable E effectiveInstance;
116 // Master flag controlling whether this context can yield an effective statement
117 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
118 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
119 private boolean isSupportedToBuildEffective = true;
121 // Flag bit assignments
122 private static final int IS_SUPPORTED_BY_FEATURES = 0x10;
123 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x20;
124 private static final int IS_IGNORE_IF_FEATURE = 0x40;
125 private static final int HAVE_IGNORE_IF_FEATURE = 0x80;
126 // Have-and-set flag constants, also used as masks
127 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
128 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
130 // EffectiveConfig mapping
131 private static final int MASK_CONFIG = 0x03;
132 private static final int HAVE_CONFIG = 0x04;
133 private static final EffectiveConfig[] EFFECTIVE_CONFIGS;
136 final EffectiveConfig[] values = EffectiveConfig.values();
137 final int length = values.length;
138 verify(length == 4, "Unexpected EffectiveConfig cardinality %s", length);
139 EFFECTIVE_CONFIGS = values;
142 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
143 // hence improve memory layout.
146 // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
147 // FIXME: move this out once we have JDK15+
148 private boolean fullyDefined;
150 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
151 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
153 private volatile SchemaPath schemaPath;
159 ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
160 isSupportedToBuildEffective = original.isSupportedToBuildEffective;
161 fullyDefined = original.fullyDefined;
162 flags = original.flags;
167 // Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
168 // up mixing concerns and simple details with more complex logic.
173 public abstract StatementContextBase<?, ?, ?> getParentContext();
176 public abstract RootStatementContext<?, ?, ?> getRoot();
179 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
182 public final @NonNull Registry getBehaviourRegistry() {
183 return getRoot().getBehaviourRegistryImpl();
187 public final YangVersion yangVersion() {
188 return getRoot().getRootVersionImpl();
192 public final void setRootVersion(final YangVersion version) {
193 getRoot().setRootVersionImpl(version);
197 public final void addRequiredSource(final SourceIdentifier dependency) {
198 getRoot().addRequiredSourceImpl(dependency);
202 public final void setRootIdentifier(final SourceIdentifier identifier) {
203 getRoot().setRootIdentifierImpl(identifier);
207 public final boolean isEnabledSemanticVersioning() {
208 return getRoot().isEnabledSemanticVersioningImpl();
212 public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
213 return getRoot().getSourceContext().newInferenceAction(phase);
217 public final StatementDefinition publicDefinition() {
218 return definition().getPublicView();
222 public final Parent effectiveParent() {
223 return getParentContext();
227 public final QName moduleName() {
228 final RootStatementContext<?, ?, ?> root = getRoot();
229 return QName.create(StmtContextUtils.getRootModuleQName(root), root.getRawArgument());
233 public final EffectiveStatement<?, ?> original() {
234 return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
238 // Non-final due to InferredStatementContext's override
239 public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
240 final @NonNull Class<Z> type) {
241 return allSubstatementsStream()
242 .filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
244 .map(ctx -> (X) ctx.getArgument());
248 // Non-final due to InferredStatementContext's override
249 public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
250 return allSubstatementsStream()
251 .anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
256 @SuppressWarnings("unchecked")
257 public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
258 return (StmtContext<A, D, Z>) this;
262 public final String toString() {
263 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
266 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
267 return toStringHelper.add("definition", definition()).add("rawArgument", rawArgument());
271 * Return the context in which this statement was defined.
273 * @return statement definition
275 abstract @NonNull StatementDefinitionContext<A, D, E> definition();
279 // NamespaceStorageSupport/Mutable integration methods. Keep these together.
284 public final <K, V, T extends K, N extends ParserNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
286 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
290 public final <K, V, N extends ParserNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
291 return getNamespace(type);
295 public final <K, V, N extends ParserNamespace<K, V>>
296 Map<K, V> localNamespacePortion(final Class<@NonNull N> type) {
297 return getLocalNamespace(type);
301 protected final void checkLocalNamespaceAllowed(final Class<? extends ParserNamespace<?, ?>> type) {
302 definition().checkNamespaceAllowed(type);
306 protected <K, V, N extends ParserNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
308 // definition().onNamespaceElementAdded(this, type, key, value);
311 abstract @Nullable ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(StatementContextBase<?, ?, ?> parent, CopyType type,
312 QNameModule targetModule);
316 // Statement build entry points -- both public and package-private.
321 public final E buildEffective() {
323 return (existing = effectiveInstance) != null ? existing : loadEffective();
326 private E loadEffective() {
327 // Creating an effective statement does not strictly require a declared instance -- there are statements like
328 // 'input', which are implicitly defined.
329 // Our implementation design makes an invariant assumption that buildDeclared() has been called by the time
330 // we attempt to create effective statement:
333 final E ret = effectiveInstance = createEffective();
334 // we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
336 if (refcount == REFCOUNT_NONE) {
342 abstract @NonNull E createEffective();
345 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
346 * this method does nothing.
348 * @param phase to be executed (completed)
349 * @return true if phase was successfully completed
350 * @throws SourceException when an error occurred in source parsing
352 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
353 return phase.isCompletedBy(getCompletedPhase()) || doTryToCompletePhase(phase);
356 abstract boolean doTryToCompletePhase(ModelProcessingPhase phase);
360 // Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
366 public final boolean isSupportedToBuildEffective() {
367 return isSupportedToBuildEffective;
371 public final void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
372 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
376 public final boolean isSupportedByFeatures() {
377 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
379 return fl == SET_SUPPORTED_BY_FEATURES;
381 if (isIgnoringIfFeatures()) {
382 flags |= SET_SUPPORTED_BY_FEATURES;
387 * If parent is supported, we need to check if-features statements of this context.
389 if (isParentSupportedByFeatures()) {
390 // If the set of supported features has not been provided, all features are supported by default.
391 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
392 SupportedFeatures.SUPPORTED_FEATURES);
393 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
394 flags |= SET_SUPPORTED_BY_FEATURES;
399 // Either parent is not supported or this statement is not supported
400 flags |= HAVE_SUPPORTED_BY_FEATURES;
404 protected abstract boolean isParentSupportedByFeatures();
407 * Config statements are not all that common which means we are performing a recursive search towards the root
408 * every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
409 * for the (usually non-existent) config statement.
412 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
413 * result without performing any lookups, solely to support {@link #effectiveConfig()}.
416 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
417 * {@link #isIgnoringConfig(StatementContextBase)}.
419 final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
420 return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
423 private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
424 final EffectiveConfig parentConfig = parent.effectiveConfig();
426 final EffectiveConfig myConfig;
427 if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
428 final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
429 if (optConfig.isPresent()) {
430 if (optConfig.orElseThrow()) {
431 // Validity check: if parent is config=false this cannot be a config=true
432 InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
433 "Parent node has config=false, this node must not be specifed as config=true");
434 myConfig = EffectiveConfig.TRUE;
436 myConfig = EffectiveConfig.FALSE;
439 // If "config" statement is not specified, the default is the same as the parent's "config" value.
440 myConfig = parentConfig;
443 myConfig = EffectiveConfig.IGNORED;
446 flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
450 protected abstract boolean isIgnoringConfig();
453 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
454 * keep on returning the same result without performing any lookups. Exists only to support
455 * {@link SubstatementContext#isIgnoringConfig()}.
458 * Note: use of this method implies that {@link #isConfiguration()} is realized with
459 * {@link #effectiveConfig(StatementContextBase)}.
461 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
462 return EffectiveConfig.IGNORED == effectiveConfig(parent);
465 protected abstract boolean isIgnoringIfFeatures();
468 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
469 * keep on returning the same result without performing any lookups. Exists only to support
470 * {@link SubstatementContext#isIgnoringIfFeatures()}.
472 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
473 final int fl = flags & SET_IGNORE_IF_FEATURE;
475 return fl == SET_IGNORE_IF_FEATURE;
477 if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
478 flags |= SET_IGNORE_IF_FEATURE;
482 flags |= HAVE_IGNORE_IF_FEATURE;
486 // These two exists only due to memory optimization, should live in AbstractResumedStatement. We are also reusing
487 // this for ReplicaStatementContext's refcount tracking.
488 final boolean fullyDefined() {
492 final void setFullyDefined() {
498 // Common SchemaPath cache. All of this is bound to be removed once YANGTOOLS-1066 is done.
502 // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
504 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
505 SchemaPath local = schemaPath;
507 synchronized (this) {
510 schemaPath = local = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
515 return Optional.ofNullable(local);
519 private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
520 final Optional<SchemaPath> maybeParentPath = parent.schemaPath();
521 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
522 final SchemaPath parentPath = maybeParentPath.get();
524 if (StmtContextUtils.isUnknownStatement(this)) {
525 return parentPath.createChild(publicDefinition().getStatementName());
527 final Object argument = argument();
528 if (argument instanceof QName) {
529 final QName qname = (QName) argument;
530 if (producesDeclared(UsesStatement.class)) {
531 return maybeParentPath.orElse(null);
534 return parentPath.createChild(qname);
536 if (argument instanceof String) {
537 // FIXME: This may yield illegal argument exceptions
538 final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
539 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
540 return parentPath.createChild(qname);
542 if (argument instanceof SchemaNodeIdentifier
543 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
544 || producesDeclared(DeviationStatement.class))) {
546 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
549 // FIXME: this does not look right
550 return maybeParentPath.orElse(null);
555 // Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
556 // contribute to state visible outside of this package.
561 * Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
562 * in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
563 * knowledge and update it when {@link #sweep()} is invoked.
565 private byte parentRef = PARENTREF_UNKNOWN;
566 private static final byte PARENTREF_UNKNOWN = -1;
567 private static final byte PARENTREF_ABSENT = 0;
568 private static final byte PARENTREF_PRESENT = 1;
571 * Acquire a reference on this context. As long as there is at least one reference outstanding,
572 * {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
574 * @throws VerifyException if {@link #effectiveSubstatements()} has already been discarded
576 final void incRef() {
577 final int current = refcount;
578 verify(current >= REFCOUNT_NONE, "Attempted to access reference count of %s", this);
579 if (current != REFCOUNT_DEFUNCT) {
580 // Note: can end up becoming REFCOUNT_DEFUNCT on overflow
581 refcount = current + 1;
583 LOG.debug("Disabled refcount increment of {}", this);
588 * Release a reference on this context. This call may result in {@link #effectiveSubstatements()} becoming
591 final void decRef() {
592 final int current = refcount;
593 if (current == REFCOUNT_DEFUNCT) {
595 LOG.debug("Disabled refcount decrement of {}", this);
598 if (current <= REFCOUNT_NONE) {
599 // Underflow, become defunct
600 LOG.warn("Statement refcount underflow, reference counting disabled for {}", this, new Throwable());
601 refcount = REFCOUNT_DEFUNCT;
605 refcount = current - 1;
606 LOG.trace("Refcount {} on {}", refcount, this);
608 if (refcount == REFCOUNT_NONE) {
614 * Return {@code true} if this context has an outstanding reference.
616 * @return True if this context has an outstanding reference.
618 final boolean haveRef() {
619 return refcount > REFCOUNT_NONE;
622 private void lastDecRef() {
623 if (noImplictRef()) {
624 // We are no longer guarded by effective instance
629 final byte prevRefs = parentRef;
630 if (prevRefs == PARENTREF_ABSENT) {
631 // We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
634 } else if (prevRefs == PARENTREF_UNKNOWN) {
635 // Noone observed our parentRef, just update it
636 loadParentRefcount();
640 static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
641 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
642 final byte prevRef = stmt.parentRef;
643 stmt.parentRef = PARENTREF_ABSENT;
644 if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
645 // Child thinks it is pinned down, update its perspective
646 stmt.markNoParentRef();
651 abstract void markNoParentRef();
653 static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
654 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
660 * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
662 private void sweep() {
663 parentRef = PARENTREF_ABSENT;
664 if (refcount == REFCOUNT_NONE && noImplictRef()) {
665 LOG.trace("Releasing {}", this);
670 static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
672 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
673 if (stmt.refcount > REFCOUNT_NONE || !stmt.noImplictRef()) {
681 * Implementation-specific sweep action. This is expected to perform a recursive {@link #sweep(Collection)} on all
682 * {@link #declaredSubstatements()} and {@link #effectiveSubstatements()} and report the result of the sweep
686 * {@link #effectiveSubstatements()} as well as namespaces may become inoperable as a result of this operation.
688 * @return True if the entire tree has been completely swept, false otherwise.
690 abstract int sweepSubstatements();
692 // Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
693 private void sweepOnDecrement() {
694 LOG.trace("Sweeping on decrement {}", this);
696 // No further parent references, sweep our state.
700 // Propagate towards parent if there is one
701 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
702 if (parent != null) {
703 parent.sweepOnChildDecrement();
707 // Called from child when it has lost its final reference
708 private void sweepOnChildDecrement() {
709 if (isAwaitingChildren()) {
710 // We are a child for which our parent is waiting. Notify it and we are done.
715 // Check parent reference count
716 final int refs = refcount;
717 if (refs > REFCOUNT_NONE || refs <= REFCOUNT_SWEEPING || !noImplictRef()) {
722 // parent is potentially reclaimable
724 LOG.trace("Cleanup {} of parent {}", refcount, this);
726 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
727 if (parent != null) {
728 parent.sweepOnChildDecrement();
734 private boolean noImplictRef() {
735 return effectiveInstance != null || !isSupportedToBuildEffective();
738 private boolean noParentRef() {
739 return parentRefcount() == PARENTREF_ABSENT;
742 private byte parentRefcount() {
744 return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
747 private byte loadParentRefcount() {
748 return parentRef = calculateParentRefcount();
751 private byte calculateParentRefcount() {
752 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
753 if (parent == null) {
754 return PARENTREF_ABSENT;
756 // There are three possibilities:
757 // - REFCOUNT_NONE, in which case we need to search next parent
758 // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
760 // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
761 final int refs = parent.refcount;
762 if (refs == REFCOUNT_NONE) {
763 return parent.parentRefcount();
765 return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
768 private boolean isAwaitingChildren() {
769 return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
772 private void sweepOnChildDone() {
773 LOG.trace("Sweeping on child done {}", this);
774 final int current = refcount;
775 if (current >= REFCOUNT_NONE) {
776 // no-op, perhaps we want to handle some cases differently?
777 LOG.trace("Ignoring child sweep of {} for {}", this, current);
780 verify(current != REFCOUNT_SWEPT, "Attempt to sweep a child of swept %s", this);
782 refcount = current + 1;
783 LOG.trace("Child refcount {}", refcount);
784 if (refcount == REFCOUNT_NONE) {
786 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
787 LOG.trace("Propagating to parent {}", parent);
788 if (parent != null && parent.isAwaitingChildren()) {
789 parent.sweepOnChildDone();
794 private void sweepDone() {
795 LOG.trace("Sweep done for {}", this);
796 refcount = REFCOUNT_SWEPT;
800 private boolean sweepState() {
801 refcount = REFCOUNT_SWEEPING;
802 final int childRefs = sweepSubstatements();
803 if (childRefs == 0) {
807 if (childRefs < 0 || childRefs >= REFCOUNT_DEFUNCT) {
808 LOG.warn("Negative child refcount {} cannot be stored, reference counting disabled for {}", childRefs, this,
810 refcount = REFCOUNT_DEFUNCT;
812 LOG.trace("Still {} outstanding children of {}", childRefs, this);
813 refcount = -childRefs;