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