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