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