Improve StatementContextBase.stream{Declared,Effective}
[yangtools.git] / parser / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / InferredStatementContext.java
index 3d012f30b54d7fa9457b6b388096b8afd283ffd2..d37cd34b0c5703bec8d915ff9c9a527a4f30134f 100644 (file)
@@ -12,9 +12,11 @@ import static java.util.Objects.requireNonNull;
 
 import com.google.common.base.VerifyException;
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Maps;
 import com.google.common.collect.Streams;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -28,13 +30,13 @@ import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
-import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
+import org.opendaylight.yangtools.yang.parser.spi.ParserNamespaces;
 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
+import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStatementState;
 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.OnDemandSchemaTreeStorageNode;
 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
@@ -86,7 +88,7 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
 
     private final @NonNull StatementContextBase<A, D, E> prototype;
     private final @NonNull StatementContextBase<?, ?, ?> parent;
-    private final @NonNull StmtContext<A, D, E> originalCtx;
+    private final @NonNull ReactorStmtCtx<A, D, E> originalCtx;
     private final QNameModule targetModule;
     private final A argument;
 
@@ -121,7 +123,10 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         this.argument = targetModule == null ? prototype.argument()
                 : prototype.definition().adaptArgumentValue(prototype, targetModule);
         this.targetModule = targetModule;
-        this.originalCtx = prototype.getOriginalCtx().orElse(prototype);
+
+        final var origCtx = prototype.getOriginalCtx().orElse(prototype);
+        verify(origCtx instanceof ReactorStmtCtx, "Unexpected original %s", origCtx);
+        this.originalCtx = (ReactorStmtCtx<A, D, E>) origCtx;
 
         // Mark prototype as blocking statement cleanup
         prototype.incRef();
@@ -138,13 +143,13 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     }
 
     @Override
-    public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
+    public Iterable<? extends @NonNull StmtContext<?, ?, ?>> allSubstatements() {
         // No need to concat with declared
         return effectiveSubstatements();
     }
 
     @Override
-    public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
+    public Stream<? extends @NonNull StmtContext<?, ?, ?>> allSubstatementsStream() {
         // No need to concat with declared
         return effectiveSubstatements().stream();
     }
@@ -193,6 +198,7 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     @Override
     public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
         substatements = addEffectiveSubstatement(ensureEffectiveSubstatements(), substatement);
+        afterAddEffectiveSubstatement(substatement);
     }
 
     @Override
@@ -210,18 +216,28 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         // If we have not materialized we do not have a difference in effective substatements, hence we can forward
         // towards the source of the statement.
         accessSubstatements();
-        return substatements == null ? tryToReusePrototype(factory) : super.createEffective(factory);
+        return substatements == null ? tryToReusePrototype(factory) : createInferredEffective(factory);
+    }
+
+    private @NonNull E createInferredEffective(final @NonNull StatementFactory<A, D, E> factory) {
+        return createInferredEffective(factory, this, streamDeclared(), streamEffective());
+    }
+
+    @Override
+    E createInferredEffective(final StatementFactory<A, D, E> factory, final InferredStatementContext<A, D, E> ctx,
+            final Stream<? extends ReactorStmtCtx<?, ?, ?>> declared,
+            final Stream<? extends ReactorStmtCtx<?, ?, ?>> effective) {
+        return originalCtx.createInferredEffective(factory, ctx, declared, effective);
     }
 
-    private @NonNull E tryToReusePrototype(final StatementFactory<A, D, E> factory) {
+    private @NonNull E tryToReusePrototype(final @NonNull StatementFactory<A, D, E> factory) {
         final E origEffective = prototype.buildEffective();
         final Collection<? extends @NonNull EffectiveStatement<?, ?>> origSubstatements =
             origEffective.effectiveSubstatements();
 
         // First check if we can reuse the entire prototype
         if (!factory.canReuseCurrent(this, prototype, origSubstatements)) {
-            // FIXME: YANGTOOLS-1214: deduplicate this return
-            return tryToReuseSubstatements(factory, origEffective);
+            return internAlongCopyAxis(factory, tryToReuseSubstatements(factory, origEffective));
         }
 
         // We can reuse this statement let's see if all statements agree...
@@ -243,11 +259,11 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
 
         // ... copy-sensitive check
         final List<EffectiveCopy> declCopy = prototype.streamDeclared()
-            .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
+            .map(this::effectiveCopy)
             .filter(Objects::nonNull)
             .collect(Collectors.toUnmodifiableList());
         final List<EffectiveCopy> effCopy = prototype.streamEffective()
-            .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
+            .map(this::effectiveCopy)
             .filter(Objects::nonNull)
             .collect(Collectors.toUnmodifiableList());
 
@@ -273,11 +289,12 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         prototype.decRef();
 
         // Values are the effective copies, hence this efficiently deals with recursion.
-        // FIXME: YANGTOOLS-1214: deduplicate this return
-        return factory.createEffective(this, declared.stream(), effective.stream());
+        return internAlongCopyAxis(factory,
+            originalCtx.createInferredEffective(factory, this, declared.stream(), effective.stream()));
     }
 
-    private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory, final @NonNull E original) {
+    private @NonNull E tryToReuseSubstatements(final @NonNull StatementFactory<A, D, E> factory,
+            final @NonNull E original) {
         if (allSubstatementsContextIndependent()) {
             LOG.debug("Reusing substatements of: {}", prototype);
             substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
@@ -287,7 +304,7 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
 
         // Fall back to full instantiation, which populates our substatements. Then check if we should be reusing
         // the substatement list, as this operation turned out to not affect them.
-        final E effective = super.createEffective(factory);
+        final E effective = createInferredEffective(factory);
         // Since we have forced instantiation to deal with this case, we also need to reset the 'modified' flag
         setUnmodified();
 
@@ -298,14 +315,24 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         return effective;
     }
 
+    private @NonNull E internAlongCopyAxis(final StatementFactory<A, D, E> factory, final @NonNull E stmt) {
+        if (!isModified()) {
+            final EffectiveStatementState state = factory.extractEffectiveState(stmt);
+            if (state != null) {
+                return prototype.unmodifiedEffectiveSource().attachEffectiveCopy(state, stmt);
+            }
+        }
+        return stmt;
+    }
+
     private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas() {
         return reusePrototypeReplicas(Streams.concat(prototype.streamDeclared(), prototype.streamEffective()));
     }
 
-    private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<StmtContext<?, ?, ?>> stream) {
+    private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<ReactorStmtCtx<?, ?, ?>> stream) {
         return stream
             .map(stmt -> {
-                final ReplicaStatementContext<?, ?, ?> ret = ((ReactorStmtCtx<?, ?, ?>) stmt).replicaAsChildOf(this);
+                final var ret = stmt.replicaAsChildOf(this);
                 ret.buildEffective();
                 return ret;
             })
@@ -313,19 +340,18 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     }
 
     private static boolean sameSubstatements(final Collection<?> original, final EffectiveStatement<?, ?> effective) {
-        final Collection<?> copied = effective.effectiveSubstatements();
+        final var copied = effective.effectiveSubstatements();
         if (copied != effective.effectiveSubstatements() || original.size() != copied.size()) {
             // Do not bother if result is treating substatements as transient
             return false;
         }
 
-        final Iterator<?> oit = original.iterator();
-        final Iterator<?> cit = copied.iterator();
-        while (oit.hasNext()) {
+        final var cit = copied.iterator();
+        for (var origChild : original) {
             verify(cit.hasNext());
             // Identity comparison on purpose to side-step whatever equality there might be. We want to reuse instances
             // after all.
-            if (oit.next() != cit.next()) {
+            if (origChild != cit.next()) {
                 return false;
             }
         }
@@ -416,8 +442,8 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         if (prototype instanceof InferredStatementContext) {
             // Note: we need to access namespace here, as the target statement may have already been populated, in which
             //       case we want to obtain the statement in local namespace storage.
-            template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(
-                SchemaTreeNamespace.class, templateQName);
+            template = ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(ParserNamespaces.schemaTree(),
+                templateQName);
         } else {
             template = prototype.allSubstatementsStream()
                 .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
@@ -434,11 +460,9 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         }
 
         @SuppressWarnings("unchecked")
-        final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
-            .orElseThrow(
-                () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
-        ensureCompletedPhase(ret);
-        addMaterialized(template, ret);
+        final var ret = (Mutable<QName, Y, Z>) copySubstatement(template).orElseThrow(
+            () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
+        addMaterialized(template, ensureCompletedPhase(ret));
 
         LOG.debug("Child {} materialized", qname);
         return ret;
@@ -449,31 +473,32 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     private List<ReactorStmtCtx<?, ?, ?>> ensureEffectiveSubstatements() {
         accessSubstatements();
         return substatements instanceof List ? castEffective(substatements)
-            : initializeSubstatements(castMaterialized(substatements));
+            // We have either not started or have only partially-materialized statements, ensure full materialization
+            : initializeSubstatements();
     }
 
     @Override
-    Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() {
+    Iterator<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() {
         // When we have not initialized, there are no statements to catch up: we will catch up when we are copying
         // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL).
         if (substatements == null) {
-            return ImmutableList.of();
+            return Collections.emptyIterator();
         }
         accessSubstatements();
         if (substatements instanceof HashMap) {
-            return castMaterialized(substatements).values();
+            return castMaterialized(substatements).values().iterator();
         } else {
-            return castEffective(substatements);
+            return castEffective(substatements).iterator();
         }
     }
 
     @Override
-    Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared() {
+    Stream<? extends @NonNull ReactorStmtCtx<?, ?, ?>> streamDeclared() {
         return Stream.empty();
     }
 
     @Override
-    Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective() {
+    Stream<? extends @NonNull ReactorStmtCtx<?, ?, ?>> streamEffective() {
         return ensureEffectiveSubstatements().stream().filter(StmtContext::isSupportedToBuildEffective);
     }
 
@@ -504,23 +529,32 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         return count;
     }
 
-    private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements(
-            final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
-        final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
-        final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
+    private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements() {
+        final var declared = prototype.mutableDeclaredSubstatements();
+        final var effective = prototype.mutableEffectiveSubstatements();
+
+        // We are about to instantiate some substatements. The simple act of materializing them may end up triggering
+        // namespace lookups, which in turn can materialize copies by themselves, running ahead of our materialization.
+        // We therefore need a meeting place for, which are the partially-materialized substatements. If we do not have
+        // them yet, instantiate them and we need to populate them as well.
+        final int expectedSize = declared.size() + effective.size();
+        var materializedSchemaTree = castMaterialized(substatements);
+        if (materializedSchemaTree == null) {
+            substatements = materializedSchemaTree = Maps.newHashMapWithExpectedSize(expectedSize);
+        }
 
-        final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
-        for (final Mutable<?, ?, ?> stmtContext : declared) {
+        final var buffer = new ArrayList<ReactorStmtCtx<?, ?, ?>>(expectedSize);
+        for (var stmtContext : declared) {
             if (stmtContext.isSupportedByFeatures()) {
                 copySubstatement(stmtContext, buffer, materializedSchemaTree);
             }
         }
-        for (final Mutable<?, ?, ?> stmtContext : effective) {
+        for (var stmtContext : effective) {
             copySubstatement(stmtContext, buffer, materializedSchemaTree);
         }
 
-        final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
-        ret.addAll((Collection) buffer);
+        final var ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
+        ret.addAll(buffer);
         substatements = ret;
         setModified();
 
@@ -538,29 +572,31 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         return effective == null ? null : new EffectiveCopy(stmt, effective);
     }
 
-    private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
+    private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<ReactorStmtCtx<?, ?, ?>> buffer,
             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
         // Consult materialized substatements. We are in a copy operation and will end up throwing materialized
         // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
         //
         // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
         // against parent would change -- and we certainly do not want that to happen.
-        final ReactorStmtCtx<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
+        final var materialized = findMaterialized(materializedSchemaTree, substatement);
         if (materialized == null) {
             copySubstatement(substatement).ifPresent(copy -> {
-                ensureCompletedPhase(copy);
-                buffer.add(copy);
+                final var cast = ensureCompletedPhase(copy);
+                materializedSchemaTree.put(substatement, cast);
+                buffer.add(cast);
             });
         } else {
             buffer.add(materialized);
         }
     }
 
-    private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
+    private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Optional<Mutable<X, Y, Z>>
+            copySubstatement(final StmtContext<X, Y, Z> substatement) {
         return substatement.copyAsChildOf(this, childCopyType(), targetModule);
     }
 
-    private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
+    private void addMaterialized(final StmtContext<?, ?, ?> template, final ReactorStmtCtx<?, ?, ?> copy) {
         final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree;
         if (substatements == null) {
             // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
@@ -575,8 +611,7 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
             materializedSchemaTree = castMaterialized(substatements);
         }
 
-        final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
-            (StatementContextBase<?, ?, ?>) copy);
+        final var existing = materializedSchemaTree.put(template, copy);
         if (existing != null) {
             throw new VerifyException(
                 "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
@@ -607,12 +642,6 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
      * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
      * properly updated there.
      */
-    @Override
-    @Deprecated
-    public SchemaPath schemaPath() {
-        return substatementGetSchemaPath();
-    }
-
     @Override
     public A argument() {
         return argument;