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