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