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