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