Do not synchronize around ReactorStmtCtx.schemaPath
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / ReactorStmtCtx.java
index 0de3e281e3a9c7f459057c4e034a902fd0087fe5..5e9f5983e2f2e697cb465a7798414a659adc17f4 100644 (file)
@@ -7,14 +7,45 @@
  */
 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
 
+import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Verify.verify;
 
+import com.google.common.base.MoreObjects;
+import com.google.common.base.MoreObjects.ToStringHelper;
 import com.google.common.base.VerifyException;
 import java.util.Collection;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.common.YangVersion;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
+import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
+import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
+import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
+import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
+import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
+import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
+import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
+import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
+import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
+import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
+import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
+import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
+import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
+import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
+import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
+import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -26,13 +57,13 @@ import org.slf4j.LoggerFactory;
  * @param <E> Effective Statement representation
  */
 abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
-        extends NamespaceStorageSupport implements Mutable<A, D, E> {
+        extends NamespaceStorageSupport implements Mutable<A, D, E>, Current<A, D> {
     private static final Logger LOG = LoggerFactory.getLogger(ReactorStmtCtx.class);
 
     /**
      * Substatement refcount tracking. This mechanics deals with retaining substatements for the purposes of
      * instantiating their lazy copies in InferredStatementContext. It works in concert with {@link #buildEffective()}
-     * and {@link #buildDeclared()}: declared/effective statement views hold an implicit reference and refcount-based
+     * and {@link #declared()}: declared/effective statement views hold an implicit reference and refcount-based
      * sweep is not activated until they are done (or this statement is not {@link #isSupportedToBuildEffective}).
      *
      * <p>
@@ -81,6 +112,511 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
      */
     private static final int REFCOUNT_SWEPT = Integer.MIN_VALUE;
 
+    private @Nullable E effectiveInstance;
+
+    // Master flag controlling whether this context can yield an effective statement
+    // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
+    //        of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
+    private boolean isSupportedToBuildEffective = true;
+
+    // EffectiveConfig mapping
+    private static final int MASK_CONFIG                = 0x03;
+    private static final int HAVE_CONFIG                = 0x04;
+    // Effective instantiation mechanics for StatementContextBase: if this flag is set all substatements are known not
+    // change when instantiated. This includes context-independent statements as well as any statements which are
+    // ignored during copy instantiation.
+    private static final int ALL_INDEPENDENT            = 0x08;
+    // Flag bit assignments
+    private static final int IS_SUPPORTED_BY_FEATURES   = 0x10;
+    private static final int HAVE_SUPPORTED_BY_FEATURES = 0x20;
+    private static final int IS_IGNORE_IF_FEATURE       = 0x40;
+    private static final int HAVE_IGNORE_IF_FEATURE     = 0x80;
+    // Have-and-set flag constants, also used as masks
+    private static final int SET_SUPPORTED_BY_FEATURES  = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
+    private static final int SET_IGNORE_IF_FEATURE      = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
+
+    private static final EffectiveConfig[] EFFECTIVE_CONFIGS;
+
+    static {
+        final EffectiveConfig[] values = EffectiveConfig.values();
+        final int length = values.length;
+        verify(length == 4, "Unexpected EffectiveConfig cardinality %s", length);
+        EFFECTIVE_CONFIGS = values;
+    }
+
+    // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
+    // hence improve memory layout.
+    private byte flags;
+
+    // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
+    // FIXME: move this out once we have JDK15+
+    private boolean fullyDefined;
+
+    // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
+    // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
+    // FIXME: this should become 'QName'
+    private SchemaPath schemaPath;
+
+    ReactorStmtCtx() {
+        // Empty on purpose
+    }
+
+    ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
+        isSupportedToBuildEffective = original.isSupportedToBuildEffective;
+        fullyDefined = original.fullyDefined;
+        flags = original.flags;
+    }
+
+    //
+    //
+    // Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
+    // up mixing concerns and simple details with more complex logic.
+    //
+    //
+
+    @Override
+    public abstract StatementContextBase<?, ?, ?> getParentContext();
+
+    @Override
+    public abstract RootStatementContext<?, ?, ?> getRoot();
+
+    @Override
+    public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
+
+    @Override
+    public final @NonNull Registry getBehaviourRegistry() {
+        return getRoot().getBehaviourRegistryImpl();
+    }
+
+    @Override
+    public final YangVersion yangVersion() {
+        return getRoot().getRootVersionImpl();
+    }
+
+    @Override
+    public final void setRootVersion(final YangVersion version) {
+        getRoot().setRootVersionImpl(version);
+    }
+
+    @Override
+    public final void addRequiredSource(final SourceIdentifier dependency) {
+        getRoot().addRequiredSourceImpl(dependency);
+    }
+
+    @Override
+    public final void setRootIdentifier(final SourceIdentifier identifier) {
+        getRoot().setRootIdentifierImpl(identifier);
+    }
+
+    @Override
+    public final boolean isEnabledSemanticVersioning() {
+        return getRoot().isEnabledSemanticVersioningImpl();
+    }
+
+    @Override
+    public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
+        return getRoot().getSourceContext().newInferenceAction(phase);
+    }
+
+    @Override
+    public final StatementDefinition publicDefinition() {
+        return definition().getPublicView();
+    }
+
+    @Override
+    public final Parent effectiveParent() {
+        return getParentContext();
+    }
+
+    @Override
+    public final QName moduleName() {
+        final RootStatementContext<?, ?, ?> root = getRoot();
+        return QName.create(StmtContextUtils.getRootModuleQName(root), root.getRawArgument());
+    }
+
+    @Override
+    public final EffectiveStatement<?, ?> original() {
+        return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
+    }
+
+    @Override
+    // Non-final due to InferredStatementContext's override
+    public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
+            final @NonNull Class<Z> type) {
+        return allSubstatementsStream()
+            .filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
+            .findAny()
+            .map(ctx -> (X) ctx.getArgument());
+    }
+
+    @Override
+    // Non-final due to InferredStatementContext's override
+    public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
+        return allSubstatementsStream()
+            .anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
+    }
+
+    @Override
+    @Deprecated
+    @SuppressWarnings("unchecked")
+    public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
+        return (StmtContext<A, D, Z>) this;
+    }
+
+    @Override
+    public final String toString() {
+        return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
+    }
+
+    protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
+        return toStringHelper.add("definition", definition()).add("rawArgument", rawArgument());
+    }
+
+    /**
+     * Return the context in which this statement was defined.
+     *
+     * @return statement definition
+     */
+    abstract @NonNull StatementDefinitionContext<A, D, E> definition();
+
+    //
+    //
+    // NamespaceStorageSupport/Mutable integration methods. Keep these together.
+    //
+    //
+
+    @Override
+    public final <K, V, T extends K, N extends ParserNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
+            final T key) {
+        return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
+    }
+
+    @Override
+    public final <K, V, N extends ParserNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
+        return getNamespace(type);
+    }
+
+    @Override
+    public final <K, V, N extends ParserNamespace<K, V>>
+            Map<K, V> localNamespacePortion(final Class<@NonNull N> type) {
+        return getLocalNamespace(type);
+    }
+
+    @Override
+    protected final void checkLocalNamespaceAllowed(final Class<? extends ParserNamespace<?, ?>> type) {
+        definition().checkNamespaceAllowed(type);
+    }
+
+    @Override
+    protected <K, V, N extends ParserNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
+            final V value) {
+        // definition().onNamespaceElementAdded(this, type, key, value);
+    }
+
+    /**
+     * Return the effective statement view of a copy operation. This method may return one of:
+     * <ul>
+     *   <li>{@code this}, when the effective view did not change</li>
+     *   <li>an InferredStatementContext, when there is a need for inference-equivalent copy</li>
+     *   <li>{@code null}, when the statement failed to materialize</li>
+     * </ul>
+     *
+     * @param parent Proposed new parent
+     * @param type Copy operation type
+     * @param targetModule New target module
+     * @return {@link ReactorStmtCtx} holding effective view
+     */
+    abstract @Nullable ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(StatementContextBase<?, ?, ?> parent, CopyType type,
+        QNameModule targetModule);
+
+    @Override
+    public final ReactorStmtCtx<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
+        checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
+        return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
+    }
+
+    abstract @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(@NonNull StatementContextBase<?, ?, ?> parent);
+
+    //
+    //
+    // Statement build entry points -- both public and package-private.
+    //
+    //
+
+    @Override
+    public final E buildEffective() {
+        final E existing;
+        return (existing = effectiveInstance) != null ? existing : loadEffective();
+    }
+
+    private E loadEffective() {
+        // Creating an effective statement does not strictly require a declared instance -- there are statements like
+        // 'input', which are implicitly defined.
+        // Our implementation design makes an invariant assumption that buildDeclared() has been called by the time
+        // we attempt to create effective statement:
+        declared();
+
+        final E ret = effectiveInstance = createEffective();
+        // we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
+        // some residue.
+        if (refcount == REFCOUNT_NONE) {
+            sweepOnDecrement();
+        }
+        return ret;
+    }
+
+    abstract @NonNull E createEffective();
+
+    /**
+     * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
+     * this method does nothing.
+     *
+     * @param phase to be executed (completed)
+     * @return true if phase was successfully completed
+     * @throws SourceException when an error occurred in source parsing
+     */
+    final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
+        return phase.isCompletedBy(getCompletedPhase()) || doTryToCompletePhase(phase);
+    }
+
+    abstract boolean doTryToCompletePhase(ModelProcessingPhase phase);
+
+    //
+    //
+    // Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
+    // shadow.
+    //
+    //
+
+    @Override
+    public final boolean isSupportedToBuildEffective() {
+        return isSupportedToBuildEffective;
+    }
+
+    @Override
+    public final void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
+        this.isSupportedToBuildEffective = isSupportedToBuildEffective;
+    }
+
+    @Override
+    public final boolean isSupportedByFeatures() {
+        final int fl = flags & SET_SUPPORTED_BY_FEATURES;
+        if (fl != 0) {
+            return fl == SET_SUPPORTED_BY_FEATURES;
+        }
+        if (isIgnoringIfFeatures()) {
+            flags |= SET_SUPPORTED_BY_FEATURES;
+            return true;
+        }
+
+        /*
+         * If parent is supported, we need to check if-features statements of this context.
+         */
+        if (isParentSupportedByFeatures()) {
+            // If the set of supported features has not been provided, all features are supported by default.
+            final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
+                    SupportedFeatures.SUPPORTED_FEATURES);
+            if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
+                flags |= SET_SUPPORTED_BY_FEATURES;
+                return true;
+            }
+        }
+
+        // Either parent is not supported or this statement is not supported
+        flags |= HAVE_SUPPORTED_BY_FEATURES;
+        return false;
+    }
+
+    protected abstract boolean isParentSupportedByFeatures();
+
+    /**
+     * Config statements are not all that common which means we are performing a recursive search towards the root
+     * every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
+     * for the (usually non-existent) config statement.
+     *
+     * <p>
+     * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
+     * result without performing any lookups, solely to support {@link #effectiveConfig()}.
+     *
+     * <p>
+     * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
+     *       {@link #isIgnoringConfig(StatementContextBase)}.
+     */
+    final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
+        return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
+    }
+
+    private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
+        final EffectiveConfig parentConfig = parent.effectiveConfig();
+
+        final EffectiveConfig myConfig;
+        if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
+            final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
+            if (optConfig.isPresent()) {
+                if (optConfig.orElseThrow()) {
+                    // Validity check: if parent is config=false this cannot be a config=true
+                    InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
+                        "Parent node has config=false, this node must not be specifed as config=true");
+                    myConfig = EffectiveConfig.TRUE;
+                } else {
+                    myConfig = EffectiveConfig.FALSE;
+                }
+            } else {
+                // If "config" statement is not specified, the default is the same as the parent's "config" value.
+                myConfig = parentConfig;
+            }
+        } else {
+            myConfig = EffectiveConfig.IGNORED;
+        }
+
+        flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
+        return myConfig;
+    }
+
+    protected abstract boolean isIgnoringConfig();
+
+    /**
+     * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
+     * keep on returning the same result without performing any lookups. Exists only to support
+     * {@link SubstatementContext#isIgnoringConfig()}.
+     *
+     * <p>
+     * Note: use of this method implies that {@link #isConfiguration()} is realized with
+     *       {@link #effectiveConfig(StatementContextBase)}.
+     */
+    final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
+        return EffectiveConfig.IGNORED == effectiveConfig(parent);
+    }
+
+    protected abstract boolean isIgnoringIfFeatures();
+
+    /**
+     * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
+     * keep on returning the same result without performing any lookups. Exists only to support
+     * {@link SubstatementContext#isIgnoringIfFeatures()}.
+     */
+    final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
+        final int fl = flags & SET_IGNORE_IF_FEATURE;
+        if (fl != 0) {
+            return fl == SET_IGNORE_IF_FEATURE;
+        }
+        if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
+            flags |= SET_IGNORE_IF_FEATURE;
+            return true;
+        }
+
+        flags |= HAVE_IGNORE_IF_FEATURE;
+        return false;
+    }
+
+    // These two exist only due to memory optimization, should live in AbstractResumedStatement. We are also reusing
+    // this for ReplicaStatementContext's refcount tracking.
+    final boolean fullyDefined() {
+        return fullyDefined;
+    }
+
+    final void setFullyDefined() {
+        fullyDefined = true;
+    }
+
+    // These two exist only for StatementContextBase. Since we are squeezed for size, with only a single bit available
+    // in flags, we default to 'false' and only set the flag to true when we are absolutely sure -- and all other cases
+    // err on the side of caution by taking the time to evaluate each substatement separately.
+    final boolean allSubstatementsContextIndependent() {
+        return (flags & ALL_INDEPENDENT) != 0;
+    }
+
+    final void setAllSubstatementsContextIndependent() {
+        flags |= ALL_INDEPENDENT;
+    }
+
+    //
+    //
+    // Various functionality from AbstractTypeStatementSupport. This used to work on top of SchemaPath, now it still
+    // lives here. Ultimate future is either proper graduation or (more likely) move to AbstractTypeStatementSupport.
+    //
+    //
+
+    @Override
+    public final QName argumentAsTypeQName() {
+        final Object argument = argument();
+        verify(argument instanceof String, "Unexpected argument %s", argument);
+        return interpretAsQName((String) argument);
+    }
+
+    @Override
+    public final QNameModule effectiveNamespace() {
+        // FIXME: there has to be a better way to do this
+        return getSchemaPath().getLastComponent().getModule();
+    }
+
+    //
+    //
+    // Common SchemaPath cache. All of this is bound to be removed once YANGTOOLS-1066 is done.
+    //
+    //
+
+    // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
+    @Deprecated
+    final @Nullable SchemaPath substatementGetSchemaPath() {
+        if (schemaPath == null) {
+            schemaPath = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
+        }
+        return schemaPath;
+    }
+
+    // FIXME: 7.0.0: this method's logic needs to be moved to the respective StatementSupport classes
+    @Deprecated
+    private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
+        final SchemaPath parentPath = parent.getSchemaPath();
+        if (StmtContextUtils.isUnknownStatement(this)) {
+            return parentPath.createChild(publicDefinition().getStatementName());
+        }
+        final Object argument = argument();
+        if (argument instanceof QName) {
+            final QName qname = (QName) argument;
+            if (producesDeclared(UsesStatement.class)) {
+                return parentPath;
+            }
+
+            return parentPath.createChild(qname);
+        }
+        if (argument instanceof String) {
+            return parentPath.createChild(interpretAsQName((String) argument));
+        }
+        if (argument instanceof SchemaNodeIdentifier
+                && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
+                        || producesDeclared(DeviationStatement.class))) {
+
+            return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
+        }
+
+        // FIXME: this does not look right, investigate more?
+        return parentPath;
+    }
+
+    private @NonNull QName interpretAsQName(final String argument) {
+        // FIXME: This may yield illegal argument exceptions
+        return StmtContextUtils.qnameFromArgument(getOriginalCtx().orElse(this), argument);
+    }
+
+    //
+    //
+    // Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
+    // contribute to state visible outside of this package.
+    //
+    //
+
+    /**
+     * Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
+     * in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
+     * knowledge and update it when {@link #sweep()} is invoked.
+     */
+    private byte parentRef = PARENTREF_UNKNOWN;
+    private static final byte PARENTREF_UNKNOWN = -1;
+    private static final byte PARENTREF_ABSENT  = 0;
+    private static final byte PARENTREF_PRESENT = 1;
+
     /**
      * Acquire a reference on this context. As long as there is at least one reference outstanding,
      * {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
@@ -118,15 +654,55 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
 
         refcount = current - 1;
         LOG.trace("Refcount {} on {}", refcount, this);
-        if (isSweepable()) {
+
+        if (refcount == REFCOUNT_NONE) {
+            lastDecRef();
+        }
+    }
+
+    /**
+     * Return {@code true} if this context has an outstanding reference.
+     *
+     * @return True if this context has an outstanding reference.
+     */
+    final boolean haveRef() {
+        return refcount > REFCOUNT_NONE;
+    }
+
+    private void lastDecRef() {
+        if (noImplictRef()) {
             // We are no longer guarded by effective instance
             sweepOnDecrement();
+            return;
+        }
+
+        final byte prevRefs = parentRef;
+        if (prevRefs == PARENTREF_ABSENT) {
+            // We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
+            // updated
+            markNoParentRef();
+        } else if (prevRefs == PARENTREF_UNKNOWN) {
+            // Noone observed our parentRef, just update it
+            loadParentRefcount();
         }
     }
 
-    final void releaseImplicitRef() {
-        if (refcount == REFCOUNT_NONE) {
-            sweepOnDecrement();
+    static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
+        for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
+            final byte prevRef = stmt.parentRef;
+            stmt.parentRef = PARENTREF_ABSENT;
+            if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
+                // Child thinks it is pinned down, update its perspective
+                stmt.markNoParentRef();
+            }
+        }
+    }
+
+    abstract void markNoParentRef();
+
+    static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
+        for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
+            stmt.sweep();
         }
     }
 
@@ -134,18 +710,13 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
      * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
      */
     private void sweep() {
-        if (isSweepable()) {
+        parentRef = PARENTREF_ABSENT;
+        if (refcount == REFCOUNT_NONE && noImplictRef()) {
             LOG.trace("Releasing {}", this);
             sweepState();
         }
     }
 
-    static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
-        for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
-            stmt.sweep();
-        }
-    }
-
     static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
         int result = 0;
         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
@@ -168,18 +739,17 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
      */
     abstract int sweepSubstatements();
 
-    abstract boolean noImplictRef();
-
-    abstract @Nullable ReactorStmtCtx<?, ?, ?> parentStmtCtx();
-
     // Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
     private void sweepOnDecrement() {
         LOG.trace("Sweeping on decrement {}", this);
-        final ReactorStmtCtx<?, ?, ?> parent = parentStmtCtx();
-        if (parent == null) {
-            // We are the top-level object and have lost a reference. Trigger sweep if possible and we are done.
+        if (noParentRef()) {
+            // No further parent references, sweep our state.
             sweepState();
-        } else {
+        }
+
+        // Propagate towards parent if there is one
+        final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
+        if (parent != null) {
             parent.sweepOnChildDecrement();
         }
     }
@@ -200,10 +770,10 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
         }
 
         // parent is potentially reclaimable
-        if (noParentRefcount()) {
+        if (noParentRef()) {
             LOG.trace("Cleanup {} of parent {}", refcount, this);
             if (sweepState()) {
-                final ReactorStmtCtx<?, ?, ?> parent = parentStmtCtx();
+                final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
                 if (parent != null) {
                     parent.sweepOnChildDecrement();
                 }
@@ -211,29 +781,44 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
         }
     }
 
-    // FIXME: cache the resolution of this
-    private boolean noParentRefcount() {
-        final ReactorStmtCtx<?, ?, ?> parent = parentStmtCtx();
-        if (parent != null) {
-            // There are three possibilities:
-            // - REFCOUNT_NONE, in which case we need to search next parent
-            // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
-            //   a reference to us
-            // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
-            final int refs = parent.refcount;
-            return refs == REFCOUNT_NONE ? parent.noParentRefcount() : refs < REFCOUNT_NONE;
+    private boolean noImplictRef() {
+        return effectiveInstance != null || !isSupportedToBuildEffective();
+    }
+
+    private boolean noParentRef() {
+        return parentRefcount() == PARENTREF_ABSENT;
+    }
+
+    private byte parentRefcount() {
+        final byte refs;
+        return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
+    }
+
+    private byte loadParentRefcount() {
+        return parentRef = calculateParentRefcount();
+    }
+
+    private byte calculateParentRefcount() {
+        final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
+        if (parent == null) {
+            return PARENTREF_ABSENT;
         }
-        return true;
+        // There are three possibilities:
+        // - REFCOUNT_NONE, in which case we need to search next parent
+        // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
+        //   a reference to us
+        // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
+        final int refs = parent.refcount;
+        if (refs == REFCOUNT_NONE) {
+            return parent.parentRefcount();
+        }
+        return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
     }
 
     private boolean isAwaitingChildren() {
         return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
     }
 
-    private boolean isSweepable() {
-        return refcount == REFCOUNT_NONE && noImplictRef();
-    }
-
     private void sweepOnChildDone() {
         LOG.trace("Sweeping on child done {}", this);
         final int current = refcount;
@@ -248,7 +833,7 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
         LOG.trace("Child refcount {}", refcount);
         if (refcount == REFCOUNT_NONE) {
             sweepDone();
-            final ReactorStmtCtx<?, ?, ?> parent = parentStmtCtx();
+            final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
             LOG.trace("Propagating to parent {}", parent);
             if (parent != null && parent.isAwaitingChildren()) {
                 parent.sweepOnChildDone();