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.EffectiveStmtCtx.Parent;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.ExecutionOrder;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
48 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
49 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
50 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * Real "core" reactor statement implementation of {@link Mutable}, supporting basic reactor lifecycle.
57 * @param <A> Argument type
58 * @param <D> Declared Statement representation
59 * @param <E> Effective Statement representation
61 abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
62 extends NamespaceStorageSupport implements Mutable<A, D, E>, Current<A, D> {
63 private static final Logger LOG = LoggerFactory.getLogger(ReactorStmtCtx.class);
66 * Substatement refcount tracking. This mechanics deals with retaining substatements for the purposes of
67 * instantiating their lazy copies in InferredStatementContext. It works in concert with {@link #buildEffective()}
68 * and {@link #declared()}: declared/effective statement views hold an implicit reference and refcount-based
69 * sweep is not activated until they are done (or this statement is not {@link #isSupportedToBuildEffective}).
72 * Reference count is hierarchical in that parent references also pin down their child statements and do not allow
76 * The counter's positive values are tracking incoming references via {@link #incRef()}/{@link #decRef()} methods.
77 * Once we transition to sweeping, this value becomes negative counting upwards to {@link #REFCOUNT_NONE} based on
78 * {@link #sweepOnChildDone()}. Once we reach that, we transition to {@link #REFCOUNT_SWEPT}.
80 private int refcount = REFCOUNT_NONE;
82 * No outstanding references, this statement is a potential candidate for sweeping, provided it has populated its
83 * declared and effective views and {@link #parentRef} is known to be absent.
85 private static final int REFCOUNT_NONE = 0;
87 * Reference count overflow or some other recoverable logic error. Do not rely on refcounts and do not sweep
91 * Note on value assignment:
92 * This allow our incRef() to naturally progress to being saturated. Others jump there directly.
93 * It also makes it it impossible to observe {@code Interger.MAX_VALUE} children, which we take advantage of for
94 * {@link #REFCOUNT_SWEEPING}.
96 private static final int REFCOUNT_DEFUNCT = Integer.MAX_VALUE;
98 * This statement is being actively swept. This is a transient value set when we are sweeping our children, so that
99 * we prevent re-entering this statement.
102 * Note on value assignment:
103 * The value is lower than any legal child refcount due to {@link #REFCOUNT_DEFUNCT} while still being higher than
104 * {@link #REFCOUNT_SWEPT}.
106 private static final int REFCOUNT_SWEEPING = -Integer.MAX_VALUE;
108 * This statement, along with its entire subtree has been swept and we positively know all our children have reached
109 * this state. We {@link #sweepNamespaces()} upon reaching this state.
112 * Note on value assignment:
113 * This is the lowest value observable, making it easier on checking others on equality.
115 private static final int REFCOUNT_SWEPT = Integer.MIN_VALUE;
118 * Effective instance built from this context. This field as dual types. Under normal circumstances in matches the
119 * {@link #buildEffective()} instance. If this context is reused, it can be inflated to {@link EffectiveInstances}
120 * and also act as a common instance reuse site.
122 private @Nullable E effectiveInstance;
124 // Master flag controlling whether this context can yield an effective statement
125 // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
126 // of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
127 private boolean isSupportedToBuildEffective = true;
129 // EffectiveConfig mapping
130 private static final int MASK_CONFIG = 0x03;
131 private static final int HAVE_CONFIG = 0x04;
132 // Effective instantiation mechanics for StatementContextBase: if this flag is set all substatements are known not
133 // change when instantiated. This includes context-independent statements as well as any statements which are
134 // ignored during copy instantiation.
135 private static final int ALL_INDEPENDENT = 0x08;
136 // Flag bit assignments
137 private static final int IS_SUPPORTED_BY_FEATURES = 0x10;
138 private static final int HAVE_SUPPORTED_BY_FEATURES = 0x20;
139 private static final int IS_IGNORE_IF_FEATURE = 0x40;
140 private static final int HAVE_IGNORE_IF_FEATURE = 0x80;
141 // Have-and-set flag constants, also used as masks
142 private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
143 private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
145 private static final EffectiveConfig[] EFFECTIVE_CONFIGS;
148 final EffectiveConfig[] values = EffectiveConfig.values();
149 final int length = values.length;
150 verify(length == 4, "Unexpected EffectiveConfig cardinality %s", length);
151 EFFECTIVE_CONFIGS = values;
154 // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
155 // hence improve memory layout.
158 // Flag for use by AbstractResumedStatement, ReplicaStatementContext and InferredStatementContext. Each of them
159 // uses it to indicated a different condition. This is hiding in the alignment shadow created by
160 // 'isSupportedToBuildEffective'.
161 // FIXME: move this out once we have JDK15+
162 private boolean boolFlag;
164 // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
165 // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
166 // FIXME: this should become 'QName'
167 private SchemaPath schemaPath;
173 ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
174 isSupportedToBuildEffective = original.isSupportedToBuildEffective;
175 boolFlag = original.boolFlag;
176 flags = original.flags;
179 // Used by ReplicaStatementContext only
180 ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original, final Void dummy) {
181 boolFlag = isSupportedToBuildEffective = original.isSupportedToBuildEffective;
182 flags = original.flags;
187 // Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
188 // up mixing concerns and simple details with more complex logic.
193 public abstract StatementContextBase<?, ?, ?> getParentContext();
196 public abstract RootStatementContext<?, ?, ?> getRoot();
199 public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
202 public final @NonNull Registry getBehaviourRegistry() {
203 return getRoot().getBehaviourRegistryImpl();
207 public final YangVersion yangVersion() {
208 return getRoot().getRootVersionImpl();
212 public final void setRootVersion(final YangVersion version) {
213 getRoot().setRootVersionImpl(version);
217 public final void addRequiredSource(final SourceIdentifier dependency) {
218 getRoot().addRequiredSourceImpl(dependency);
222 public final void setRootIdentifier(final SourceIdentifier identifier) {
223 getRoot().setRootIdentifierImpl(identifier);
227 public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
228 return getRoot().getSourceContext().newInferenceAction(phase);
232 public final StatementDefinition publicDefinition() {
233 return definition().getPublicView();
237 public final Parent effectiveParent() {
238 return getParentContext();
242 public final QName moduleName() {
243 final RootStatementContext<?, ?, ?> root = getRoot();
244 return QName.create(StmtContextUtils.getRootModuleQName(root), root.getRawArgument());
248 @Deprecated(since = "7.0.9", forRemoval = true)
249 public final EffectiveStatement<?, ?> original() {
250 return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
254 // In the next two methods we are looking for an effective statement. If we already have an effective instance,
255 // defer to it's implementation of the equivalent search. Otherwise we search our substatement contexts.
257 // Note that the search function is split, so as to allow InferredStatementContext to do its own thing first.
261 public final <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
262 final @NonNull Class<Z> type) {
263 final E existing = effectiveInstance;
264 return existing != null ? existing.findFirstEffectiveSubstatementArgument(type)
265 : findSubstatementArgumentImpl(type);
269 public final boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
270 final E existing = effectiveInstance;
271 return existing != null ? existing.findFirstEffectiveSubstatement(type).isPresent() : hasSubstatementImpl(type);
274 // Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
275 <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
276 final @NonNull Class<Z> type) {
277 return allSubstatementsStream()
278 .filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
280 .map(ctx -> (X) ctx.getArgument());
283 // Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
284 boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
285 return allSubstatementsStream()
286 .anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
291 @SuppressWarnings("unchecked")
292 public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
293 return (StmtContext<A, D, Z>) this;
297 public final String toString() {
298 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
301 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
302 return toStringHelper.add("definition", definition()).add("rawArgument", rawArgument())
303 .add("refCount", refString());
306 private String refString() {
307 final int current = refcount;
309 case REFCOUNT_DEFUNCT:
311 case REFCOUNT_SWEEPING:
316 return String.valueOf(refcount);
321 * Return the context in which this statement was defined.
323 * @return statement definition
325 abstract @NonNull StatementDefinitionContext<A, D, E> definition();
329 // NamespaceStorageSupport/Mutable integration methods. Keep these together.
334 public final <K, V, T extends K, N extends ParserNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
336 return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
340 public final <K, V, N extends ParserNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
341 return getNamespace(type);
345 public final <K, V, N extends ParserNamespace<K, V>>
346 Map<K, V> localNamespacePortion(final Class<@NonNull N> type) {
347 return getLocalNamespace(type);
351 protected <K, V, N extends ParserNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
353 // definition().onNamespaceElementAdded(this, type, key, value);
357 * Return the effective statement view of a copy operation. This method may return one of:
359 * <li>{@code this}, when the effective view did not change</li>
360 * <li>an InferredStatementContext, when there is a need for inference-equivalent copy</li>
361 * <li>{@code null}, when the statement failed to materialize</li>
364 * @param parent Proposed new parent
365 * @param type Copy operation type
366 * @param targetModule New target module
367 * @return {@link ReactorStmtCtx} holding effective view
369 abstract @Nullable ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(StatementContextBase<?, ?, ?> parent, CopyType type,
370 QNameModule targetModule);
373 public final ReplicaStatementContext<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
374 checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
375 final var ret = replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
376 definition().onStatementAdded(ret);
380 abstract @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(@NonNull StatementContextBase<?, ?, ?> parent);
384 // Statement build entry points -- both public and package-private.
389 public final E buildEffective() {
391 return (existing = effectiveInstance) != null ? existing : loadEffective();
394 private @NonNull E loadEffective() {
395 // Creating an effective statement does not strictly require a declared instance -- there are statements like
396 // 'input', which are implicitly defined.
397 // Our implementation design makes an invariant assumption that buildDeclared() has been called by the time
398 // we attempt to create effective statement:
401 final E ret = createEffective();
402 effectiveInstance = ret;
403 // we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
405 if (refcount == REFCOUNT_NONE) {
411 abstract @NonNull E createEffective();
414 * Walk this statement's copy history and return the statement closest to original which has not had its effective
415 * statements modified. This statement and returned substatement logically have the same set of substatements, hence
416 * share substatement-derived state.
418 * @return Closest {@link ReactorStmtCtx} with equivalent effective substatements
420 abstract @NonNull ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource();
423 public final ModelProcessingPhase getCompletedPhase() {
424 return ModelProcessingPhase.ofExecutionOrder(executionOrder());
427 abstract byte executionOrder();
430 * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
431 * this method does nothing. This must not be called with {@link ExecutionOrder#NULL}.
433 * @param phase to be executed (completed)
434 * @return true if phase was successfully completed
435 * @throws SourceException when an error occurred in source parsing
437 final boolean tryToCompletePhase(final byte executionOrder) {
438 return executionOrder() >= executionOrder || doTryToCompletePhase(executionOrder);
441 abstract boolean doTryToCompletePhase(byte targetOrder);
445 // Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
451 public final boolean isSupportedToBuildEffective() {
452 return isSupportedToBuildEffective;
456 public final void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
457 this.isSupportedToBuildEffective = isSupportedToBuildEffective;
461 public final boolean isSupportedByFeatures() {
462 final int fl = flags & SET_SUPPORTED_BY_FEATURES;
464 return fl == SET_SUPPORTED_BY_FEATURES;
466 if (isIgnoringIfFeatures()) {
467 flags |= SET_SUPPORTED_BY_FEATURES;
472 * If parent is supported, we need to check if-features statements of this context.
474 if (isParentSupportedByFeatures()) {
475 // If the set of supported features has not been provided, all features are supported by default.
476 final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
477 SupportedFeatures.SUPPORTED_FEATURES);
478 if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
479 flags |= SET_SUPPORTED_BY_FEATURES;
484 // Either parent is not supported or this statement is not supported
485 flags |= HAVE_SUPPORTED_BY_FEATURES;
489 protected abstract boolean isParentSupportedByFeatures();
492 * Config statements are not all that common which means we are performing a recursive search towards the root
493 * every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
494 * for the (usually non-existent) config statement.
497 * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
498 * result without performing any lookups, solely to support {@link #effectiveConfig()}.
501 * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
502 * {@link #isIgnoringConfig(StatementContextBase)}.
504 final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
505 return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
508 private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
509 final EffectiveConfig parentConfig = parent.effectiveConfig();
511 final EffectiveConfig myConfig;
512 if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
513 final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
514 if (optConfig.isPresent()) {
515 if (optConfig.orElseThrow()) {
516 // Validity check: if parent is config=false this cannot be a config=true
517 InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
518 "Parent node has config=false, this node must not be specifed as config=true");
519 myConfig = EffectiveConfig.TRUE;
521 myConfig = EffectiveConfig.FALSE;
524 // If "config" statement is not specified, the default is the same as the parent's "config" value.
525 myConfig = parentConfig;
528 myConfig = EffectiveConfig.IGNORED;
531 flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
535 protected abstract boolean isIgnoringConfig();
538 * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
539 * keep on returning the same result without performing any lookups. Exists only to support
540 * {@link SubstatementContext#isIgnoringConfig()}.
543 * Note: use of this method implies that {@link #isConfiguration()} is realized with
544 * {@link #effectiveConfig(StatementContextBase)}.
546 final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
547 return EffectiveConfig.IGNORED == effectiveConfig(parent);
550 protected abstract boolean isIgnoringIfFeatures();
553 * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
554 * keep on returning the same result without performing any lookups. Exists only to support
555 * {@link SubstatementContext#isIgnoringIfFeatures()}.
557 final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
558 final int fl = flags & SET_IGNORE_IF_FEATURE;
560 return fl == SET_IGNORE_IF_FEATURE;
562 if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
563 flags |= SET_IGNORE_IF_FEATURE;
567 flags |= HAVE_IGNORE_IF_FEATURE;
571 // These two exist only due to memory optimization, should live in AbstractResumedStatement.
572 final boolean fullyDefined() {
576 final void setFullyDefined() {
580 // This exists only due to memory optimization, should live in ReplicaStatementContext. In this context the flag
581 // indicates the need to drop source's reference count when we are being swept.
582 final boolean haveSourceReference() {
586 // These three exist due to memory optimization, should live in InferredStatementContext. In this context the flag
587 // indicates whether or not this statement's substatement file was modified, i.e. it is not quite the same as the
589 final boolean isModified() {
593 final void setModified() {
597 final void setUnmodified() {
601 // These two exist only for StatementContextBase. Since we are squeezed for size, with only a single bit available
602 // in flags, we default to 'false' and only set the flag to true when we are absolutely sure -- and all other cases
603 // err on the side of caution by taking the time to evaluate each substatement separately.
604 final boolean allSubstatementsContextIndependent() {
605 return (flags & ALL_INDEPENDENT) != 0;
608 final void setAllSubstatementsContextIndependent() {
609 flags |= ALL_INDEPENDENT;
614 // Various functionality from AbstractTypeStatementSupport. This used to work on top of SchemaPath, now it still
615 // lives here. Ultimate future is either proper graduation or (more likely) move to AbstractTypeStatementSupport.
620 public final QName argumentAsTypeQName() {
621 return interpretAsQName(getRawArgument());
625 public final QNameModule effectiveNamespace() {
626 // FIXME: there has to be a better way to do this
627 return getSchemaPath().getLastComponent().getModule();
632 // Common SchemaPath cache. All of this is bound to be removed once YANGTOOLS-1066 is done.
636 // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
638 final @Nullable SchemaPath substatementGetSchemaPath() {
639 if (schemaPath == null) {
640 schemaPath = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
645 // FIXME: 7.0.0: this method's logic needs to be moved to the respective StatementSupport classes
647 private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
648 final SchemaPath parentPath = parent.getSchemaPath();
649 if (StmtContextUtils.isUnknownStatement(this)) {
650 return parentPath.createChild(publicDefinition().getStatementName());
652 final Object argument = argument();
653 if (argument instanceof QName) {
654 final QName qname = (QName) argument;
655 if (producesDeclared(UsesStatement.class)) {
659 return parentPath.createChild(qname);
661 if (argument instanceof String) {
662 return parentPath.createChild(interpretAsQName((String) argument));
664 if (argument instanceof SchemaNodeIdentifier
665 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
666 || producesDeclared(DeviationStatement.class))) {
668 return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
671 // FIXME: this does not look right, investigate more?
675 private @NonNull QName interpretAsQName(final String argument) {
676 // FIXME: This may yield illegal argument exceptions
677 return StmtContextUtils.qnameFromArgument(getOriginalCtx().orElse(this), argument);
682 // Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
683 // contribute to state visible outside of this package.
688 * Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
689 * in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
690 * knowledge and update it when {@link #sweep()} is invoked.
692 private byte parentRef = PARENTREF_UNKNOWN;
693 private static final byte PARENTREF_UNKNOWN = -1;
694 private static final byte PARENTREF_ABSENT = 0;
695 private static final byte PARENTREF_PRESENT = 1;
698 * Acquire a reference on this context. As long as there is at least one reference outstanding,
699 * {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
701 * @throws VerifyException if {@link #effectiveSubstatements()} has already been discarded
703 final void incRef() {
704 final int current = refcount;
705 verify(current >= REFCOUNT_NONE, "Attempted to access reference count of %s", this);
706 if (current != REFCOUNT_DEFUNCT) {
707 // Note: can end up becoming REFCOUNT_DEFUNCT on overflow
708 refcount = current + 1;
710 LOG.debug("Disabled refcount increment of {}", this);
715 * Release a reference on this context. This call may result in {@link #effectiveSubstatements()} becoming
718 final void decRef() {
719 final int current = refcount;
720 if (current == REFCOUNT_DEFUNCT) {
722 LOG.debug("Disabled refcount decrement of {}", this);
725 if (current <= REFCOUNT_NONE) {
726 // Underflow, become defunct
727 // FIXME: add a global 'warn once' flag
728 LOG.warn("Statement refcount underflow, reference counting disabled for {}", this, new Throwable());
729 refcount = REFCOUNT_DEFUNCT;
733 refcount = current - 1;
734 LOG.trace("Refcount {} on {}", refcount, this);
736 if (refcount == REFCOUNT_NONE) {
742 * Return {@code true} if this context has no outstanding references.
744 * @return True if this context has no outstanding references.
746 final boolean noRefs() {
747 final int local = refcount;
748 return local < REFCOUNT_NONE || local == REFCOUNT_NONE && noParentRef();
751 private void lastDecRef() {
752 if (noImplictRef()) {
753 // We are no longer guarded by effective instance
758 final byte prevRefs = parentRef;
759 if (prevRefs == PARENTREF_ABSENT) {
760 // We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
763 } else if (prevRefs == PARENTREF_UNKNOWN) {
764 // Noone observed our parentRef, just update it
765 loadParentRefcount();
769 static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
770 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
771 final byte prevRef = stmt.parentRef;
772 stmt.parentRef = PARENTREF_ABSENT;
773 if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
774 // Child thinks it is pinned down, update its perspective
775 stmt.markNoParentRef();
780 abstract void markNoParentRef();
782 static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
783 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
789 * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
791 private void sweep() {
792 parentRef = PARENTREF_ABSENT;
793 if (refcount == REFCOUNT_NONE && noImplictRef()) {
794 LOG.trace("Releasing {}", this);
799 static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
801 for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
802 if (stmt.refcount > REFCOUNT_NONE || !stmt.noImplictRef()) {
810 * Implementation-specific sweep action. This is expected to perform a recursive {@link #sweep(Collection)} on all
811 * {@link #declaredSubstatements()} and {@link #effectiveSubstatements()} and report the result of the sweep
815 * {@link #effectiveSubstatements()} as well as namespaces may become inoperable as a result of this operation.
817 * @return True if the entire tree has been completely swept, false otherwise.
819 abstract int sweepSubstatements();
821 // Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
822 private void sweepOnDecrement() {
823 LOG.trace("Sweeping on decrement {}", this);
825 // No further parent references, sweep our state.
829 // Propagate towards parent if there is one
830 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
831 if (parent != null) {
832 parent.sweepOnChildDecrement();
836 // Called from child when it has lost its final reference
837 private void sweepOnChildDecrement() {
838 if (isAwaitingChildren()) {
839 // We are a child for which our parent is waiting. Notify it and we are done.
844 // Check parent reference count
845 final int refs = refcount;
846 if (refs > REFCOUNT_NONE || refs <= REFCOUNT_SWEEPING || !noImplictRef()) {
851 // parent is potentially reclaimable
853 LOG.trace("Cleanup {} of parent {}", refcount, this);
855 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
856 if (parent != null) {
857 parent.sweepOnChildDecrement();
863 private boolean noImplictRef() {
864 return effectiveInstance != null || !isSupportedToBuildEffective();
867 private boolean noParentRef() {
868 return parentRefcount() == PARENTREF_ABSENT;
871 private byte parentRefcount() {
873 return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
876 private byte loadParentRefcount() {
877 return parentRef = calculateParentRefcount();
880 private byte calculateParentRefcount() {
881 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
882 if (parent == null) {
883 return PARENTREF_ABSENT;
886 // A slight wrinkle here is that our machinery handles only PRESENT -> ABSENT invalidation and we can reach here
887 // while inference is still ongoing and hence we may not have a complete picture about existing references. We
888 // could therefore end up caching an ABSENT result and then that information becoming stale as a new reference
890 if (parent.executionOrder() < ExecutionOrder.EFFECTIVE_MODEL) {
891 return PARENTREF_UNKNOWN;
894 // There are three possibilities:
895 // - REFCOUNT_NONE, in which case we need to search next parent
896 // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
898 // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
899 final int refs = parent.refcount;
900 if (refs == REFCOUNT_NONE) {
901 return parent.parentRefcount();
903 return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
906 private boolean isAwaitingChildren() {
907 return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
910 private void sweepOnChildDone() {
911 LOG.trace("Sweeping on child done {}", this);
912 final int current = refcount;
913 if (current >= REFCOUNT_NONE) {
914 // no-op, perhaps we want to handle some cases differently?
915 LOG.trace("Ignoring child sweep of {} for {}", this, current);
918 verify(current != REFCOUNT_SWEPT, "Attempt to sweep a child of swept %s", this);
920 refcount = current + 1;
921 LOG.trace("Child refcount {}", refcount);
922 if (refcount == REFCOUNT_NONE) {
924 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
925 LOG.trace("Propagating to parent {}", parent);
926 if (parent != null && parent.isAwaitingChildren()) {
927 parent.sweepOnChildDone();
932 private void sweepDone() {
933 LOG.trace("Sweep done for {}", this);
934 refcount = REFCOUNT_SWEPT;
938 private boolean sweepState() {
939 refcount = REFCOUNT_SWEEPING;
940 final int childRefs = sweepSubstatements();
941 if (childRefs == 0) {
945 if (childRefs < 0 || childRefs >= REFCOUNT_DEFUNCT) {
946 // FIXME: add a global 'warn once' flag
947 LOG.warn("Negative child refcount {} cannot be stored, reference counting disabled for {}", childRefs, this,
949 refcount = REFCOUNT_DEFUNCT;
951 LOG.trace("Still {} outstanding children of {}", childRefs, this);
952 refcount = -childRefs;