Move findSubstatementArgument()/hasSubstatement() to BoundStmtCtx
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / ReactorStmtCtx.java
index 1f4ba0355af8413940a69d862db369f4dd40e0ac..e51579b703b4743ed8036911c9f32d62e5f9f810 100644 (file)
@@ -32,6 +32,8 @@ import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
+import org.opendaylight.yangtools.yang.parser.spi.meta.CommonStmtCtx;
+import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
@@ -40,6 +42,7 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Regist
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
+import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
 import org.slf4j.Logger;
@@ -53,13 +56,13 @@ import org.slf4j.LoggerFactory;
  * @param <E> Effective Statement representation
  */
 abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
-        extends NamespaceStorageSupport implements Mutable<A, D, E> {
+        extends NamespaceStorageSupport implements Mutable<A, D, E>, Current<A, D> {
     private static final Logger LOG = LoggerFactory.getLogger(ReactorStmtCtx.class);
 
     /**
      * Substatement refcount tracking. This mechanics deals with retaining substatements for the purposes of
      * instantiating their lazy copies in InferredStatementContext. It works in concert with {@link #buildEffective()}
-     * and {@link #buildDeclared()}: declared/effective statement views hold an implicit reference and refcount-based
+     * and {@link #declared()}: declared/effective statement views hold an implicit reference and refcount-based
      * sweep is not activated until they are done (or this statement is not {@link #isSupportedToBuildEffective}).
      *
      * <p>
@@ -116,22 +119,25 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
     private boolean isSupportedToBuildEffective = true;
 
     // Flag bit assignments
-    private static final int IS_SUPPORTED_BY_FEATURES    = 0x01;
-    private static final int HAVE_SUPPORTED_BY_FEATURES  = 0x02;
-    private static final int IS_IGNORE_IF_FEATURE        = 0x04;
-    private static final int HAVE_IGNORE_IF_FEATURE      = 0x08;
-    // Note: these four are related
-    private static final int IS_IGNORE_CONFIG            = 0x10;
-    private static final int HAVE_IGNORE_CONFIG          = 0x20;
-    private static final int IS_CONFIGURATION            = 0x40;
-    private static final int HAVE_CONFIGURATION          = 0x80;
-
+    private static final int IS_SUPPORTED_BY_FEATURES   = 0x10;
+    private static final int HAVE_SUPPORTED_BY_FEATURES = 0x20;
+    private static final int IS_IGNORE_IF_FEATURE       = 0x40;
+    private static final int HAVE_IGNORE_IF_FEATURE     = 0x80;
     // Have-and-set flag constants, also used as masks
-    private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
-    private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
-    // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
-    private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
-    private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
+    private static final int SET_SUPPORTED_BY_FEATURES  = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
+    private static final int SET_IGNORE_IF_FEATURE      = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
+
+    // EffectiveConfig mapping
+    private static final int MASK_CONFIG = 0x03;
+    private static final int HAVE_CONFIG = 0x04;
+    private static final EffectiveConfig[] EFFECTIVE_CONFIGS;
+
+    static {
+        final EffectiveConfig[] values = EffectiveConfig.values();
+        final int length = values.length;
+        verify(length == 4, "Unexpected EffectiveConfig cardinality %s", length);
+        EFFECTIVE_CONFIGS = values;
+    }
 
     // Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
     // hence improve memory layout.
@@ -217,6 +223,45 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
         return definition().getPublicView();
     }
 
+    @Override
+    public final Parent effectiveParent() {
+        return getParentContext();
+    }
+
+    @Override
+    public final CommonStmtCtx root() {
+        return getRoot();
+    }
+
+    @Override
+    public final EffectiveStatement<?, ?> original() {
+        return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
+    }
+
+    @Override
+    // Non-final due to InferredStatementContext's override
+    public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
+            final @NonNull Class<Z> type) {
+        return allSubstatementsStream()
+            .filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
+            .findAny()
+            .map(ctx -> (X) ctx.getArgument());
+    }
+
+    @Override
+    // Non-final due to InferredStatementContext's override
+    public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
+        return allSubstatementsStream()
+            .anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
+    }
+
+    @Override
+    @Deprecated
+    @SuppressWarnings("unchecked")
+    public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
+        return (StmtContext<A, D, Z>) this;
+    }
+
     @Override
     public final String toString() {
         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
@@ -283,7 +328,7 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
         // 'input', which are implicitly defined.
         // Our implementation design makes an invariant assumption that buildDeclared() has been called by the time
         // we attempt to create effective statement:
-        buildDeclared();
+        declared();
 
         final E ret = effectiveInstance = createEffective();
         // we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
@@ -296,6 +341,20 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
 
     abstract @NonNull E createEffective();
 
+    /**
+     * Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
+     * this method does nothing.
+     *
+     * @param phase to be executed (completed)
+     * @return true if phase was successfully completed
+     * @throws SourceException when an error occurred in source parsing
+     */
+    final boolean tryToCompletePhase(final ModelProcessingPhase phase) {
+        return phase.isCompletedBy(getCompletedPhase()) || doTryToCompletePhase(phase);
+    }
+
+    abstract boolean doTryToCompletePhase(ModelProcessingPhase phase);
+
     //
     //
     // Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
@@ -346,44 +405,46 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
 
     /**
      * Config statements are not all that common which means we are performing a recursive search towards the root
-     * every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
+     * every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
      * for the (usually non-existent) config statement.
      *
      * <p>
      * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
-     * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
+     * result without performing any lookups, solely to support {@link #effectiveConfig()}.
      *
      * <p>
      * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
      *       {@link #isIgnoringConfig(StatementContextBase)}.
      */
-    final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
-        final int fl = flags & SET_CONFIGURATION;
-        if (fl != 0) {
-            return fl == SET_CONFIGURATION;
-        }
-        if (isIgnoringConfig(parent)) {
-            // Note: SET_CONFIGURATION has been stored in flags
-            return true;
-        }
+    final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
+        return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
+    }
 
-        final boolean isConfig;
-        final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
-        if (optConfig.isPresent()) {
-            isConfig = optConfig.orElseThrow();
-            if (isConfig) {
-                // Validity check: if parent is config=false this cannot be a config=true
-                InferenceException.throwIf(!parent.isConfiguration(), sourceReference(),
+    private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
+        final EffectiveConfig parentConfig = parent.effectiveConfig();
+
+        final EffectiveConfig myConfig;
+        if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
+            final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
+            if (optConfig.isPresent()) {
+                if (optConfig.orElseThrow()) {
+                    // Validity check: if parent is config=false this cannot be a config=true
+                    InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
                         "Parent node has config=false, this node must not be specifed as config=true");
+                    myConfig = EffectiveConfig.TRUE;
+                } else {
+                    myConfig = EffectiveConfig.FALSE;
+                }
+            } else {
+                // If "config" statement is not specified, the default is the same as the parent's "config" value.
+                myConfig = parentConfig;
             }
         } else {
-            // If "config" statement is not specified, the default is the same as the parent's "config" value.
-            isConfig = parent.isConfiguration();
+            myConfig = EffectiveConfig.IGNORED;
         }
 
-        // Resolved, make sure we cache this return
-        flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
-        return isConfig;
+        flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
+        return myConfig;
     }
 
     protected abstract boolean isIgnoringConfig();
@@ -395,20 +456,10 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
      *
      * <p>
      * Note: use of this method implies that {@link #isConfiguration()} is realized with
-     *       {@link #isConfiguration(StatementContextBase)}.
+     *       {@link #effectiveConfig(StatementContextBase)}.
      */
     final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
-        final int fl = flags & SET_IGNORE_CONFIG;
-        if (fl != 0) {
-            return fl == SET_IGNORE_CONFIG;
-        }
-        if (definition().support().isIgnoringConfig() || parent.isIgnoringConfig()) {
-            flags |= SET_IGNORE_CONFIG;
-            return true;
-        }
-
-        flags |= HAVE_IGNORE_CONFIG;
-        return false;
+        return EffectiveConfig.IGNORED == effectiveConfig(parent);
     }
 
     protected abstract boolean isIgnoringIfFeatures();
@@ -448,8 +499,6 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
     //
     //
 
-    abstract @NonNull Optional<SchemaPath> schemaPath();
-
     // Exists only to support {SubstatementContext,InferredStatementContext}.schemaPath()
     @Deprecated
     final @NonNull Optional<SchemaPath> substatementGetSchemaPath() {
@@ -508,6 +557,16 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
     //
     //
 
+    /**
+     * Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
+     * in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
+     * knowledge and update it when {@link #sweep()} is invoked.
+     */
+    private byte parentRef = PARENTREF_UNKNOWN;
+    private static final byte PARENTREF_UNKNOWN = -1;
+    private static final byte PARENTREF_ABSENT  = 0;
+    private static final byte PARENTREF_PRESENT = 1;
+
     /**
      * Acquire a reference on this context. As long as there is at least one reference outstanding,
      * {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
@@ -545,28 +604,60 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
 
         refcount = current - 1;
         LOG.trace("Refcount {} on {}", refcount, this);
-        if (isSweepable()) {
+
+        if (refcount == REFCOUNT_NONE) {
+            lastDecRef();
+        }
+    }
+
+    private void lastDecRef() {
+        if (noImplictRef()) {
             // We are no longer guarded by effective instance
             sweepOnDecrement();
+            return;
+        }
+
+        final byte prevRefs = parentRef;
+        if (prevRefs == PARENTREF_ABSENT) {
+            // We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
+            // updated
+            markNoParentRef();
+        } else if (prevRefs == PARENTREF_UNKNOWN) {
+            // Noone observed our parentRef, just update it
+            loadParentRefcount();
         }
     }
 
-    /**
-     * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
-     */
-    private void sweep() {
-        if (isSweepable()) {
-            LOG.trace("Releasing {}", this);
-            sweepState();
+    static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
+        for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
+            final byte prevRef = stmt.parentRef;
+            stmt.parentRef = PARENTREF_ABSENT;
+            if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
+                // Child thinks it is pinned down, update its perspective
+                stmt.markNoParentRef();
+            }
         }
     }
 
+    abstract void markNoParentRef();
+
     static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
             stmt.sweep();
         }
     }
 
+    /**
+     * Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
+     */
+    private void sweep() {
+        parentRef = PARENTREF_ABSENT;
+        if (refcount == REFCOUNT_NONE && noImplictRef()) {
+            LOG.trace("Releasing {}", this);
+            sweepState();
+        }
+    }
+
     static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
         int result = 0;
         for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
@@ -592,7 +683,7 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
     // Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
     private void sweepOnDecrement() {
         LOG.trace("Sweeping on decrement {}", this);
-        if (noParentRefcount()) {
+        if (noParentRef()) {
             // No further parent references, sweep our state.
             sweepState();
         }
@@ -620,7 +711,7 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
         }
 
         // parent is potentially reclaimable
-        if (noParentRefcount()) {
+        if (noParentRef()) {
             LOG.trace("Cleanup {} of parent {}", refcount, this);
             if (sweepState()) {
                 final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
@@ -635,29 +726,40 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
         return effectiveInstance != null || !isSupportedToBuildEffective();
     }
 
-    // FIXME: cache the resolution of this
-    private boolean noParentRefcount() {
+    private boolean noParentRef() {
+        return parentRefcount() == PARENTREF_ABSENT;
+    }
+
+    private byte parentRefcount() {
+        final byte refs;
+        return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
+    }
+
+    private byte loadParentRefcount() {
+        return parentRef = calculateParentRefcount();
+    }
+
+    private byte calculateParentRefcount() {
         final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
-        if (parent != null) {
-            // There are three possibilities:
-            // - REFCOUNT_NONE, in which case we need to search next parent
-            // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
-            //   a reference to us
-            // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
-            final int refs = parent.refcount;
-            return refs == REFCOUNT_NONE ? parent.noParentRefcount() : refs < REFCOUNT_NONE;
+        if (parent == null) {
+            return PARENTREF_ABSENT;
+        }
+        // There are three possibilities:
+        // - REFCOUNT_NONE, in which case we need to search next parent
+        // - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
+        //   a reference to us
+        // - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
+        final int refs = parent.refcount;
+        if (refs == REFCOUNT_NONE) {
+            return parent.parentRefcount();
         }
-        return true;
+        return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
     }
 
     private boolean isAwaitingChildren() {
         return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
     }
 
-    private boolean isSweepable() {
-        return refcount == REFCOUNT_NONE && noImplictRef();
-    }
-
     private void sweepOnChildDone() {
         LOG.trace("Sweeping on child done {}", this);
         final int current = refcount;