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