Add derived statement cache
[yangtools.git] / yang / 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 import static com.google.common.base.Verify.verifyNotNull;
13
14 import com.google.common.base.MoreObjects;
15 import com.google.common.base.MoreObjects.ToStringHelper;
16 import com.google.common.base.VerifyException;
17 import java.util.Collection;
18 import java.util.Map;
19 import java.util.Optional;
20 import java.util.Set;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.eclipse.jdt.annotation.Nullable;
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.SchemaPath;
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.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.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
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     // SchemaPath cache for use with SubstatementContext and InferredStatementContext. This hurts RootStatementContext
165     // a bit in terms of size -- but those are only a few and SchemaPath is on its way out anyway.
166     // FIXME: this should become 'QName'
167     private SchemaPath schemaPath;
168
169     ReactorStmtCtx() {
170         // Empty on purpose
171     }
172
173     ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
174         isSupportedToBuildEffective = original.isSupportedToBuildEffective;
175         boolFlag = original.boolFlag;
176         flags = original.flags;
177     }
178
179     // Used by ReplicaStatementContext only
180     ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original, final Void dummy) {
181         boolFlag = isSupportedToBuildEffective = original.isSupportedToBuildEffective;
182         flags = original.flags;
183     }
184
185     //
186     //
187     // Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
188     // up mixing concerns and simple details with more complex logic.
189     //
190     //
191
192     @Override
193     public abstract StatementContextBase<?, ?, ?> getParentContext();
194
195     @Override
196     public abstract RootStatementContext<?, ?, ?> getRoot();
197
198     @Override
199     public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
200
201     @Override
202     public final @NonNull Registry getBehaviourRegistry() {
203         return getRoot().getBehaviourRegistryImpl();
204     }
205
206     @Override
207     public final YangVersion yangVersion() {
208         return getRoot().getRootVersionImpl();
209     }
210
211     @Override
212     public final void setRootVersion(final YangVersion version) {
213         getRoot().setRootVersionImpl(version);
214     }
215
216     @Override
217     public final void addRequiredSource(final SourceIdentifier dependency) {
218         getRoot().addRequiredSourceImpl(dependency);
219     }
220
221     @Override
222     public final void setRootIdentifier(final SourceIdentifier identifier) {
223         getRoot().setRootIdentifierImpl(identifier);
224     }
225
226     @Override
227     public final boolean isEnabledSemanticVersioning() {
228         return getRoot().isEnabledSemanticVersioningImpl();
229     }
230
231     @Override
232     public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
233         return getRoot().getSourceContext().newInferenceAction(phase);
234     }
235
236     @Override
237     public final StatementDefinition publicDefinition() {
238         return definition().getPublicView();
239     }
240
241     @Override
242     public final Parent effectiveParent() {
243         return getParentContext();
244     }
245
246     @Override
247     public final QName moduleName() {
248         final RootStatementContext<?, ?, ?> root = getRoot();
249         return QName.create(StmtContextUtils.getRootModuleQName(root), root.getRawArgument());
250     }
251
252     @Override
253     public final EffectiveStatement<?, ?> original() {
254         return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
255     }
256
257     //
258     // In the next two methods we are looking for an effective statement. If we already have an effective instance,
259     // defer to it's implementation of the equivalent search. Otherwise we search our substatement contexts.
260     //
261     // Note that the search function is split, so as to allow InferredStatementContext to do its own thing first.
262     //
263
264     @Override
265     public final <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
266             final @NonNull Class<Z> type) {
267         final Object existing = effectiveInstance;
268         return existing != null ? EffectiveInstances.local(existing).findFirstEffectiveSubstatementArgument(type)
269             : findSubstatementArgumentImpl(type);
270     }
271
272     @Override
273     public final boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
274         final Object existing = effectiveInstance;
275         return existing != null ? EffectiveInstances.local(existing).findFirstEffectiveSubstatement(type).isPresent()
276             : hasSubstatementImpl(type);
277     }
278
279     // Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
280     <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
281             final @NonNull Class<Z> type) {
282         return allSubstatementsStream()
283             .filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
284             .findAny()
285             .map(ctx -> (X) ctx.getArgument());
286     }
287
288     // Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
289     boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
290         return allSubstatementsStream()
291             .anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
292     }
293
294     @Override
295     @Deprecated
296     @SuppressWarnings("unchecked")
297     public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
298         return (StmtContext<A, D, Z>) this;
299     }
300
301     @Override
302     public final String toString() {
303         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
304     }
305
306     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
307         return toStringHelper.add("definition", definition()).add("rawArgument", rawArgument());
308     }
309
310     /**
311      * Return the context in which this statement was defined.
312      *
313      * @return statement definition
314      */
315     abstract @NonNull StatementDefinitionContext<A, D, E> definition();
316
317     //
318     //
319     // NamespaceStorageSupport/Mutable integration methods. Keep these together.
320     //
321     //
322
323     @Override
324     public final <K, V, T extends K, N extends ParserNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
325             final T key) {
326         return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
327     }
328
329     @Override
330     public final <K, V, N extends ParserNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
331         return getNamespace(type);
332     }
333
334     @Override
335     public final <K, V, N extends ParserNamespace<K, V>>
336             Map<K, V> localNamespacePortion(final Class<@NonNull N> type) {
337         return getLocalNamespace(type);
338     }
339
340     @Override
341     protected final void checkLocalNamespaceAllowed(final Class<? extends ParserNamespace<?, ?>> type) {
342         definition().checkNamespaceAllowed(type);
343     }
344
345     @Override
346     protected <K, V, N extends ParserNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
347             final V value) {
348         // definition().onNamespaceElementAdded(this, type, key, value);
349     }
350
351     /**
352      * Return the effective statement view of a copy operation. This method may return one of:
353      * <ul>
354      *   <li>{@code this}, when the effective view did not change</li>
355      *   <li>an InferredStatementContext, when there is a need for inference-equivalent copy</li>
356      *   <li>{@code null}, when the statement failed to materialize</li>
357      * </ul>
358      *
359      * @param parent Proposed new parent
360      * @param type Copy operation type
361      * @param targetModule New target module
362      * @return {@link ReactorStmtCtx} holding effective view
363      */
364     abstract @Nullable ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(StatementContextBase<?, ?, ?> parent, CopyType type,
365         QNameModule targetModule);
366
367     @Override
368     public final ReactorStmtCtx<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
369         checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
370         return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
371     }
372
373     abstract @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(@NonNull StatementContextBase<?, ?, ?> parent);
374
375     //
376     //
377     // Statement build entry points -- both public and package-private.
378     //
379     //
380
381     @Override
382     public final E buildEffective() {
383         final Object existing;
384         return (existing = effectiveInstance) != null ? EffectiveInstances.local(existing) : loadEffective();
385     }
386
387     private @NonNull E loadEffective() {
388         // Creating an effective statement does not strictly require a declared instance -- there are statements like
389         // 'input', which are implicitly defined.
390         // Our implementation design makes an invariant assumption that buildDeclared() has been called by the time
391         // we attempt to create effective statement:
392         declared();
393
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     /**
408      * Attach an effective copy of this statement. This essentially acts as a map, where we make a few assumptions:
409      * <ul>
410      *   <li>{@code copy} and {@code this} statement share {@link #getOriginalCtx()} if it exists</li>
411      *   <li>{@code copy} did not modify any statements relative to {@code this}</li>
412      * </ul>
413      *
414      *
415      * @param state effective statement state, acting as a lookup key
416      * @param copy New copy to append
417      * @return {@code copy} or a previously-created instances with the same {@code state}
418      */
419     @SuppressWarnings("unchecked")
420     final @NonNull E attachCopy(final @NonNull EffectiveStatementState state, final @NonNull E copy) {
421         final Object effective = verifyNotNull(effectiveInstance, "Attaching copy to a unbuilt %s", this);
422         final EffectiveInstances<E> instances;
423         if (effective instanceof EffectiveInstances) {
424             instances = (EffectiveInstances<E>) effective;
425         } else {
426             effectiveInstance = instances = new EffectiveInstances<>((E) effective);
427         }
428         return instances.attachCopy(state, copy);
429     }
430
431     /**
432      * Walk this statement's copy history and return the statement closest to original which has not had its effective
433      * statements modified. This statement and returned substatement logically have the same set of substatements, hence
434      * share substatement-derived state.
435      *
436      * @return Closest {@link ReactorStmtCtx} with equivalent effective substatements
437      */
438     abstract @NonNull ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource();
439
440     /**
441      * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
442      * this method does nothing.
443      *
444      * @param phase to be executed (completed)
445      * @return true if phase was successfully completed
446      * @throws SourceException when an error occurred in source parsing
447      */
448     final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
449         return phase.isCompletedBy(getCompletedPhase()) || doTryToCompletePhase(phase);
450     }
451
452     abstract boolean doTryToCompletePhase(ModelProcessingPhase phase);
453
454     //
455     //
456     // Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
457     // shadow.
458     //
459     //
460
461     @Override
462     public final boolean isSupportedToBuildEffective() {
463         return isSupportedToBuildEffective;
464     }
465
466     @Override
467     public final void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
468         this.isSupportedToBuildEffective = isSupportedToBuildEffective;
469     }
470
471     @Override
472     public final boolean isSupportedByFeatures() {
473         final int fl = flags & SET_SUPPORTED_BY_FEATURES;
474         if (fl != 0) {
475             return fl == SET_SUPPORTED_BY_FEATURES;
476         }
477         if (isIgnoringIfFeatures()) {
478             flags |= SET_SUPPORTED_BY_FEATURES;
479             return true;
480         }
481
482         /*
483          * If parent is supported, we need to check if-features statements of this context.
484          */
485         if (isParentSupportedByFeatures()) {
486             // If the set of supported features has not been provided, all features are supported by default.
487             final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
488                     SupportedFeatures.SUPPORTED_FEATURES);
489             if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
490                 flags |= SET_SUPPORTED_BY_FEATURES;
491                 return true;
492             }
493         }
494
495         // Either parent is not supported or this statement is not supported
496         flags |= HAVE_SUPPORTED_BY_FEATURES;
497         return false;
498     }
499
500     protected abstract boolean isParentSupportedByFeatures();
501
502     /**
503      * Config statements are not all that common which means we are performing a recursive search towards the root
504      * every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
505      * for the (usually non-existent) config statement.
506      *
507      * <p>
508      * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
509      * result without performing any lookups, solely to support {@link #effectiveConfig()}.
510      *
511      * <p>
512      * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
513      *       {@link #isIgnoringConfig(StatementContextBase)}.
514      */
515     final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
516         return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
517     }
518
519     private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
520         final EffectiveConfig parentConfig = parent.effectiveConfig();
521
522         final EffectiveConfig myConfig;
523         if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
524             final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
525             if (optConfig.isPresent()) {
526                 if (optConfig.orElseThrow()) {
527                     // Validity check: if parent is config=false this cannot be a config=true
528                     InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
529                         "Parent node has config=false, this node must not be specifed as config=true");
530                     myConfig = EffectiveConfig.TRUE;
531                 } else {
532                     myConfig = EffectiveConfig.FALSE;
533                 }
534             } else {
535                 // If "config" statement is not specified, the default is the same as the parent's "config" value.
536                 myConfig = parentConfig;
537             }
538         } else {
539             myConfig = EffectiveConfig.IGNORED;
540         }
541
542         flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
543         return myConfig;
544     }
545
546     protected abstract boolean isIgnoringConfig();
547
548     /**
549      * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
550      * keep on returning the same result without performing any lookups. Exists only to support
551      * {@link SubstatementContext#isIgnoringConfig()}.
552      *
553      * <p>
554      * Note: use of this method implies that {@link #isConfiguration()} is realized with
555      *       {@link #effectiveConfig(StatementContextBase)}.
556      */
557     final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
558         return EffectiveConfig.IGNORED == effectiveConfig(parent);
559     }
560
561     protected abstract boolean isIgnoringIfFeatures();
562
563     /**
564      * This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
565      * keep on returning the same result without performing any lookups. Exists only to support
566      * {@link SubstatementContext#isIgnoringIfFeatures()}.
567      */
568     final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
569         final int fl = flags & SET_IGNORE_IF_FEATURE;
570         if (fl != 0) {
571             return fl == SET_IGNORE_IF_FEATURE;
572         }
573         if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
574             flags |= SET_IGNORE_IF_FEATURE;
575             return true;
576         }
577
578         flags |= HAVE_IGNORE_IF_FEATURE;
579         return false;
580     }
581
582     // These two exist only due to memory optimization, should live in AbstractResumedStatement.
583     final boolean fullyDefined() {
584         return boolFlag;
585     }
586
587     final void setFullyDefined() {
588         boolFlag = true;
589     }
590
591     // This exists only due to memory optimization, should live in ReplicaStatementContext. In this context the flag
592     // indicates the need to drop source's reference count when we are being swept.
593     final boolean haveSourceReference() {
594         return boolFlag;
595     }
596
597     // These three exist due to memory optimization, should live in InferredStatementContext. In this context the flag
598     // indicates whether or not this statement's substatement file was modified, i.e. it is not quite the same as the
599     // prototype's file.
600     final boolean isModified() {
601         return boolFlag;
602     }
603
604     final void setModified() {
605         boolFlag = true;
606     }
607
608     final void setUnmodified() {
609         boolFlag = false;
610     }
611
612     // These two exist only for StatementContextBase. Since we are squeezed for size, with only a single bit available
613     // in flags, we default to 'false' and only set the flag to true when we are absolutely sure -- and all other cases
614     // err on the side of caution by taking the time to evaluate each substatement separately.
615     final boolean allSubstatementsContextIndependent() {
616         return (flags & ALL_INDEPENDENT) != 0;
617     }
618
619     final void setAllSubstatementsContextIndependent() {
620         flags |= ALL_INDEPENDENT;
621     }
622
623     //
624     //
625     // Various functionality from AbstractTypeStatementSupport. This used to work on top of SchemaPath, now it still
626     // lives here. Ultimate future is either proper graduation or (more likely) move to AbstractTypeStatementSupport.
627     //
628     //
629
630     @Override
631     public final QName argumentAsTypeQName() {
632         final Object argument = argument();
633         verify(argument instanceof String, "Unexpected argument %s", argument);
634         return interpretAsQName((String) argument);
635     }
636
637     @Override
638     public final QNameModule effectiveNamespace() {
639         // FIXME: there has to be a better way to do this
640         return getSchemaPath().getLastComponent().getModule();
641     }
642
643     //
644     //
645     // Common SchemaPath cache. All of this is bound to be removed once YANGTOOLS-1066 is done.
646     //
647     //
648
649     // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
650     @Deprecated
651     final @Nullable SchemaPath substatementGetSchemaPath() {
652         if (schemaPath == null) {
653             schemaPath = createSchemaPath((StatementContextBase<?, ?, ?>) coerceParentContext());
654         }
655         return schemaPath;
656     }
657
658     // FIXME: 7.0.0: this method's logic needs to be moved to the respective StatementSupport classes
659     @Deprecated
660     private SchemaPath createSchemaPath(final StatementContextBase<?, ?, ?> parent) {
661         final SchemaPath parentPath = parent.getSchemaPath();
662         if (StmtContextUtils.isUnknownStatement(this)) {
663             return parentPath.createChild(publicDefinition().getStatementName());
664         }
665         final Object argument = argument();
666         if (argument instanceof QName) {
667             final QName qname = (QName) argument;
668             if (producesDeclared(UsesStatement.class)) {
669                 return parentPath;
670             }
671
672             return parentPath.createChild(qname);
673         }
674         if (argument instanceof String) {
675             return parentPath.createChild(interpretAsQName((String) argument));
676         }
677         if (argument instanceof SchemaNodeIdentifier
678                 && (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
679                         || producesDeclared(DeviationStatement.class))) {
680
681             return parentPath.createChild(((SchemaNodeIdentifier) argument).getNodeIdentifiers());
682         }
683
684         // FIXME: this does not look right, investigate more?
685         return parentPath;
686     }
687
688     private @NonNull QName interpretAsQName(final String argument) {
689         // FIXME: This may yield illegal argument exceptions
690         return StmtContextUtils.qnameFromArgument(getOriginalCtx().orElse(this), argument);
691     }
692
693     //
694     //
695     // Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
696     // contribute to state visible outside of this package.
697     //
698     //
699
700     /**
701      * Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
702      * in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
703      * knowledge and update it when {@link #sweep()} is invoked.
704      */
705     private byte parentRef = PARENTREF_UNKNOWN;
706     private static final byte PARENTREF_UNKNOWN = -1;
707     private static final byte PARENTREF_ABSENT  = 0;
708     private static final byte PARENTREF_PRESENT = 1;
709
710     /**
711      * Acquire a reference on this context. As long as there is at least one reference outstanding,
712      * {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
713      *
714      * @throws VerifyException if {@link #effectiveSubstatements()} has already been discarded
715      */
716     final void incRef() {
717         final int current = refcount;
718         verify(current >= REFCOUNT_NONE, "Attempted to access reference count of %s", this);
719         if (current != REFCOUNT_DEFUNCT) {
720             // Note: can end up becoming REFCOUNT_DEFUNCT on overflow
721             refcount = current + 1;
722         } else {
723             LOG.debug("Disabled refcount increment of {}", this);
724         }
725     }
726
727     /**
728      * Release a reference on this context. This call may result in {@link #effectiveSubstatements()} becoming
729      * unavailable.
730      */
731     final void decRef() {
732         final int current = refcount;
733         if (current == REFCOUNT_DEFUNCT) {
734             // no-op
735             LOG.debug("Disabled refcount decrement of {}", this);
736             return;
737         }
738         if (current <= REFCOUNT_NONE) {
739             // Underflow, become defunct
740             // FIXME: add a global 'warn once' flag
741             LOG.warn("Statement refcount underflow, reference counting disabled for {}", this, new Throwable());
742             refcount = REFCOUNT_DEFUNCT;
743             return;
744         }
745
746         refcount = current - 1;
747         LOG.trace("Refcount {} on {}", refcount, this);
748
749         if (refcount == REFCOUNT_NONE) {
750             lastDecRef();
751         }
752     }
753
754     /**
755      * Return {@code true} if this context has no outstanding references.
756      *
757      * @return True if this context has no outstanding references.
758      */
759     final boolean noRefs() {
760         final int local = refcount;
761         return local < REFCOUNT_NONE || local == REFCOUNT_NONE && noParentRef();
762     }
763
764     private void lastDecRef() {
765         if (noImplictRef()) {
766             // We are no longer guarded by effective instance
767             sweepOnDecrement();
768             return;
769         }
770
771         final byte prevRefs = parentRef;
772         if (prevRefs == PARENTREF_ABSENT) {
773             // We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
774             // updated
775             markNoParentRef();
776         } else if (prevRefs == PARENTREF_UNKNOWN) {
777             // Noone observed our parentRef, just update it
778             loadParentRefcount();
779         }
780     }
781
782     static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
783         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
784             final byte prevRef = stmt.parentRef;
785             stmt.parentRef = PARENTREF_ABSENT;
786             if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
787                 // Child thinks it is pinned down, update its perspective
788                 stmt.markNoParentRef();
789             }
790         }
791     }
792
793     abstract void markNoParentRef();
794
795     static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
796         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
797             stmt.sweep();
798         }
799     }
800
801     /**
802      * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
803      */
804     private void sweep() {
805         parentRef = PARENTREF_ABSENT;
806         if (refcount == REFCOUNT_NONE && noImplictRef()) {
807             LOG.trace("Releasing {}", this);
808             sweepState();
809         }
810     }
811
812     static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
813         int result = 0;
814         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
815             if (stmt.refcount > REFCOUNT_NONE || !stmt.noImplictRef()) {
816                 result++;
817             }
818         }
819         return result;
820     }
821
822     /**
823      * Implementation-specific sweep action. This is expected to perform a recursive {@link #sweep(Collection)} on all
824      * {@link #declaredSubstatements()} and {@link #effectiveSubstatements()} and report the result of the sweep
825      * operation.
826      *
827      * <p>
828      * {@link #effectiveSubstatements()} as well as namespaces may become inoperable as a result of this operation.
829      *
830      * @return True if the entire tree has been completely swept, false otherwise.
831      */
832     abstract int sweepSubstatements();
833
834     // Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
835     private void sweepOnDecrement() {
836         LOG.trace("Sweeping on decrement {}", this);
837         if (noParentRef()) {
838             // No further parent references, sweep our state.
839             sweepState();
840         }
841
842         // Propagate towards parent if there is one
843         final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
844         if (parent != null) {
845             parent.sweepOnChildDecrement();
846         }
847     }
848
849     // Called from child when it has lost its final reference
850     private void sweepOnChildDecrement() {
851         if (isAwaitingChildren()) {
852             // We are a child for which our parent is waiting. Notify it and we are done.
853             sweepOnChildDone();
854             return;
855         }
856
857         // Check parent reference count
858         final int refs = refcount;
859         if (refs > REFCOUNT_NONE || refs <= REFCOUNT_SWEEPING || !noImplictRef()) {
860             // No-op
861             return;
862         }
863
864         // parent is potentially reclaimable
865         if (noParentRef()) {
866             LOG.trace("Cleanup {} of parent {}", refcount, this);
867             if (sweepState()) {
868                 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
869                 if (parent != null) {
870                     parent.sweepOnChildDecrement();
871                 }
872             }
873         }
874     }
875
876     private boolean noImplictRef() {
877         return effectiveInstance != null || !isSupportedToBuildEffective();
878     }
879
880     private boolean noParentRef() {
881         return parentRefcount() == PARENTREF_ABSENT;
882     }
883
884     private byte parentRefcount() {
885         final byte refs;
886         return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
887     }
888
889     private byte loadParentRefcount() {
890         return parentRef = calculateParentRefcount();
891     }
892
893     private byte calculateParentRefcount() {
894         final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
895         if (parent == null) {
896             return PARENTREF_ABSENT;
897         }
898         // There are three possibilities:
899         // - REFCOUNT_NONE, in which case we need to search next parent
900         // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
901         //   a reference to us
902         // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
903         final int refs = parent.refcount;
904         if (refs == REFCOUNT_NONE) {
905             return parent.parentRefcount();
906         }
907         return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
908     }
909
910     private boolean isAwaitingChildren() {
911         return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
912     }
913
914     private void sweepOnChildDone() {
915         LOG.trace("Sweeping on child done {}", this);
916         final int current = refcount;
917         if (current >= REFCOUNT_NONE) {
918             // no-op, perhaps we want to handle some cases differently?
919             LOG.trace("Ignoring child sweep of {} for {}", this, current);
920             return;
921         }
922         verify(current != REFCOUNT_SWEPT, "Attempt to sweep a child of swept %s", this);
923
924         refcount = current + 1;
925         LOG.trace("Child refcount {}", refcount);
926         if (refcount == REFCOUNT_NONE) {
927             sweepDone();
928             final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
929             LOG.trace("Propagating to parent {}", parent);
930             if (parent != null && parent.isAwaitingChildren()) {
931                 parent.sweepOnChildDone();
932             }
933         }
934     }
935
936     private void sweepDone() {
937         LOG.trace("Sweep done for {}", this);
938         refcount = REFCOUNT_SWEPT;
939         sweepNamespaces();
940     }
941
942     private boolean sweepState() {
943         refcount = REFCOUNT_SWEEPING;
944         final int childRefs = sweepSubstatements();
945         if (childRefs == 0) {
946             sweepDone();
947             return true;
948         }
949         if (childRefs < 0 || childRefs >= REFCOUNT_DEFUNCT) {
950             // FIXME: add a global 'warn once' flag
951             LOG.warn("Negative child refcount {} cannot be stored, reference counting disabled for {}", childRefs, this,
952                 new Throwable());
953             refcount = REFCOUNT_DEFUNCT;
954         } else {
955             LOG.trace("Still {} outstanding children of {}", childRefs, this);
956             refcount = -childRefs;
957         }
958         return false;
959     }
960 }