Fix SchemaTreeNamespace population via augment
[yangtools.git] / parser / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / StatementContextBase.java
index 8375a46705c93cadd3a1c3cf66743511848243f6..1be883cd2b2213fea83f50024247b09c67e87a7c 100644 (file)
@@ -30,6 +30,7 @@ import java.util.Map.Entry;
 import java.util.Optional;
 import java.util.stream.Stream;
 import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
@@ -49,7 +50,7 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport.CopyPolicy;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
-import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
+import org.opendaylight.yangtools.yang.parser.spi.meta.UndeclaredStatementFactory;
 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
 import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
@@ -149,6 +150,24 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
      */
     private byte executionOrder;
 
+    /**
+     * This field should live in AbstractResumedStatement, but is placed here for memory efficiency to squat in the
+     * alignment shadow of {@link #bitsAight} and {@link #executionOrder}.
+     */
+    private boolean implicitDeclaredFlag;
+
+    // TODO: we a single byte of alignment shadow left, we should think how we can use it to cache information we build
+    //       during InferredStatementContext.tryToReusePrototype(). We usually end up being routed to
+    //       copyAsChildOfImpl() -- which performs an eager instantiation and checks for changes afterwards. We should
+    //       be able to capture how parent scope affects the copy in a few bits. If we can do that, than we can reap
+    //       the benefits by just examining new parent context and old parent context contribution to the state. If
+    //       their impact is the same, we can skip instantiation of statements and directly reuse them (individually,
+    //       or as a complete file).
+    //
+    //       Whatever we end up tracking, we need to track two views of that -- for the statement itself
+    //       (sans substatements) and a summary of substatements. I think it should be possible to get this working
+    //       with 2x5bits -- we have up to 15 mutable bits available if we share the field with implicitDeclaredFlag.
+
     // Copy constructor used by subclasses to implement reparent()
     StatementContextBase(final StatementContextBase<A, D, E> original) {
         super(original);
@@ -312,13 +331,12 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
 
     @Override
     public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
-            Mutable<X, Y, Z> addEffectiveSubstatement(final StatementSupport<X, Y, Z> support, final X arg) {
-        // FIXME: YANGTOOLS-652: This does not need to be a SubstatementContext, in can be a specialized
-        //                       StatementContextBase subclass.
-        final Mutable<X, Y, Z> ret = new SubstatementContext<>(this, new StatementDefinitionContext<>(support),
-                ImplicitSubstatement.of(sourceReference()), arg);
+            Mutable<X, Y, Z> createUndeclaredSubstatement(final StatementSupport<X, Y, Z> support, final X arg) {
+        requireNonNull(support);
+        checkArgument(support instanceof UndeclaredStatementFactory, "Unsupported statement support %s", support);
+
+        final var ret = new UndeclaredStmtCtx<>(this, support, arg);
         support.onStatementAdded(ret);
-        addEffectiveSubstatement(ret);
         return ret;
     }
 
@@ -333,6 +351,19 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
         return resized;
     }
 
+    static final void afterAddEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
+        // Undeclared statements still need to have 'onDeclarationFinished()' triggered
+        if (substatement instanceof UndeclaredStmtCtx) {
+            finishDeclaration((UndeclaredStmtCtx<?, ?, ?>) substatement);
+        }
+    }
+
+    // Split out to keep generics working without a warning
+    private static <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> void finishDeclaration(
+            final UndeclaredStmtCtx<X, Y, Z> substatement) {
+        substatement.definition().onDeclarationFinished(substatement, ModelProcessingPhase.FULL_DECLARATION);
+    }
+
     @Override
     public final void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
         if (!statements.isEmpty()) {
@@ -358,7 +389,7 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
         return resized;
     }
 
-    abstract Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
+    abstract Iterator<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete();
 
     // exposed for InferredStatementContext only
     final void ensureCompletedPhase(final Mutable<?, ?, ?> stmt) {
@@ -412,15 +443,7 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
         return result;
     }
 
-    @NonNull E createEffective(final StatementFactory<A, D, E> factory) {
-        return createEffective(factory, this);
-    }
-
-    // Creates EffectiveStatement through full materialization
-    static <A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> @NonNull E createEffective(
-            final StatementFactory<A, D, E> factory, final StatementContextBase<A, D, E> ctx) {
-        return factory.createEffective(ctx, ctx.streamDeclared(), ctx.streamEffective());
-    }
+    abstract @NonNull E createEffective(@NonNull StatementFactory<A, D, E> factory);
 
     /**
      * Return a stream of declared statements which can be built into an {@link EffectiveStatement}, as per
@@ -455,8 +478,9 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
         for (final StatementContextBase<?, ?, ?> child : mutableDeclaredSubstatements()) {
             finished &= child.tryToCompletePhase(targetOrder);
         }
-        for (final ReactorStmtCtx<?, ?, ?> child : effectiveChildrenToComplete()) {
-            finished &= child.tryToCompletePhase(targetOrder);
+        final var it = effectiveChildrenToComplete();
+        while (it.hasNext()) {
+            finished &= it.next().tryToCompletePhase(targetOrder);
         }
         return finished;
     }
@@ -719,7 +743,7 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
         return Optional.ofNullable(copyAsChildOfImpl(parent, type, targetModule));
     }
 
-    private ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
+    private @Nullable ReactorStmtCtx<A, D, E> copyAsChildOfImpl(final Mutable<?, ?, ?> parent, final CopyType type,
             final QNameModule targetModule) {
         final StatementSupport<A, D, E> support = definition.support();
         final CopyPolicy policy = support.copyPolicy();
@@ -757,7 +781,7 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
         return canReuseCurrent(copy) ? this : copy;
     }
 
-    private boolean canReuseCurrent(final ReactorStmtCtx<A, D, E> copy) {
+    private boolean canReuseCurrent(final @NonNull ReactorStmtCtx<A, D, E> copy) {
         // Defer to statement factory to see if we can reuse this object. If we can and have only context-independent
         // substatements we can reuse the object. More complex cases are handled indirectly via the copy.
         return definition.getFactory().canReuseCurrent(copy, this, buildEffective().effectiveSubstatements())
@@ -785,9 +809,7 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
         final InferredStatementContext<X, Y, Z> copy;
 
         if (implicitParent.isPresent()) {
-            final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
-            result = new SubstatementContext(this, def, original.sourceReference(), original.rawArgument(),
-                original.argument(), type);
+            result = new UndeclaredStmtCtx(this, implicitParent.orElseThrow(), original, type);
 
             final CopyType childCopyType;
             switch (type) {
@@ -805,6 +827,7 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
 
             copy = new InferredStatementContext<>(result, original, childCopyType, type, targetModule);
             result.addEffectiveSubstatement(copy);
+            result.definition.onStatementAdded(result);
         } else {
             result = copy = new InferredStatementContext<>(this, original, type, type, targetModule);
         }
@@ -836,16 +859,11 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
             return original;
         }
 
-        final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.orElseThrow());
-        final CopyType type = original.history().getLastOperation();
-
         checkArgument(original instanceof StatementContextBase, "Unsupported original %s", original);
         final var origBase = (StatementContextBase<?, ?, ?>)original;
 
-        @SuppressWarnings({ "rawtypes", "unchecked"})
-        final SubstatementContext<?, ?, ?> result = new SubstatementContext(origBase.getParentContext(), def,
-            original.sourceReference(), original.rawArgument(), original.argument(), type);
-
+        @SuppressWarnings({ "rawtypes", "unchecked" })
+        final UndeclaredStmtCtx<?, ?, ?> result = new UndeclaredStmtCtx(origBase, optImplicit.orElseThrow());
         result.addEffectiveSubstatement(origBase.reparent(result));
         result.setCompletedPhase(original.getCompletedPhase());
         return result;
@@ -859,4 +877,13 @@ abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends
      * @return True if {@link #allSubstatements()} and {@link #allSubstatementsStream()} would return an empty stream.
      */
     abstract boolean hasEmptySubstatements();
+
+    // Note: these two are exposed for AbstractResumedStatement only
+    final boolean getImplicitDeclaredFlag() {
+        return implicitDeclaredFlag;
+    }
+
+    final void setImplicitDeclaredFlag() {
+        implicitDeclaredFlag = true;
+    }
 }