Add parent refcount cache
[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.YangVersion;
23 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
24 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
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.CommonStmtCtx;
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.MutableStatement;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
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     // Flag bit assignments
122     private static final int IS_SUPPORTED_BY_FEATURES    = 0x01;
123     private static final int HAVE_SUPPORTED_BY_FEATURES  = 0x02;
124     private static final int IS_IGNORE_IF_FEATURE        = 0x04;
125     private static final int HAVE_IGNORE_IF_FEATURE      = 0x08;
126     // Note: these four are related
127     private static final int IS_IGNORE_CONFIG            = 0x10;
128     private static final int HAVE_IGNORE_CONFIG          = 0x20;
129     private static final int IS_CONFIGURATION            = 0x40;
130     private static final int HAVE_CONFIGURATION          = 0x80;
131
132     // Have-and-set flag constants, also used as masks
133     private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
134     private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
135     // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
136     private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
137     private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
138
139     // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
140     // hence improve memory layout.
141     private byte flags;
142
143     // Flag for use with AbstractResumedStatement. This is hiding in the alignment shadow created by above boolean
144     // FIXME: move this out once we have JDK15+
145     private boolean fullyDefined;
146
147     // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
148     // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
149     @Deprecated
150     private volatile SchemaPath schemaPath;
151
152     ReactorStmtCtx() {
153         // Empty on purpose
154     }
155
156     ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
157         isSupportedToBuildEffective = original.isSupportedToBuildEffective;
158         fullyDefined = original.fullyDefined;
159         flags = original.flags;
160     }
161
162     //
163     //
164     // Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
165     // up mixing concerns and simple details with more complex logic.
166     //
167     //
168
169     @Override
170     public abstract StatementContextBase<?, ?, ?> getParentContext();
171
172     @Override
173     public abstract RootStatementContext<?, ?, ?> getRoot();
174
175     @Override
176     public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
177
178     @Override
179     public final @NonNull Registry getBehaviourRegistry() {
180         return getRoot().getBehaviourRegistryImpl();
181     }
182
183     @Override
184     public final YangVersion yangVersion() {
185         return getRoot().getRootVersionImpl();
186     }
187
188     @Override
189     public final void setRootVersion(final YangVersion version) {
190         getRoot().setRootVersionImpl(version);
191     }
192
193     @Override
194     public final void addMutableStmtToSeal(final MutableStatement mutableStatement) {
195         getRoot().addMutableStmtToSealImpl(mutableStatement);
196     }
197
198     @Override
199     public final void addRequiredSource(final SourceIdentifier dependency) {
200         getRoot().addRequiredSourceImpl(dependency);
201     }
202
203     @Override
204     public final void setRootIdentifier(final SourceIdentifier identifier) {
205         getRoot().setRootIdentifierImpl(identifier);
206     }
207
208     @Override
209     public final boolean isEnabledSemanticVersioning() {
210         return getRoot().isEnabledSemanticVersioningImpl();
211     }
212
213     @Override
214     public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
215         return getRoot().getSourceContext().newInferenceAction(phase);
216     }
217
218     @Override
219     public final StatementDefinition publicDefinition() {
220         return definition().getPublicView();
221     }
222
223     @Override
224     public final Parent effectiveParent() {
225         return getParentContext();
226     }
227
228     @Override
229     public final CommonStmtCtx root() {
230         return getRoot();
231     }
232
233     @Override
234     public final EffectiveStatement<?, ?> original() {
235         return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
236     }
237
238     @Override
239     @Deprecated
240     @SuppressWarnings("unchecked")
241     public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
242         return (StmtContext<A, D, Z>) this;
243     }
244
245     @Override
246     public final String toString() {
247         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
248     }
249
250     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
251         return toStringHelper.add("definition", definition()).add("rawArgument", rawArgument());
252     }
253
254     /**
255      * Return the context in which this statement was defined.
256      *
257      * @return statement definition
258      */
259     abstract @NonNull StatementDefinitionContext<A, D, E> definition();
260
261     //
262     //
263     // NamespaceStorageSupport/Mutable integration methods. Keep these together.
264     //
265     //
266
267     @Override
268     public final <K, V, T extends K, N extends IdentifierNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
269             final T key) {
270         return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
271     }
272
273     @Override
274     public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
275         return getNamespace(type);
276     }
277
278     @Override
279     public final <K, V, N extends IdentifierNamespace<K, V>> Map<K, V> localNamespace(final Class<@NonNull N> type) {
280         return getLocalNamespace(type);
281     }
282
283     @Override
284     protected final void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
285         definition().checkNamespaceAllowed(type);
286     }
287
288     @Override
289     protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
290             final V value) {
291         // definition().onNamespaceElementAdded(this, type, key, value);
292     }
293
294     //
295     //
296     // Statement build entry points -- both public and package-private.
297     //
298     //
299
300     @Override
301     public final E buildEffective() {
302         final E existing;
303         return (existing = effectiveInstance) != null ? existing : loadEffective();
304     }
305
306     private E loadEffective() {
307         // Creating an effective statement does not strictly require a declared instance -- there are statements like
308         // 'input', which are implicitly defined.
309         // Our implementation design makes an invariant assumption that buildDeclared() has been called by the time
310         // we attempt to create effective statement:
311         declared();
312
313         final E ret = effectiveInstance = createEffective();
314         // we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
315         // some residue.
316         if (refcount == REFCOUNT_NONE) {
317             sweepOnDecrement();
318         }
319         return ret;
320     }
321
322     abstract @NonNull E createEffective();
323
324     /**
325      * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
326      * this method does nothing.
327      *
328      * @param phase to be executed (completed)
329      * @return true if phase was successfully completed
330      * @throws SourceException when an error occurred in source parsing
331      */
332     final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
333         return phase.isCompletedBy(getCompletedPhase()) || doTryToCompletePhase(phase);
334     }
335
336     abstract boolean doTryToCompletePhase(ModelProcessingPhase phase);
337
338     //
339     //
340     // Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
341     // shadow.
342     //
343     //
344
345     @Override
346     public final boolean isSupportedToBuildEffective() {
347         return isSupportedToBuildEffective;
348     }
349
350     @Override
351     public final void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
352         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
353     }
354
355     @Override
356     public final boolean isSupportedByFeatures() {
357         final int fl = flags & SET_SUPPORTED_BY_FEATURES;
358         if (fl != 0) {
359             return fl == SET_SUPPORTED_BY_FEATURES;
360         }
361         if (isIgnoringIfFeatures()) {
362             flags |= SET_SUPPORTED_BY_FEATURES;
363             return true;
364         }
365
366         /*
367          * If parent is supported, we need to check if-features statements of this context.
368          */
369         if (isParentSupportedByFeatures()) {
370             // If the set of supported features has not been provided, all features are supported by default.
371             final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
372                     SupportedFeatures.SUPPORTED_FEATURES);
373             if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
374                 flags |= SET_SUPPORTED_BY_FEATURES;
375                 return true;
376             }
377         }
378
379         // Either parent is not supported or this statement is not supported
380         flags |= HAVE_SUPPORTED_BY_FEATURES;
381         return false;
382     }
383
384     protected abstract boolean isParentSupportedByFeatures();
385
386     /**
387      * Config statements are not all that common which means we are performing a recursive search towards the root
388      * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
389      * for the (usually non-existent) config statement.
390      *
391      * <p>
392      * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
393      * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
394      *
395      * <p>
396      * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
397      *       {@link #isIgnoringConfig(StatementContextBase)}.
398      */
399     final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
400         final int fl = flags & SET_CONFIGURATION;
401         if (fl != 0) {
402             return fl == SET_CONFIGURATION;
403         }
404         if (isIgnoringConfig(parent)) {
405             // Note: SET_CONFIGURATION has been stored in flags
406             return true;
407         }
408
409         final boolean isConfig;
410         final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
411         if (optConfig.isPresent()) {
412             isConfig = optConfig.orElseThrow();
413             if (isConfig) {
414                 // Validity check: if parent is config=false this cannot be a config=true
415                 InferenceException.throwIf(!parent.effectiveConfig(), this,
416                     "Parent node has config=false, this node must not be specifed as config=true");
417             }
418         } else {
419             // If "config" statement is not specified, the default is the same as the parent's "config" value.
420             isConfig = parent.effectiveConfig();
421         }
422
423         // Resolved, make sure we cache this return
424         flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
425         return isConfig;
426     }
427
428     protected abstract boolean isIgnoringConfig();
429
430     /**
431      * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
432      * keep on returning the same result without performing any lookups. Exists only to support
433      * {@link SubstatementContext#isIgnoringConfig()}.
434      *
435      * <p>
436      * Note: use of this method implies that {@link #isConfiguration()} is realized with
437      *       {@link #isConfiguration(StatementContextBase)}.
438      */
439     final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
440         final int fl = flags & SET_IGNORE_CONFIG;
441         if (fl != 0) {
442             return fl == SET_IGNORE_CONFIG;
443         }
444         if (definition().support().isIgnoringConfig() || parent.isIgnoringConfig()) {
445             flags |= SET_IGNORE_CONFIG;
446             return true;
447         }
448
449         flags |= HAVE_IGNORE_CONFIG;
450         return false;
451     }
452
453     protected abstract boolean isIgnoringIfFeatures();
454
455     /**
456      * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
457      * keep on returning the same result without performing any lookups. Exists only to support
458      * {@link SubstatementContext#isIgnoringIfFeatures()}.
459      */
460     final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
461         final int fl = flags & SET_IGNORE_IF_FEATURE;
462         if (fl != 0) {
463             return fl == SET_IGNORE_IF_FEATURE;
464         }
465         if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
466             flags |= SET_IGNORE_IF_FEATURE;
467             return true;
468         }
469
470         flags |= HAVE_IGNORE_IF_FEATURE;
471         return false;
472     }
473
474     // These two exists only due to memory optimization, should live in AbstractResumedStatement. We are also reusing
475     // this for ReplicaStatementContext's refcount tracking.
476     final boolean fullyDefined() {
477         return fullyDefined;
478     }
479
480     final void setFullyDefined() {
481         fullyDefined = true;
482     }
483
484     //
485     //
486     // Common SchemaPath cache. All of this is bound to be removed once YANGTOOLS-1066 is done.
487     //
488     //
489
490     // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
491     @Deprecated
492     final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
493         SchemaPath local = schemaPath;
494         if (local == null) {
495             synchronized (this) {
496                 local = schemaPath;
497                 if (local == null) {
498                     schemaPath = local = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
499                 }
500             }
501         }
502
503         return Optional.ofNullable(local);
504     }
505
506     @Deprecated
507     private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
508         final Optional<SchemaPath> maybeParentPath = parent.schemaPath();
509         verify(maybeParentPath.isPresent(), "Parent %s does not have a SchemaPath", parent);
510         final SchemaPath parentPath = maybeParentPath.get();
511
512         if (StmtContextUtils.isUnknownStatement(this)) {
513             return parentPath.createChild(publicDefinition().getStatementName());
514         }
515         final Object argument = argument();
516         if (argument instanceof QName) {
517             final QName qname = (QName) argument;
518             if (producesDeclared(UsesStatement.class)) {
519                 return maybeParentPath.orElse(null);
520             }
521
522             return parentPath.createChild(qname);
523         }
524         if (argument instanceof String) {
525             // FIXME: This may yield illegal argument exceptions
526             final Optional<StmtContext<A, D, E>> originalCtx = getOriginalCtx();
527             final QName qname = StmtContextUtils.qnameFromArgument(originalCtx.orElse(this), (String) argument);
528             return parentPath.createChild(qname);
529         }
530         if (argument instanceof SchemaNodeIdentifier
531                 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
532                         || producesDeclared(DeviationStatement.class))) {
533
534             return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
535         }
536
537         // FIXME: this does not look right
538         return maybeParentPath.orElse(null);
539     }
540
541     //
542     //
543     // Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
544     // contribute to state visible outside of this package.
545     //
546     //
547
548     /**
549      * Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
550      * in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
551      * knowledge and update it when {@link #sweep()} is invoked.
552      */
553     private byte parentRef = PARENTREF_UNKNOWN;
554     private static final byte PARENTREF_UNKNOWN = -1;
555     private static final byte PARENTREF_ABSENT  = 0;
556     private static final byte PARENTREF_PRESENT = 1;
557
558     /**
559      * Acquire a reference on this context. As long as there is at least one reference outstanding,
560      * {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
561      *
562      * @throws VerifyException if {@link #effectiveSubstatements()} has already been discarded
563      */
564     final void incRef() {
565         final int current = refcount;
566         verify(current >= REFCOUNT_NONE, "Attempted to access reference count of %s", this);
567         if (current != REFCOUNT_DEFUNCT) {
568             // Note: can end up becoming REFCOUNT_DEFUNCT on overflow
569             refcount = current + 1;
570         } else {
571             LOG.debug("Disabled refcount increment of {}", this);
572         }
573     }
574
575     /**
576      * Release a reference on this context. This call may result in {@link #effectiveSubstatements()} becoming
577      * unavailable.
578      */
579     final void decRef() {
580         final int current = refcount;
581         if (current == REFCOUNT_DEFUNCT) {
582             // no-op
583             LOG.debug("Disabled refcount decrement of {}", this);
584             return;
585         }
586         if (current <= REFCOUNT_NONE) {
587             // Underflow, become defunct
588             LOG.warn("Statement refcount underflow, reference counting disabled for {}", this, new Throwable());
589             refcount = REFCOUNT_DEFUNCT;
590             return;
591         }
592
593         refcount = current - 1;
594         LOG.trace("Refcount {} on {}", refcount, this);
595
596         if (refcount == REFCOUNT_NONE) {
597             lastDecRef();
598         }
599     }
600
601     private void lastDecRef() {
602         if (noImplictRef()) {
603             // We are no longer guarded by effective instance
604             sweepOnDecrement();
605             return;
606         }
607
608         final byte prevRefs = parentRef;
609         if (prevRefs == PARENTREF_ABSENT) {
610             // We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
611             // updated
612             markNoParentRef();
613         } else if (prevRefs == PARENTREF_UNKNOWN) {
614             // Noone observed our parentRef, just update it
615             loadParentRefcount();
616         }
617     }
618
619     static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
620         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
621             final byte prevRef = stmt.parentRef;
622             stmt.parentRef = PARENTREF_ABSENT;
623             if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
624                 // Child thinks it is pinned down, update its perspective
625                 stmt.markNoParentRef();
626             }
627         }
628     }
629
630     abstract void markNoParentRef();
631
632     static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
633         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
634             stmt.sweep();
635         }
636     }
637
638     /**
639      * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
640      */
641     private void sweep() {
642         parentRef = PARENTREF_ABSENT;
643         if (refcount == REFCOUNT_NONE && noImplictRef()) {
644             LOG.trace("Releasing {}", this);
645             sweepState();
646         }
647     }
648
649     static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
650         int result = 0;
651         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
652             if (stmt.refcount > REFCOUNT_NONE || !stmt.noImplictRef()) {
653                 result++;
654             }
655         }
656         return result;
657     }
658
659     /**
660      * Implementation-specific sweep action. This is expected to perform a recursive {@link #sweep(Collection)} on all
661      * {@link #declaredSubstatements()} and {@link #effectiveSubstatements()} and report the result of the sweep
662      * operation.
663      *
664      * <p>
665      * {@link #effectiveSubstatements()} as well as namespaces may become inoperable as a result of this operation.
666      *
667      * @return True if the entire tree has been completely swept, false otherwise.
668      */
669     abstract int sweepSubstatements();
670
671     // Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
672     private void sweepOnDecrement() {
673         LOG.trace("Sweeping on decrement {}", this);
674         if (noParentRef()) {
675             // No further parent references, sweep our state.
676             sweepState();
677         }
678
679         // Propagate towards parent if there is one
680         final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
681         if (parent != null) {
682             parent.sweepOnChildDecrement();
683         }
684     }
685
686     // Called from child when it has lost its final reference
687     private void sweepOnChildDecrement() {
688         if (isAwaitingChildren()) {
689             // We are a child for which our parent is waiting. Notify it and we are done.
690             sweepOnChildDone();
691             return;
692         }
693
694         // Check parent reference count
695         final int refs = refcount;
696         if (refs > REFCOUNT_NONE || refs <= REFCOUNT_SWEEPING || !noImplictRef()) {
697             // No-op
698             return;
699         }
700
701         // parent is potentially reclaimable
702         if (noParentRef()) {
703             LOG.trace("Cleanup {} of parent {}", refcount, this);
704             if (sweepState()) {
705                 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
706                 if (parent != null) {
707                     parent.sweepOnChildDecrement();
708                 }
709             }
710         }
711     }
712
713     private boolean noImplictRef() {
714         return effectiveInstance != null || !isSupportedToBuildEffective();
715     }
716
717     private boolean noParentRef() {
718         return parentRefcount() == PARENTREF_ABSENT;
719     }
720
721     private byte parentRefcount() {
722         final byte refs;
723         return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
724     }
725
726     private byte loadParentRefcount() {
727         return parentRef = calculateParentRefcount();
728     }
729
730     private byte calculateParentRefcount() {
731         final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
732         if (parent == null) {
733             return PARENTREF_ABSENT;
734         }
735         // There are three possibilities:
736         // - REFCOUNT_NONE, in which case we need to search next parent
737         // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
738         //   a reference to us
739         // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
740         final int refs = parent.refcount;
741         if (refs == REFCOUNT_NONE) {
742             return parent.parentRefcount();
743         }
744         return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
745     }
746
747     private boolean isAwaitingChildren() {
748         return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
749     }
750
751     private void sweepOnChildDone() {
752         LOG.trace("Sweeping on child done {}", this);
753         final int current = refcount;
754         if (current >= REFCOUNT_NONE) {
755             // no-op, perhaps we want to handle some cases differently?
756             LOG.trace("Ignoring child sweep of {} for {}", this, current);
757             return;
758         }
759         verify(current != REFCOUNT_SWEPT, "Attempt to sweep a child of swept %s", this);
760
761         refcount = current + 1;
762         LOG.trace("Child refcount {}", refcount);
763         if (refcount == REFCOUNT_NONE) {
764             sweepDone();
765             final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
766             LOG.trace("Propagating to parent {}", parent);
767             if (parent != null && parent.isAwaitingChildren()) {
768                 parent.sweepOnChildDone();
769             }
770         }
771     }
772
773     private void sweepDone() {
774         LOG.trace("Sweep done for {}", this);
775         refcount = REFCOUNT_SWEPT;
776         sweepNamespaces();
777     }
778
779     private boolean sweepState() {
780         refcount = REFCOUNT_SWEEPING;
781         final int childRefs = sweepSubstatements();
782         if (childRefs == 0) {
783             sweepDone();
784             return true;
785         }
786         if (childRefs < 0 || childRefs >= REFCOUNT_DEFUNCT) {
787             LOG.warn("Negative child refcount {} cannot be stored, reference counting disabled for {}", childRefs, this,
788                 new Throwable());
789             refcount = REFCOUNT_DEFUNCT;
790         } else {
791             LOG.trace("Still {} outstanding children of {}", childRefs, this);
792             refcount = -childRefs;
793         }
794         return false;
795     }
796 }