Cache substatement context-independence summary
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / ReactorStmtCtx.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
9
10 import static com.google.common.base.Verify.verify;
11
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.VerifyException;
15 import java.util.Collection;
16 import java.util.Map;
17 import java.util.Optional;
18 import java.util.Set;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.common.QNameModule;
23 import org.opendaylight.yangtools.yang.common.YangVersion;
24 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
25 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
28 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
33 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
34 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
46 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
47 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Real "core" reactor statement implementation of {@link Mutable}, supporting basic reactor lifecycle.
53  *
54  * @param <A> Argument type
55  * @param <D> Declared Statement representation
56  * @param <E> Effective Statement representation
57  */
58 abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
59         extends NamespaceStorageSupport implements Mutable<A, D, E>, Current<A, D> {
60     private static final Logger LOG = LoggerFactory.getLogger(ReactorStmtCtx.class);
61
62     /**
63      * Substatement refcount tracking. This mechanics deals with retaining substatements for the purposes of
64      * instantiating their lazy copies in InferredStatementContext. It works in concert with {@link #buildEffective()}
65      * and {@link #declared()}: declared/effective statement views hold an implicit reference and refcount-based
66      * sweep is not activated until they are done (or this statement is not {@link #isSupportedToBuildEffective}).
67      *
68      * <p>
69      * Reference count is hierarchical in that parent references also pin down their child statements and do not allow
70      * them to be swept.
71      *
72      * <p>
73      * The counter's positive values are tracking incoming references via {@link #incRef()}/{@link #decRef()} methods.
74      * Once we transition to sweeping, this value becomes negative counting upwards to {@link #REFCOUNT_NONE} based on
75      * {@link #sweepOnChildDone()}. Once we reach that, we transition to {@link #REFCOUNT_SWEPT}.
76      */
77     private int refcount = REFCOUNT_NONE;
78     /**
79      * No outstanding references, this statement is a potential candidate for sweeping, provided it has populated its
80      * declared and effective views and {@link #parentRef} is known to be absent.
81      */
82     private static final int REFCOUNT_NONE = 0;
83     /**
84      * Reference count overflow or some other recoverable logic error. Do not rely on refcounts and do not sweep
85      * anything.
86      *
87      * <p>
88      * Note on value assignment:
89      * This allow our incRef() to naturally progress to being saturated. Others jump there directly.
90      * It also makes it  it impossible to observe {@code Interger.MAX_VALUE} children, which we take advantage of for
91      * {@link #REFCOUNT_SWEEPING}.
92      */
93     private static final int REFCOUNT_DEFUNCT = Integer.MAX_VALUE;
94     /**
95      * This statement is being actively swept. This is a transient value set when we are sweeping our children, so that
96      * we prevent re-entering this statement.
97      *
98      * <p>
99      * Note on value assignment:
100      * The value is lower than any legal child refcount due to {@link #REFCOUNT_DEFUNCT} while still being higher than
101      * {@link #REFCOUNT_SWEPT}.
102      */
103     private static final int REFCOUNT_SWEEPING = -Integer.MAX_VALUE;
104     /**
105      * This statement, along with its entire subtree has been swept and we positively know all our children have reached
106      * this state. We {@link #sweepNamespaces()} upon reaching this state.
107      *
108      * <p>
109      * Note on value assignment:
110      * This is the lowest value observable, making it easier on checking others on equality.
111      */
112     private static final int REFCOUNT_SWEPT = Integer.MIN_VALUE;
113
114     private @Nullable E effectiveInstance;
115
116     // Master flag controlling whether this context can yield an effective statement
117     // FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
118     //        of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
119     private boolean isSupportedToBuildEffective = true;
120
121     // EffectiveConfig mapping
122     private static final int MASK_CONFIG                = 0x03;
123     private static final int HAVE_CONFIG                = 0x04;
124     // Effective instantiation mechanics for StatementContextBase: if this flag is set all substatements are known not
125     // change when instantiated. This includes context-independent statements as well as any statements which are
126     // ignored during copy instantiation.
127     private static final int ALL_INDEPENDENT            = 0x08;
128     // Flag bit assignments
129     private static final int IS_SUPPORTED_BY_FEATURES   = 0x10;
130     private static final int HAVE_SUPPORTED_BY_FEATURES = 0x20;
131     private static final int IS_IGNORE_IF_FEATURE       = 0x40;
132     private static final int HAVE_IGNORE_IF_FEATURE     = 0x80;
133     // Have-and-set flag constants, also used as masks
134     private static final int SET_SUPPORTED_BY_FEATURES  = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
135     private static final int SET_IGNORE_IF_FEATURE      = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
136
137     private static final EffectiveConfig[] EFFECTIVE_CONFIGS;
138
139     static {
140         final EffectiveConfig[] values = EffectiveConfig.values();
141         final int length = values.length;
142         verify(length == 4, "Unexpected EffectiveConfig cardinality %s", length);
143         EFFECTIVE_CONFIGS = values;
144     }
145
146     // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
147     // hence improve memory layout.
148     private byte flags;
149
150     // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
151     // FIXME: move this out once we have JDK15+
152     private boolean fullyDefined;
153
154     // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
155     // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
156     @Deprecated
157     private volatile SchemaPath schemaPath;
158
159     ReactorStmtCtx() {
160         // Empty on purpose
161     }
162
163     ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
164         isSupportedToBuildEffective = original.isSupportedToBuildEffective;
165         fullyDefined = original.fullyDefined;
166         flags = original.flags;
167     }
168
169     //
170     //
171     // Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
172     // up mixing concerns and simple details with more complex logic.
173     //
174     //
175
176     @Override
177     public abstract StatementContextBase<?, ?, ?> getParentContext();
178
179     @Override
180     public abstract RootStatementContext<?, ?, ?> getRoot();
181
182     @Override
183     public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
184
185     @Override
186     public final @NonNull Registry getBehaviourRegistry() {
187         return getRoot().getBehaviourRegistryImpl();
188     }
189
190     @Override
191     public final YangVersion yangVersion() {
192         return getRoot().getRootVersionImpl();
193     }
194
195     @Override
196     public final void setRootVersion(final YangVersion version) {
197         getRoot().setRootVersionImpl(version);
198     }
199
200     @Override
201     public final void addRequiredSource(final SourceIdentifier dependency) {
202         getRoot().addRequiredSourceImpl(dependency);
203     }
204
205     @Override
206     public final void setRootIdentifier(final SourceIdentifier identifier) {
207         getRoot().setRootIdentifierImpl(identifier);
208     }
209
210     @Override
211     public final boolean isEnabledSemanticVersioning() {
212         return getRoot().isEnabledSemanticVersioningImpl();
213     }
214
215     @Override
216     public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
217         return getRoot().getSourceContext().newInferenceAction(phase);
218     }
219
220     @Override
221     public final StatementDefinition publicDefinition() {
222         return definition().getPublicView();
223     }
224
225     @Override
226     public final Parent effectiveParent() {
227         return getParentContext();
228     }
229
230     @Override
231     public final QName moduleName() {
232         final RootStatementContext<?, ?, ?> root = getRoot();
233         return QName.create(StmtContextUtils.getRootModuleQName(root), root.getRawArgument());
234     }
235
236     @Override
237     public final EffectiveStatement<?, ?> original() {
238         return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
239     }
240
241     @Override
242     // Non-final due to InferredStatementContext's override
243     public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
244             final @NonNull Class<Z> type) {
245         return allSubstatementsStream()
246             .filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
247             .findAny()
248             .map(ctx -> (X) ctx.getArgument());
249     }
250
251     @Override
252     // Non-final due to InferredStatementContext's override
253     public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
254         return allSubstatementsStream()
255             .anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
256     }
257
258     @Override
259     @Deprecated
260     @SuppressWarnings("unchecked")
261     public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
262         return (StmtContext<A, D, Z>) this;
263     }
264
265     @Override
266     public final String toString() {
267         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
268     }
269
270     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
271         return toStringHelper.add("definition", definition()).add("rawArgument", rawArgument());
272     }
273
274     /**
275      * Return the context in which this statement was defined.
276      *
277      * @return statement definition
278      */
279     abstract @NonNull StatementDefinitionContext<A, D, E> definition();
280
281     //
282     //
283     // NamespaceStorageSupport/Mutable integration methods. Keep these together.
284     //
285     //
286
287     @Override
288     public final <K, V, T extends K, N extends ParserNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
289             final T key) {
290         return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
291     }
292
293     @Override
294     public final <K, V, N extends ParserNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
295         return getNamespace(type);
296     }
297
298     @Override
299     public final <K, V, N extends ParserNamespace<K, V>>
300             Map<K, V> localNamespacePortion(final Class<@NonNull N> type) {
301         return getLocalNamespace(type);
302     }
303
304     @Override
305     protected final void checkLocalNamespaceAllowed(final Class<? extends ParserNamespace<?, ?>> type) {
306         definition().checkNamespaceAllowed(type);
307     }
308
309     @Override
310     protected <K, V, N extends ParserNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
311             final V value) {
312         // definition().onNamespaceElementAdded(this, type, key, value);
313     }
314
315     abstract @Nullable ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(StatementContextBase<?, ?, ?> parent, CopyType type,
316         QNameModule targetModule);
317
318     //
319     //
320     // Statement build entry points -- both public and package-private.
321     //
322     //
323
324     @Override
325     public final E buildEffective() {
326         final E existing;
327         return (existing = effectiveInstance) != null ? existing : loadEffective();
328     }
329
330     private E loadEffective() {
331         // Creating an effective statement does not strictly require a declared instance -- there are statements like
332         // 'input', which are implicitly defined.
333         // Our implementation design makes an invariant assumption that buildDeclared() has been called by the time
334         // we attempt to create effective statement:
335         declared();
336
337         final E ret = effectiveInstance = createEffective();
338         // we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
339         // some residue.
340         if (refcount == REFCOUNT_NONE) {
341             sweepOnDecrement();
342         }
343         return ret;
344     }
345
346     abstract @NonNull E createEffective();
347
348     /**
349      * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
350      * this method does nothing.
351      *
352      * @param phase to be executed (completed)
353      * @return true if phase was successfully completed
354      * @throws SourceException when an error occurred in source parsing
355      */
356     final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
357         return phase.isCompletedBy(getCompletedPhase()) || doTryToCompletePhase(phase);
358     }
359
360     abstract boolean doTryToCompletePhase(ModelProcessingPhase phase);
361
362     //
363     //
364     // Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
365     // shadow.
366     //
367     //
368
369     @Override
370     public final boolean isSupportedToBuildEffective() {
371         return isSupportedToBuildEffective;
372     }
373
374     @Override
375     public final void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
376         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
377     }
378
379     @Override
380     public final boolean isSupportedByFeatures() {
381         final int fl = flags & SET_SUPPORTED_BY_FEATURES;
382         if (fl != 0) {
383             return fl == SET_SUPPORTED_BY_FEATURES;
384         }
385         if (isIgnoringIfFeatures()) {
386             flags |= SET_SUPPORTED_BY_FEATURES;
387             return true;
388         }
389
390         /*
391          * If parent is supported, we need to check if-features statements of this context.
392          */
393         if (isParentSupportedByFeatures()) {
394             // If the set of supported features has not been provided, all features are supported by default.
395             final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
396                     SupportedFeatures.SUPPORTED_FEATURES);
397             if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
398                 flags |= SET_SUPPORTED_BY_FEATURES;
399                 return true;
400             }
401         }
402
403         // Either parent is not supported or this statement is not supported
404         flags |= HAVE_SUPPORTED_BY_FEATURES;
405         return false;
406     }
407
408     protected abstract boolean isParentSupportedByFeatures();
409
410     /**
411      * Config statements are not all that common which means we are performing a recursive search towards the root
412      * every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
413      * for the (usually non-existent) config statement.
414      *
415      * <p>
416      * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
417      * result without performing any lookups, solely to support {@link #effectiveConfig()}.
418      *
419      * <p>
420      * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
421      *       {@link #isIgnoringConfig(StatementContextBase)}.
422      */
423     final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
424         return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
425     }
426
427     private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
428         final EffectiveConfig parentConfig = parent.effectiveConfig();
429
430         final EffectiveConfig myConfig;
431         if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
432             final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
433             if (optConfig.isPresent()) {
434                 if (optConfig.orElseThrow()) {
435                     // Validity check: if parent is config=false this cannot be a config=true
436                     InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
437                         "Parent node has config=false, this node must not be specifed as config=true");
438                     myConfig = EffectiveConfig.TRUE;
439                 } else {
440                     myConfig = EffectiveConfig.FALSE;
441                 }
442             } else {
443                 // If "config" statement is not specified, the default is the same as the parent's "config" value.
444                 myConfig = parentConfig;
445             }
446         } else {
447             myConfig = EffectiveConfig.IGNORED;
448         }
449
450         flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
451         return myConfig;
452     }
453
454     protected abstract boolean isIgnoringConfig();
455
456     /**
457      * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
458      * keep on returning the same result without performing any lookups. Exists only to support
459      * {@link SubstatementContext#isIgnoringConfig()}.
460      *
461      * <p>
462      * Note: use of this method implies that {@link #isConfiguration()} is realized with
463      *       {@link #effectiveConfig(StatementContextBase)}.
464      */
465     final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
466         return EffectiveConfig.IGNORED == effectiveConfig(parent);
467     }
468
469     protected abstract boolean isIgnoringIfFeatures();
470
471     /**
472      * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
473      * keep on returning the same result without performing any lookups. Exists only to support
474      * {@link SubstatementContext#isIgnoringIfFeatures()}.
475      */
476     final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
477         final int fl = flags & SET_IGNORE_IF_FEATURE;
478         if (fl != 0) {
479             return fl == SET_IGNORE_IF_FEATURE;
480         }
481         if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
482             flags |= SET_IGNORE_IF_FEATURE;
483             return true;
484         }
485
486         flags |= HAVE_IGNORE_IF_FEATURE;
487         return false;
488     }
489
490     // These two exist only due to memory optimization, should live in AbstractResumedStatement. We are also reusing
491     // this for ReplicaStatementContext's refcount tracking.
492     final boolean fullyDefined() {
493         return fullyDefined;
494     }
495
496     final void setFullyDefined() {
497         fullyDefined = true;
498     }
499
500     // These two exist only for StatementContextBase. Since we are squeezed for size, with only a single bit available
501     // in flags, we default to 'false' and only set the flag to true when we are absolutely sure -- and all other cases
502     // err on the side of caution by taking the time to evaluate each substatement separately.
503     final boolean allSubstatementsContextIndependent() {
504         return (flags & ALL_INDEPENDENT) != 0;
505     }
506
507     final void setAllSubstatementsContextIndependent() {
508         flags |= ALL_INDEPENDENT;
509     }
510
511     //
512     //
513     // Common SchemaPath cache. All of this is bound to be removed once YANGTOOLS-1066 is done.
514     //
515     //
516
517     // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
518     @Deprecated
519     final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
520         SchemaPath local = schemaPath;
521         if (local == null) {
522             synchronized (this) {
523                 local = schemaPath;
524                 if (local == null) {
525                     schemaPath = local = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
526                 }
527             }
528         }
529
530         return Optional.ofNullable(local);
531     }
532
533     @Deprecated
534     private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
535         final Optional<SchemaPath> maybeParentPath = parent.schemaPath();
536         verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
537         final SchemaPath parentPath = maybeParentPath.get();
538
539         if (StmtContextUtils.isUnknownStatement(this)) {
540             return parentPath.createChild(publicDefinition().getStatementName());
541         }
542         final Object argument = argument();
543         if (argument instanceof QName) {
544             final QName qname = (QName) argument;
545             if (producesDeclared(UsesStatement.class)) {
546                 return maybeParentPath.orElse(null);
547             }
548
549             return parentPath.createChild(qname);
550         }
551         if (argument instanceof String) {
552             // FIXME: This may yield illegal argument exceptions
553             final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
554             final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
555             return parentPath.createChild(qname);
556         }
557         if (argument instanceof SchemaNodeIdentifier
558                 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
559                         || producesDeclared(DeviationStatement.class))) {
560
561             return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
562         }
563
564         // FIXME: this does not look right
565         return maybeParentPath.orElse(null);
566     }
567
568     //
569     //
570     // Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
571     // contribute to state visible outside of this package.
572     //
573     //
574
575     /**
576      * Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
577      * in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
578      * knowledge and update it when {@link #sweep()} is invoked.
579      */
580     private byte parentRef = PARENTREF_UNKNOWN;
581     private static final byte PARENTREF_UNKNOWN = -1;
582     private static final byte PARENTREF_ABSENT  = 0;
583     private static final byte PARENTREF_PRESENT = 1;
584
585     /**
586      * Acquire a reference on this context. As long as there is at least one reference outstanding,
587      * {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
588      *
589      * @throws VerifyException if {@link #effectiveSubstatements()} has already been discarded
590      */
591     final void incRef() {
592         final int current = refcount;
593         verify(current >= REFCOUNT_NONE, "Attempted to access reference count of %s", this);
594         if (current != REFCOUNT_DEFUNCT) {
595             // Note: can end up becoming REFCOUNT_DEFUNCT on overflow
596             refcount = current + 1;
597         } else {
598             LOG.debug("Disabled refcount increment of {}", this);
599         }
600     }
601
602     /**
603      * Release a reference on this context. This call may result in {@link #effectiveSubstatements()} becoming
604      * unavailable.
605      */
606     final void decRef() {
607         final int current = refcount;
608         if (current == REFCOUNT_DEFUNCT) {
609             // no-op
610             LOG.debug("Disabled refcount decrement of {}", this);
611             return;
612         }
613         if (current <= REFCOUNT_NONE) {
614             // Underflow, become defunct
615             LOG.warn("Statement refcount underflow, reference counting disabled for {}", this, new Throwable());
616             refcount = REFCOUNT_DEFUNCT;
617             return;
618         }
619
620         refcount = current - 1;
621         LOG.trace("Refcount {} on {}", refcount, this);
622
623         if (refcount == REFCOUNT_NONE) {
624             lastDecRef();
625         }
626     }
627
628     /**
629      * Return {@code true} if this context has an outstanding reference.
630      *
631      * @return True if this context has an outstanding reference.
632      */
633     final boolean haveRef() {
634         return refcount > REFCOUNT_NONE;
635     }
636
637     private void lastDecRef() {
638         if (noImplictRef()) {
639             // We are no longer guarded by effective instance
640             sweepOnDecrement();
641             return;
642         }
643
644         final byte prevRefs = parentRef;
645         if (prevRefs == PARENTREF_ABSENT) {
646             // We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
647             // updated
648             markNoParentRef();
649         } else if (prevRefs == PARENTREF_UNKNOWN) {
650             // Noone observed our parentRef, just update it
651             loadParentRefcount();
652         }
653     }
654
655     static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
656         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
657             final byte prevRef = stmt.parentRef;
658             stmt.parentRef = PARENTREF_ABSENT;
659             if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
660                 // Child thinks it is pinned down, update its perspective
661                 stmt.markNoParentRef();
662             }
663         }
664     }
665
666     abstract void markNoParentRef();
667
668     static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
669         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
670             stmt.sweep();
671         }
672     }
673
674     /**
675      * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
676      */
677     private void sweep() {
678         parentRef = PARENTREF_ABSENT;
679         if (refcount == REFCOUNT_NONE && noImplictRef()) {
680             LOG.trace("Releasing {}", this);
681             sweepState();
682         }
683     }
684
685     static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
686         int result = 0;
687         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
688             if (stmt.refcount > REFCOUNT_NONE || !stmt.noImplictRef()) {
689                 result++;
690             }
691         }
692         return result;
693     }
694
695     /**
696      * Implementation-specific sweep action. This is expected to perform a recursive {@link #sweep(Collection)} on all
697      * {@link #declaredSubstatements()} and {@link #effectiveSubstatements()} and report the result of the sweep
698      * operation.
699      *
700      * <p>
701      * {@link #effectiveSubstatements()} as well as namespaces may become inoperable as a result of this operation.
702      *
703      * @return True if the entire tree has been completely swept, false otherwise.
704      */
705     abstract int sweepSubstatements();
706
707     // Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
708     private void sweepOnDecrement() {
709         LOG.trace("Sweeping on decrement {}", this);
710         if (noParentRef()) {
711             // No further parent references, sweep our state.
712             sweepState();
713         }
714
715         // Propagate towards parent if there is one
716         final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
717         if (parent != null) {
718             parent.sweepOnChildDecrement();
719         }
720     }
721
722     // Called from child when it has lost its final reference
723     private void sweepOnChildDecrement() {
724         if (isAwaitingChildren()) {
725             // We are a child for which our parent is waiting. Notify it and we are done.
726             sweepOnChildDone();
727             return;
728         }
729
730         // Check parent reference count
731         final int refs = refcount;
732         if (refs > REFCOUNT_NONE || refs <= REFCOUNT_SWEEPING || !noImplictRef()) {
733             // No-op
734             return;
735         }
736
737         // parent is potentially reclaimable
738         if (noParentRef()) {
739             LOG.trace("Cleanup {} of parent {}", refcount, this);
740             if (sweepState()) {
741                 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
742                 if (parent != null) {
743                     parent.sweepOnChildDecrement();
744                 }
745             }
746         }
747     }
748
749     private boolean noImplictRef() {
750         return effectiveInstance != null || !isSupportedToBuildEffective();
751     }
752
753     private boolean noParentRef() {
754         return parentRefcount() == PARENTREF_ABSENT;
755     }
756
757     private byte parentRefcount() {
758         final byte refs;
759         return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
760     }
761
762     private byte loadParentRefcount() {
763         return parentRef = calculateParentRefcount();
764     }
765
766     private byte calculateParentRefcount() {
767         final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
768         if (parent == null) {
769             return PARENTREF_ABSENT;
770         }
771         // There are three possibilities:
772         // - REFCOUNT_NONE, in which case we need to search next parent
773         // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
774         //   a reference to us
775         // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
776         final int refs = parent.refcount;
777         if (refs == REFCOUNT_NONE) {
778             return parent.parentRefcount();
779         }
780         return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
781     }
782
783     private boolean isAwaitingChildren() {
784         return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
785     }
786
787     private void sweepOnChildDone() {
788         LOG.trace("Sweeping on child done {}", this);
789         final int current = refcount;
790         if (current >= REFCOUNT_NONE) {
791             // no-op, perhaps we want to handle some cases differently?
792             LOG.trace("Ignoring child sweep of {} for {}", this, current);
793             return;
794         }
795         verify(current != REFCOUNT_SWEPT, "Attempt to sweep a child of swept %s", this);
796
797         refcount = current + 1;
798         LOG.trace("Child refcount {}", refcount);
799         if (refcount == REFCOUNT_NONE) {
800             sweepDone();
801             final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
802             LOG.trace("Propagating to parent {}", parent);
803             if (parent != null && parent.isAwaitingChildren()) {
804                 parent.sweepOnChildDone();
805             }
806         }
807     }
808
809     private void sweepDone() {
810         LOG.trace("Sweep done for {}", this);
811         refcount = REFCOUNT_SWEPT;
812         sweepNamespaces();
813     }
814
815     private boolean sweepState() {
816         refcount = REFCOUNT_SWEEPING;
817         final int childRefs = sweepSubstatements();
818         if (childRefs == 0) {
819             sweepDone();
820             return true;
821         }
822         if (childRefs < 0 || childRefs >= REFCOUNT_DEFUNCT) {
823             LOG.warn("Negative child refcount {} cannot be stored, reference counting disabled for {}", childRefs, this,
824                 new Throwable());
825             refcount = REFCOUNT_DEFUNCT;
826         } else {
827             LOG.trace("Still {} outstanding children of {}", childRefs, this);
828             refcount = -childRefs;
829         }
830         return false;
831     }
832 }