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