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 and ReplicateStatementContext. This is hiding in the alignment shadow
152 // created by above boolean
153 // FIXME: move this out once we have JDK15+
154 private boolean fullyDefined;
156 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
157 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
158 // FIXME: this should become 'QName'
159 private SchemaPath schemaPath;
165 ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
166 isSupportedToBuildEffective = original.isSupportedToBuildEffective;
167 fullyDefined = original.fullyDefined;
168 flags = original.flags;
171 // Used by ReplicaStatementContext only
172 ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original, final Void dummy) {
173 fullyDefined = isSupportedToBuildEffective = original.isSupportedToBuildEffective;
174 flags = original.flags;
179 // Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
180 // up mixing concerns and simple details with more complex logic.
185 public abstract StatementContextBase<?, ?, ?> getParentContext();
188 public abstract RootStatementContext<?, ?, ?> getRoot();
191 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
194 public final @NonNull Registry getBehaviourRegistry() {
195 return getRoot().getBehaviourRegistryImpl();
199 public final YangVersion yangVersion() {
200 return getRoot().getRootVersionImpl();
204 public final void setRootVersion(final YangVersion version) {
205 getRoot().setRootVersionImpl(version);
209 public final void addRequiredSource(final SourceIdentifier dependency) {
210 getRoot().addRequiredSourceImpl(dependency);
214 public final void setRootIdentifier(final SourceIdentifier identifier) {
215 getRoot().setRootIdentifierImpl(identifier);
219 public final boolean isEnabledSemanticVersioning() {
220 return getRoot().isEnabledSemanticVersioningImpl();
224 public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
225 return getRoot().getSourceContext().newInferenceAction(phase);
229 public final StatementDefinition publicDefinition() {
230 return definition().getPublicView();
234 public final Parent effectiveParent() {
235 return getParentContext();
239 public final QName moduleName() {
240 final RootStatementContext<?, ?, ?> root = getRoot();
241 return QName.create(StmtContextUtils.getRootModuleQName(root), root.getRawArgument());
245 public final EffectiveStatement<?, ?> original() {
246 return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
250 // In the next two methods we are looking for an effective statement. If we already have an effective instance,
251 // defer to it's implementation of the equivalent search. Otherwise we search our substatement contexts.
253 // Note that the search function is split, so as to allow InferredStatementContext to do its own thing first.
257 public final <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
258 final @NonNull Class<Z> type) {
259 final E local = effectiveInstance;
260 return local != null ? local.findFirstEffectiveSubstatementArgument(type)
261 : findSubstatementArgumentImpl(type);
265 public final boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
266 final E local = effectiveInstance;
267 return local != null ? local.findFirstEffectiveSubstatement(type).isPresent()
268 : hasSubstatementImpl(type);
271 // Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
272 <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
273 final @NonNull Class<Z> type) {
274 return allSubstatementsStream()
275 .filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
277 .map(ctx -> (X) ctx.getArgument());
280 // Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
281 boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
282 return allSubstatementsStream()
283 .anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
288 @SuppressWarnings("unchecked")
289 public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
290 return (StmtContext<A, D, Z>) this;
294 public final String toString() {
295 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
298 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
299 return toStringHelper.add("definition", definition()).add("rawArgument", rawArgument());
303 * Return the context in which this statement was defined.
305 * @return statement definition
307 abstract @NonNull StatementDefinitionContext<A, D, E> definition();
311 // NamespaceStorageSupport/Mutable integration methods. Keep these together.
316 public final <K, V, T extends K, N extends ParserNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
318 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
322 public final <K, V, N extends ParserNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
323 return getNamespace(type);
327 public final <K, V, N extends ParserNamespace<K, V>>
328 Map<K, V> localNamespacePortion(final Class<@NonNull N> type) {
329 return getLocalNamespace(type);
333 protected final void checkLocalNamespaceAllowed(final Class<? extends ParserNamespace<?, ?>> type) {
334 definition().checkNamespaceAllowed(type);
338 protected <K, V, N extends ParserNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
340 // definition().onNamespaceElementAdded(this, type, key, value);
344 * Return the effective statement view of a copy operation. This method may return one of:
346 * <li>{@code this}, when the effective view did not change</li>
347 * <li>an InferredStatementContext, when there is a need for inference-equivalent copy</li>
348 * <li>{@code null}, when the statement failed to materialize</li>
351 * @param parent Proposed new parent
352 * @param type Copy operation type
353 * @param targetModule New target module
354 * @return {@link ReactorStmtCtx} holding effective view
356 abstract @Nullable ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(StatementContextBase<?, ?, ?> parent, CopyType type,
357 QNameModule targetModule);
360 public final ReactorStmtCtx<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
361 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
362 return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
365 abstract @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(@NonNull StatementContextBase<?, ?, ?> parent);
369 // Statement build entry points -- both public and package-private.
374 public final E buildEffective() {
376 return (existing = effectiveInstance) != null ? existing : loadEffective();
379 private @NonNull E loadEffective() {
380 // Creating an effective statement does not strictly require a declared instance -- there are statements like
381 // 'input', which are implicitly defined.
382 // Our implementation design makes an invariant assumption that buildDeclared() has been called by the time
383 // we attempt to create effective statement:
386 final E ret = effectiveInstance = createEffective();
387 // we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
389 if (refcount == REFCOUNT_NONE) {
395 abstract @NonNull E createEffective();
398 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
399 * this method does nothing.
401 * @param phase to be executed (completed)
402 * @return true if phase was successfully completed
403 * @throws SourceException when an error occurred in source parsing
405 final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
406 return phase.isCompletedBy(getCompletedPhase()) || doTryToCompletePhase(phase);
409 abstract boolean doTryToCompletePhase(ModelProcessingPhase phase);
413 // Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
419 public final boolean isSupportedToBuildEffective() {
420 return isSupportedToBuildEffective;
424 public final void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
425 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
429 public final boolean isSupportedByFeatures() {
430 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
432 return fl == SET_SUPPORTED_BY_FEATURES;
434 if (isIgnoringIfFeatures()) {
435 flags |= SET_SUPPORTED_BY_FEATURES;
440 * If parent is supported, we need to check if-features statements of this context.
442 if (isParentSupportedByFeatures()) {
443 // If the set of supported features has not been provided, all features are supported by default.
444 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
445 SupportedFeatures.SUPPORTED_FEATURES);
446 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
447 flags |= SET_SUPPORTED_BY_FEATURES;
452 // Either parent is not supported or this statement is not supported
453 flags |= HAVE_SUPPORTED_BY_FEATURES;
457 protected abstract boolean isParentSupportedByFeatures();
460 * Config statements are not all that common which means we are performing a recursive search towards the root
461 * every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
462 * for the (usually non-existent) config statement.
465 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
466 * result without performing any lookups, solely to support {@link #effectiveConfig()}.
469 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
470 * {@link #isIgnoringConfig(StatementContextBase)}.
472 final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
473 return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
476 private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
477 final EffectiveConfig parentConfig = parent.effectiveConfig();
479 final EffectiveConfig myConfig;
480 if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
481 final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
482 if (optConfig.isPresent()) {
483 if (optConfig.orElseThrow()) {
484 // Validity check: if parent is config=false this cannot be a config=true
485 InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
486 "Parent node has config=false, this node must not be specifed as config=true");
487 myConfig = EffectiveConfig.TRUE;
489 myConfig = EffectiveConfig.FALSE;
492 // If "config" statement is not specified, the default is the same as the parent's "config" value.
493 myConfig = parentConfig;
496 myConfig = EffectiveConfig.IGNORED;
499 flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
503 protected abstract boolean isIgnoringConfig();
506 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
507 * keep on returning the same result without performing any lookups. Exists only to support
508 * {@link SubstatementContext#isIgnoringConfig()}.
511 * Note: use of this method implies that {@link #isConfiguration()} is realized with
512 * {@link #effectiveConfig(StatementContextBase)}.
514 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
515 return EffectiveConfig.IGNORED == effectiveConfig(parent);
518 protected abstract boolean isIgnoringIfFeatures();
521 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
522 * keep on returning the same result without performing any lookups. Exists only to support
523 * {@link SubstatementContext#isIgnoringIfFeatures()}.
525 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
526 final int fl = flags & SET_IGNORE_IF_FEATURE;
528 return fl == SET_IGNORE_IF_FEATURE;
530 if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
531 flags |= SET_IGNORE_IF_FEATURE;
535 flags |= HAVE_IGNORE_IF_FEATURE;
539 // These two exist only due to memory optimization, should live in AbstractResumedStatement.
540 final boolean fullyDefined() {
544 final void setFullyDefined() {
548 // This exists only due to memory optimization, should live in ReplicaStatementContext.
549 final boolean haveSourceReference() {
553 // These two exist only for StatementContextBase. Since we are squeezed for size, with only a single bit available
554 // in flags, we default to 'false' and only set the flag to true when we are absolutely sure -- and all other cases
555 // err on the side of caution by taking the time to evaluate each substatement separately.
556 final boolean allSubstatementsContextIndependent() {
557 return (flags & ALL_INDEPENDENT) != 0;
560 final void setAllSubstatementsContextIndependent() {
561 flags |= ALL_INDEPENDENT;
566 // Various functionality from AbstractTypeStatementSupport. This used to work on top of SchemaPath, now it still
567 // lives here. Ultimate future is either proper graduation or (more likely) move to AbstractTypeStatementSupport.
572 public final QName argumentAsTypeQName() {
573 final Object argument = argument();
574 verify(argument instanceof String, "Unexpected argument %s", argument);
575 return interpretAsQName((String) argument);
579 public final QNameModule effectiveNamespace() {
580 // FIXME: there has to be a better way to do this
581 return getSchemaPath().getLastComponent().getModule();
586 // Common SchemaPath cache. All of this is bound to be removed once YANGTOOLS-1066 is done.
590 // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
592 final @Nullable SchemaPath substatementGetSchemaPath() {
593 if (schemaPath == null) {
594 schemaPath = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
599 // FIXME: 7.0.0: this method's logic needs to be moved to the respective StatementSupport classes
601 private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
602 final SchemaPath parentPath = parent.getSchemaPath();
603 if (StmtContextUtils.isUnknownStatement(this)) {
604 return parentPath.createChild(publicDefinition().getStatementName());
606 final Object argument = argument();
607 if (argument instanceof QName) {
608 final QName qname = (QName) argument;
609 if (producesDeclared(UsesStatement.class)) {
613 return parentPath.createChild(qname);
615 if (argument instanceof String) {
616 return parentPath.createChild(interpretAsQName((String) argument));
618 if (argument instanceof SchemaNodeIdentifier
619 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
620 || producesDeclared(DeviationStatement.class))) {
622 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
625 // FIXME: this does not look right, investigate more?
629 private @NonNull QName interpretAsQName(final String argument) {
630 // FIXME: This may yield illegal argument exceptions
631 return StmtContextUtils.qnameFromArgument(getOriginalCtx().orElse(this), argument);
636 // Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
637 // contribute to state visible outside of this package.
642 * Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
643 * in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
644 * knowledge and update it when {@link #sweep()} is invoked.
646 private byte parentRef = PARENTREF_UNKNOWN;
647 private static final byte PARENTREF_UNKNOWN = -1;
648 private static final byte PARENTREF_ABSENT = 0;
649 private static final byte PARENTREF_PRESENT = 1;
652 * Acquire a reference on this context. As long as there is at least one reference outstanding,
653 * {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
655 * @throws VerifyException if {@link #effectiveSubstatements()} has already been discarded
657 final void incRef() {
658 final int current = refcount;
659 verify(current >= REFCOUNT_NONE, "Attempted to access reference count of %s", this);
660 if (current != REFCOUNT_DEFUNCT) {
661 // Note: can end up becoming REFCOUNT_DEFUNCT on overflow
662 refcount = current + 1;
664 LOG.debug("Disabled refcount increment of {}", this);
669 * Release a reference on this context. This call may result in {@link #effectiveSubstatements()} becoming
672 final void decRef() {
673 final int current = refcount;
674 if (current == REFCOUNT_DEFUNCT) {
676 LOG.debug("Disabled refcount decrement of {}", this);
679 if (current <= REFCOUNT_NONE) {
680 // Underflow, become defunct
681 // FIXME: add a global 'warn once' flag
682 LOG.warn("Statement refcount underflow, reference counting disabled for {}", this, new Throwable());
683 refcount = REFCOUNT_DEFUNCT;
687 refcount = current - 1;
688 LOG.trace("Refcount {} on {}", refcount, this);
690 if (refcount == REFCOUNT_NONE) {
696 * Return {@code true} if this context has no outstanding references.
698 * @return True if this context has no outstanding references.
700 final boolean noRefs() {
701 final int local = refcount;
702 return local < REFCOUNT_NONE || local == REFCOUNT_NONE && noParentRef();
705 private void lastDecRef() {
706 if (noImplictRef()) {
707 // We are no longer guarded by effective instance
712 final byte prevRefs = parentRef;
713 if (prevRefs == PARENTREF_ABSENT) {
714 // We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
717 } else if (prevRefs == PARENTREF_UNKNOWN) {
718 // Noone observed our parentRef, just update it
719 loadParentRefcount();
723 static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
724 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
725 final byte prevRef = stmt.parentRef;
726 stmt.parentRef = PARENTREF_ABSENT;
727 if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
728 // Child thinks it is pinned down, update its perspective
729 stmt.markNoParentRef();
734 abstract void markNoParentRef();
736 static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
737 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
743 * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
745 private void sweep() {
746 parentRef = PARENTREF_ABSENT;
747 if (refcount == REFCOUNT_NONE && noImplictRef()) {
748 LOG.trace("Releasing {}", this);
753 static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
755 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
756 if (stmt.refcount > REFCOUNT_NONE || !stmt.noImplictRef()) {
764 * Implementation-specific sweep action. This is expected to perform a recursive {@link #sweep(Collection)} on all
765 * {@link #declaredSubstatements()} and {@link #effectiveSubstatements()} and report the result of the sweep
769 * {@link #effectiveSubstatements()} as well as namespaces may become inoperable as a result of this operation.
771 * @return True if the entire tree has been completely swept, false otherwise.
773 abstract int sweepSubstatements();
775 // Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
776 private void sweepOnDecrement() {
777 LOG.trace("Sweeping on decrement {}", this);
779 // No further parent references, sweep our state.
783 // Propagate towards parent if there is one
784 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
785 if (parent != null) {
786 parent.sweepOnChildDecrement();
790 // Called from child when it has lost its final reference
791 private void sweepOnChildDecrement() {
792 if (isAwaitingChildren()) {
793 // We are a child for which our parent is waiting. Notify it and we are done.
798 // Check parent reference count
799 final int refs = refcount;
800 if (refs > REFCOUNT_NONE || refs <= REFCOUNT_SWEEPING || !noImplictRef()) {
805 // parent is potentially reclaimable
807 LOG.trace("Cleanup {} of parent {}", refcount, this);
809 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
810 if (parent != null) {
811 parent.sweepOnChildDecrement();
817 private boolean noImplictRef() {
818 return effectiveInstance != null || !isSupportedToBuildEffective();
821 private boolean noParentRef() {
822 return parentRefcount() == PARENTREF_ABSENT;
825 private byte parentRefcount() {
827 return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
830 private byte loadParentRefcount() {
831 return parentRef = calculateParentRefcount();
834 private byte calculateParentRefcount() {
835 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
836 if (parent == null) {
837 return PARENTREF_ABSENT;
839 // There are three possibilities:
840 // - REFCOUNT_NONE, in which case we need to search next parent
841 // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
843 // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
844 final int refs = parent.refcount;
845 if (refs == REFCOUNT_NONE) {
846 return parent.parentRefcount();
848 return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
851 private boolean isAwaitingChildren() {
852 return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
855 private void sweepOnChildDone() {
856 LOG.trace("Sweeping on child done {}", this);
857 final int current = refcount;
858 if (current >= REFCOUNT_NONE) {
859 // no-op, perhaps we want to handle some cases differently?
860 LOG.trace("Ignoring child sweep of {} for {}", this, current);
863 verify(current != REFCOUNT_SWEPT, "Attempt to sweep a child of swept %s", this);
865 refcount = current + 1;
866 LOG.trace("Child refcount {}", refcount);
867 if (refcount == REFCOUNT_NONE) {
869 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
870 LOG.trace("Propagating to parent {}", parent);
871 if (parent != null && parent.isAwaitingChildren()) {
872 parent.sweepOnChildDone();
877 private void sweepDone() {
878 LOG.trace("Sweep done for {}", this);
879 refcount = REFCOUNT_SWEPT;
883 private boolean sweepState() {
884 refcount = REFCOUNT_SWEEPING;
885 final int childRefs = sweepSubstatements();
886 if (childRefs == 0) {
890 if (childRefs < 0 || childRefs >= REFCOUNT_DEFUNCT) {
891 // FIXME: add a global 'warn once' flag
892 LOG.warn("Negative child refcount {} cannot be stored, reference counting disabled for {}", childRefs, this,
894 refcount = REFCOUNT_DEFUNCT;
896 LOG.trace("Still {} outstanding children of {}", childRefs, this);
897 refcount = -childRefs;