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