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