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.QName;
23 import org.opendaylight.yangtools.yang.common.QNameModule;
24 import org.opendaylight.yangtools.yang.common.YangVersion;
25 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
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.EffectiveStmtCtx.Current;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
46 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
47 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
48 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * Real "core" reactor statement implementation of {@link Mutable}, supporting basic reactor lifecycle.
55 * @param <A> Argument type
56 * @param <D> Declared Statement representation
57 * @param <E> Effective Statement representation
59 abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
60 extends NamespaceStorageSupport implements Mutable<A, D, E>, Current<A, D> {
61 private static final Logger LOG = LoggerFactory.getLogger(ReactorStmtCtx.class);
64 * Substatement refcount tracking. This mechanics deals with retaining substatements for the purposes of
65 * instantiating their lazy copies in InferredStatementContext. It works in concert with {@link #buildEffective()}
66 * and {@link #declared()}: declared/effective statement views hold an implicit reference and refcount-based
67 * sweep is not activated until they are done (or this statement is not {@link #isSupportedToBuildEffective}).
70 * Reference count is hierarchical in that parent references also pin down their child statements and do not allow
74 * The counter's positive values are tracking incoming references via {@link #incRef()}/{@link #decRef()} methods.
75 * Once we transition to sweeping, this value becomes negative counting upwards to {@link #REFCOUNT_NONE} based on
76 * {@link #sweepOnChildDone()}. Once we reach that, we transition to {@link #REFCOUNT_SWEPT}.
78 private int refcount = REFCOUNT_NONE;
80 * No outstanding references, this statement is a potential candidate for sweeping, provided it has populated its
81 * declared and effective views and {@link #parentRef} is known to be absent.
83 private static final int REFCOUNT_NONE = 0;
85 * Reference count overflow or some other recoverable logic error. Do not rely on refcounts and do not sweep
89 * Note on value assignment:
90 * This allow our incRef() to naturally progress to being saturated. Others jump there directly.
91 * It also makes it it impossible to observe {@code Interger.MAX_VALUE} children, which we take advantage of for
92 * {@link #REFCOUNT_SWEEPING}.
94 private static final int REFCOUNT_DEFUNCT = Integer.MAX_VALUE;
96 * This statement is being actively swept. This is a transient value set when we are sweeping our children, so that
97 * we prevent re-entering this statement.
100 * Note on value assignment:
101 * The value is lower than any legal child refcount due to {@link #REFCOUNT_DEFUNCT} while still being higher than
102 * {@link #REFCOUNT_SWEPT}.
104 private static final int REFCOUNT_SWEEPING = -Integer.MAX_VALUE;
106 * This statement, along with its entire subtree has been swept and we positively know all our children have reached
107 * this state. We {@link #sweepNamespaces()} upon reaching this state.
110 * Note on value assignment:
111 * This is the lowest value observable, making it easier on checking others on equality.
113 private static final int REFCOUNT_SWEPT = Integer.MIN_VALUE;
115 private @Nullable E effectiveInstance;
117 // Master flag controlling whether this context can yield an effective statement
118 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
119 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
120 private boolean isSupportedToBuildEffective = true;
122 // EffectiveConfig mapping
123 private static final int MASK_CONFIG = 0x03;
124 private static final int HAVE_CONFIG = 0x04;
125 // Effective instantiation mechanics for StatementContextBase: if this flag is set all substatements are known not
126 // change when instantiated. This includes context-independent statements as well as any statements which are
127 // ignored during copy instantiation.
128 private static final int ALL_INDEPENDENT = 0x08;
129 // Flag bit assignments
130 private static final int IS_SUPPORTED_BY_FEATURES = 0x10;
131 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x20;
132 private static final int IS_IGNORE_IF_FEATURE = 0x40;
133 private static final int HAVE_IGNORE_IF_FEATURE = 0x80;
134 // Have-and-set flag constants, also used as masks
135 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
136 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
138 private static final EffectiveConfig[] EFFECTIVE_CONFIGS;
141 final EffectiveConfig[] values = EffectiveConfig.values();
142 final int length = values.length;
143 verify(length == 4, "Unexpected EffectiveConfig cardinality %s", length);
144 EFFECTIVE_CONFIGS = values;
147 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
148 // hence improve memory layout.
151 // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
152 // FIXME: move this out once we have JDK15+
153 private boolean fullyDefined;
155 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
156 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
158 private volatile SchemaPath schemaPath;
164 ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
165 isSupportedToBuildEffective = original.isSupportedToBuildEffective;
166 fullyDefined = original.fullyDefined;
167 flags = original.flags;
172 // Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
173 // up mixing concerns and simple details with more complex logic.
178 public abstract StatementContextBase<?, ?, ?> getParentContext();
181 public abstract RootStatementContext<?, ?, ?> getRoot();
184 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
187 public final @NonNull Registry getBehaviourRegistry() {
188 return getRoot().getBehaviourRegistryImpl();
192 public final YangVersion yangVersion() {
193 return getRoot().getRootVersionImpl();
197 public final void setRootVersion(final YangVersion version) {
198 getRoot().setRootVersionImpl(version);
202 public final void addRequiredSource(final SourceIdentifier dependency) {
203 getRoot().addRequiredSourceImpl(dependency);
207 public final void setRootIdentifier(final SourceIdentifier identifier) {
208 getRoot().setRootIdentifierImpl(identifier);
212 public final boolean isEnabledSemanticVersioning() {
213 return getRoot().isEnabledSemanticVersioningImpl();
217 public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
218 return getRoot().getSourceContext().newInferenceAction(phase);
222 public final StatementDefinition publicDefinition() {
223 return definition().getPublicView();
227 public final Parent effectiveParent() {
228 return getParentContext();
232 public final QName moduleName() {
233 final RootStatementContext<?, ?, ?> root = getRoot();
234 return QName.create(StmtContextUtils.getRootModuleQName(root), root.getRawArgument());
238 public final EffectiveStatement<?, ?> original() {
239 return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
243 // Non-final due to InferredStatementContext's override
244 public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
245 final @NonNull Class<Z> type) {
246 return allSubstatementsStream()
247 .filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
249 .map(ctx -> (X) ctx.getArgument());
253 // Non-final due to InferredStatementContext's override
254 public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
255 return allSubstatementsStream()
256 .anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
261 @SuppressWarnings("unchecked")
262 public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
263 return (StmtContext<A, D, Z>) this;
267 public final String toString() {
268 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
271 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
272 return toStringHelper.add("definition", definition()).add("rawArgument", rawArgument());
276 * Return the context in which this statement was defined.
278 * @return statement definition
280 abstract @NonNull StatementDefinitionContext<A, D, E> definition();
284 // NamespaceStorageSupport/Mutable integration methods. Keep these together.
289 public final <K, V, T extends K, N extends ParserNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
291 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
295 public final <K, V, N extends ParserNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
296 return getNamespace(type);
300 public final <K, V, N extends ParserNamespace<K, V>>
301 Map<K, V> localNamespacePortion(final Class<@NonNull N> type) {
302 return getLocalNamespace(type);
306 protected final void checkLocalNamespaceAllowed(final Class<? extends ParserNamespace<?, ?>> type) {
307 definition().checkNamespaceAllowed(type);
311 protected <K, V, N extends ParserNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
313 // definition().onNamespaceElementAdded(this, type, key, value);
316 abstract @Nullable ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(StatementContextBase<?, ?, ?> parent, CopyType type,
317 QNameModule targetModule);
320 public final ReactorStmtCtx<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
321 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
322 return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
325 abstract @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(@NonNull StatementContextBase<?, ?, ?> parent);
329 // Statement build entry points -- both public and package-private.
334 public final E buildEffective() {
336 return (existing = effectiveInstance) != null ? existing : loadEffective();
339 private E loadEffective() {
340 // Creating an effective statement does not strictly require a declared instance -- there are statements like
341 // 'input', which are implicitly defined.
342 // Our implementation design makes an invariant assumption that buildDeclared() has been called by the time
343 // we attempt to create effective statement:
346 final E ret = effectiveInstance = createEffective();
347 // we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
349 if (refcount == REFCOUNT_NONE) {
355 abstract @NonNull E createEffective();
358 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
359 * this method does nothing.
361 * @param phase to be executed (completed)
362 * @return true if phase was successfully completed
363 * @throws SourceException when an error occurred in source parsing
365 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
366 return phase.isCompletedBy(getCompletedPhase()) || doTryToCompletePhase(phase);
369 abstract boolean doTryToCompletePhase(ModelProcessingPhase phase);
373 // Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
379 public final boolean isSupportedToBuildEffective() {
380 return isSupportedToBuildEffective;
384 public final void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
385 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
389 public final boolean isSupportedByFeatures() {
390 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
392 return fl == SET_SUPPORTED_BY_FEATURES;
394 if (isIgnoringIfFeatures()) {
395 flags |= SET_SUPPORTED_BY_FEATURES;
400 * If parent is supported, we need to check if-features statements of this context.
402 if (isParentSupportedByFeatures()) {
403 // If the set of supported features has not been provided, all features are supported by default.
404 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
405 SupportedFeatures.SUPPORTED_FEATURES);
406 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
407 flags |= SET_SUPPORTED_BY_FEATURES;
412 // Either parent is not supported or this statement is not supported
413 flags |= HAVE_SUPPORTED_BY_FEATURES;
417 protected abstract boolean isParentSupportedByFeatures();
420 * Config statements are not all that common which means we are performing a recursive search towards the root
421 * every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
422 * for the (usually non-existent) config statement.
425 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
426 * result without performing any lookups, solely to support {@link #effectiveConfig()}.
429 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
430 * {@link #isIgnoringConfig(StatementContextBase)}.
432 final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
433 return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
436 private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
437 final EffectiveConfig parentConfig = parent.effectiveConfig();
439 final EffectiveConfig myConfig;
440 if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
441 final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
442 if (optConfig.isPresent()) {
443 if (optConfig.orElseThrow()) {
444 // Validity check: if parent is config=false this cannot be a config=true
445 InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
446 "Parent node has config=false, this node must not be specifed as config=true");
447 myConfig = EffectiveConfig.TRUE;
449 myConfig = EffectiveConfig.FALSE;
452 // If "config" statement is not specified, the default is the same as the parent's "config" value.
453 myConfig = parentConfig;
456 myConfig = EffectiveConfig.IGNORED;
459 flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
463 protected abstract boolean isIgnoringConfig();
466 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
467 * keep on returning the same result without performing any lookups. Exists only to support
468 * {@link SubstatementContext#isIgnoringConfig()}.
471 * Note: use of this method implies that {@link #isConfiguration()} is realized with
472 * {@link #effectiveConfig(StatementContextBase)}.
474 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
475 return EffectiveConfig.IGNORED == effectiveConfig(parent);
478 protected abstract boolean isIgnoringIfFeatures();
481 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
482 * keep on returning the same result without performing any lookups. Exists only to support
483 * {@link SubstatementContext#isIgnoringIfFeatures()}.
485 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
486 final int fl = flags & SET_IGNORE_IF_FEATURE;
488 return fl == SET_IGNORE_IF_FEATURE;
490 if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
491 flags |= SET_IGNORE_IF_FEATURE;
495 flags |= HAVE_IGNORE_IF_FEATURE;
499 // These two exist only due to memory optimization, should live in AbstractResumedStatement. We are also reusing
500 // this for ReplicaStatementContext's refcount tracking.
501 final boolean fullyDefined() {
505 final void setFullyDefined() {
509 // These two exist only for StatementContextBase. Since we are squeezed for size, with only a single bit available
510 // in flags, we default to 'false' and only set the flag to true when we are absolutely sure -- and all other cases
511 // err on the side of caution by taking the time to evaluate each substatement separately.
512 final boolean allSubstatementsContextIndependent() {
513 return (flags & ALL_INDEPENDENT) != 0;
516 final void setAllSubstatementsContextIndependent() {
517 flags |= ALL_INDEPENDENT;
522 // Common SchemaPath cache. All of this is bound to be removed once YANGTOOLS-1066 is done.
526 // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
528 final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
529 SchemaPath local = schemaPath;
531 synchronized (this) {
534 schemaPath = local = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
539 return Optional.ofNullable(local);
543 private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
544 final Optional<SchemaPath> maybeParentPath = parent.schemaPath();
545 verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
546 final SchemaPath parentPath = maybeParentPath.get();
548 if (StmtContextUtils.isUnknownStatement(this)) {
549 return parentPath.createChild(publicDefinition().getStatementName());
551 final Object argument = argument();
552 if (argument instanceof QName) {
553 final QName qname = (QName) argument;
554 if (producesDeclared(UsesStatement.class)) {
555 return maybeParentPath.orElse(null);
558 return parentPath.createChild(qname);
560 if (argument instanceof String) {
561 // FIXME: This may yield illegal argument exceptions
562 final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
563 final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
564 return parentPath.createChild(qname);
566 if (argument instanceof SchemaNodeIdentifier
567 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
568 || producesDeclared(DeviationStatement.class))) {
570 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
573 // FIXME: this does not look right
574 return maybeParentPath.orElse(null);
579 // Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
580 // contribute to state visible outside of this package.
585 * Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
586 * in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
587 * knowledge and update it when {@link #sweep()} is invoked.
589 private byte parentRef = PARENTREF_UNKNOWN;
590 private static final byte PARENTREF_UNKNOWN = -1;
591 private static final byte PARENTREF_ABSENT = 0;
592 private static final byte PARENTREF_PRESENT = 1;
595 * Acquire a reference on this context. As long as there is at least one reference outstanding,
596 * {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
598 * @throws VerifyException if {@link #effectiveSubstatements()} has already been discarded
600 final void incRef() {
601 final int current = refcount;
602 verify(current >= REFCOUNT_NONE, "Attempted to access reference count of %s", this);
603 if (current != REFCOUNT_DEFUNCT) {
604 // Note: can end up becoming REFCOUNT_DEFUNCT on overflow
605 refcount = current + 1;
607 LOG.debug("Disabled refcount increment of {}", this);
612 * Release a reference on this context. This call may result in {@link #effectiveSubstatements()} becoming
615 final void decRef() {
616 final int current = refcount;
617 if (current == REFCOUNT_DEFUNCT) {
619 LOG.debug("Disabled refcount decrement of {}", this);
622 if (current <= REFCOUNT_NONE) {
623 // Underflow, become defunct
624 LOG.warn("Statement refcount underflow, reference counting disabled for {}", this, new Throwable());
625 refcount = REFCOUNT_DEFUNCT;
629 refcount = current - 1;
630 LOG.trace("Refcount {} on {}", refcount, this);
632 if (refcount == REFCOUNT_NONE) {
638 * Return {@code true} if this context has an outstanding reference.
640 * @return True if this context has an outstanding reference.
642 final boolean haveRef() {
643 return refcount > REFCOUNT_NONE;
646 private void lastDecRef() {
647 if (noImplictRef()) {
648 // We are no longer guarded by effective instance
653 final byte prevRefs = parentRef;
654 if (prevRefs == PARENTREF_ABSENT) {
655 // We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
658 } else if (prevRefs == PARENTREF_UNKNOWN) {
659 // Noone observed our parentRef, just update it
660 loadParentRefcount();
664 static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
665 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
666 final byte prevRef = stmt.parentRef;
667 stmt.parentRef = PARENTREF_ABSENT;
668 if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
669 // Child thinks it is pinned down, update its perspective
670 stmt.markNoParentRef();
675 abstract void markNoParentRef();
677 static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
678 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
684 * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
686 private void sweep() {
687 parentRef = PARENTREF_ABSENT;
688 if (refcount == REFCOUNT_NONE && noImplictRef()) {
689 LOG.trace("Releasing {}", this);
694 static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
696 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
697 if (stmt.refcount > REFCOUNT_NONE || !stmt.noImplictRef()) {
705 * Implementation-specific sweep action. This is expected to perform a recursive {@link #sweep(Collection)} on all
706 * {@link #declaredSubstatements()} and {@link #effectiveSubstatements()} and report the result of the sweep
710 * {@link #effectiveSubstatements()} as well as namespaces may become inoperable as a result of this operation.
712 * @return True if the entire tree has been completely swept, false otherwise.
714 abstract int sweepSubstatements();
716 // Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
717 private void sweepOnDecrement() {
718 LOG.trace("Sweeping on decrement {}", this);
720 // No further parent references, sweep our state.
724 // Propagate towards parent if there is one
725 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
726 if (parent != null) {
727 parent.sweepOnChildDecrement();
731 // Called from child when it has lost its final reference
732 private void sweepOnChildDecrement() {
733 if (isAwaitingChildren()) {
734 // We are a child for which our parent is waiting. Notify it and we are done.
739 // Check parent reference count
740 final int refs = refcount;
741 if (refs > REFCOUNT_NONE || refs <= REFCOUNT_SWEEPING || !noImplictRef()) {
746 // parent is potentially reclaimable
748 LOG.trace("Cleanup {} of parent {}", refcount, this);
750 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
751 if (parent != null) {
752 parent.sweepOnChildDecrement();
758 private boolean noImplictRef() {
759 return effectiveInstance != null || !isSupportedToBuildEffective();
762 private boolean noParentRef() {
763 return parentRefcount() == PARENTREF_ABSENT;
766 private byte parentRefcount() {
768 return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
771 private byte loadParentRefcount() {
772 return parentRef = calculateParentRefcount();
775 private byte calculateParentRefcount() {
776 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
777 if (parent == null) {
778 return PARENTREF_ABSENT;
780 // There are three possibilities:
781 // - REFCOUNT_NONE, in which case we need to search next parent
782 // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
784 // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
785 final int refs = parent.refcount;
786 if (refs == REFCOUNT_NONE) {
787 return parent.parentRefcount();
789 return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
792 private boolean isAwaitingChildren() {
793 return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
796 private void sweepOnChildDone() {
797 LOG.trace("Sweeping on child done {}", this);
798 final int current = refcount;
799 if (current >= REFCOUNT_NONE) {
800 // no-op, perhaps we want to handle some cases differently?
801 LOG.trace("Ignoring child sweep of {} for {}", this, current);
804 verify(current != REFCOUNT_SWEPT, "Attempt to sweep a child of swept %s", this);
806 refcount = current + 1;
807 LOG.trace("Child refcount {}", refcount);
808 if (refcount == REFCOUNT_NONE) {
810 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
811 LOG.trace("Propagating to parent {}", parent);
812 if (parent != null && parent.isAwaitingChildren()) {
813 parent.sweepOnChildDone();
818 private void sweepDone() {
819 LOG.trace("Sweep done for {}", this);
820 refcount = REFCOUNT_SWEPT;
824 private boolean sweepState() {
825 refcount = REFCOUNT_SWEEPING;
826 final int childRefs = sweepSubstatements();
827 if (childRefs == 0) {
831 if (childRefs < 0 || childRefs >= REFCOUNT_DEFUNCT) {
832 LOG.warn("Negative child refcount {} cannot be stored, reference counting disabled for {}", childRefs, this,
834 refcount = REFCOUNT_DEFUNCT;
836 LOG.trace("Still {} outstanding children of {}", childRefs, this);
837 refcount = -childRefs;