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