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