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