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