Cleanup unrecognized statement wrapping
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / InferredStatementContext.java
index 183f4d79bf55311aeefcb207ce590e0882a595af..8c2c3db91512708aa24a7e826d16bd12718c1fc1 100644 (file)
@@ -12,7 +12,6 @@ import static java.util.Objects.requireNonNull;
 
 import com.google.common.base.VerifyException;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Streams;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -20,23 +19,21 @@ import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-import java.util.Map.Entry;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 import org.eclipse.jdt.annotation.NonNull;
 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.YangStmtMapping;
 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.meta.CopyHistory;
 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.OnDemandSchemaTreeStorageNode;
@@ -55,14 +52,42 @@ import org.slf4j.LoggerFactory;
  */
 final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
         extends StatementContextBase<A, D, E> implements OnDemandSchemaTreeStorageNode {
+    // An effective copy view, with enough information to decide what to do next
+    private static final class EffectiveCopy implements Immutable {
+        // Original statement
+        private final ReactorStmtCtx<?, ?, ?> orig;
+        // Effective view, if the statement is to be reused it equals to orig
+        private final ReactorStmtCtx<?, ?, ?> copy;
+
+        EffectiveCopy(final ReactorStmtCtx<?, ?, ?> orig, final ReactorStmtCtx<?, ?, ?> copy) {
+            this.orig = requireNonNull(orig);
+            this.copy = requireNonNull(copy);
+        }
+
+        boolean isReused() {
+            return orig == copy;
+        }
+
+        ReactorStmtCtx<?, ?, ?> toChildContext(final @NonNull InferredStatementContext<?, ?, ?> parent) {
+            return isReused() ? orig.replicaAsChildOf(parent) : copy;
+        }
+
+        ReactorStmtCtx<?, ?, ?> toReusedChild(final @NonNull InferredStatementContext<?, ?, ?> parent) {
+            verify(isReused(), "Attempted to discard copy %s", copy);
+            return orig.replicaAsChildOf(parent);
+        }
+    }
+
     private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class);
 
-    // Sentinel object for 'substatements'
-    private static final Object SWEPT_SUBSTATEMENTS = new Object();
+    // Sentinel objects for 'substatements', String is a good enough type
+    private static final @NonNull String REUSED_SUBSTATEMENTS = "reused";
+    private static final @NonNull String SWEPT_SUBSTATEMENTS = "swept";
 
     private final @NonNull StatementContextBase<A, D, E> prototype;
     private final @NonNull StatementContextBase<?, ?, ?> parent;
     private final @NonNull StmtContext<A, D, E> originalCtx;
+    // TODO: consider encoding this in StatementContextBase fields, there should be plenty of room
     private final @NonNull CopyType childCopyType;
     private final QNameModule targetModule;
     private final A argument;
@@ -93,7 +118,7 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
 
     InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype,
             final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) {
-        super(prototype.definition(), CopyHistory.of(myCopyType, prototype.history()));
+        super(prototype, myCopyType);
         this.parent = requireNonNull(parent);
         this.prototype = requireNonNull(prototype);
         this.argument = targetModule == null ? prototype.argument()
@@ -188,6 +213,7 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     E createEffective(final StatementFactory<A, D, E> factory) {
         // 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);
     }
 
@@ -198,10 +224,12 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
 
         // First check if we can reuse the entire prototype
         if (!factory.canReuseCurrent(this, prototype, origSubstatements)) {
-            return tryToReuseSubstatements(factory, origSubstatements);
+            // FIXME: YANGTOOLS-1214: deduplicate this return
+            return tryToReuseSubstatements(factory, origEffective);
         }
 
-        // No substatements to deal with, we can freely reuse the original
+        // We can reuse this statement let's see if all statements agree...
+        // ... no substatements to deal with, we can freely reuse the original
         if (origSubstatements.isEmpty()) {
             LOG.debug("Reusing empty: {}", origEffective);
             substatements = ImmutableList.of();
@@ -209,62 +237,77 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
             return origEffective;
         }
 
-        // We can reuse this statement let's see if all the statements agree
-        final List<Entry<Mutable<?, ?, ?>, Mutable<?, ?, ?>>> declared = prototype.streamDeclared()
-            .filter(StmtContext::isSupportedByFeatures)
+        // ... all are context independent, reuse the original
+        if (allSubstatementsContextIndependent()) {
+            LOG.debug("Reusing context-independent: {}", origEffective);
+            substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
+            prototype.decRef();
+            return origEffective;
+        }
+
+        // ... copy-sensitive check
+        final List<EffectiveCopy> declCopy = prototype.streamDeclared()
             .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
             .filter(Objects::nonNull)
             .collect(Collectors.toUnmodifiableList());
-        final List<Entry<Mutable<?, ?, ?>, Mutable<?, ?, ?>>> effective = prototype.streamEffective()
+        final List<EffectiveCopy> effCopy = prototype.streamEffective()
             .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
             .filter(Objects::nonNull)
             .collect(Collectors.toUnmodifiableList());
 
-        // We no longer need the prototype's substatements, but we may need to retain ours
-        prototype.decRef();
-        if (haveRef()) {
-            substatements = Streams.concat(declared.stream(), effective.stream())
-                .map(Entry::getValue)
-                .collect(ImmutableList.toImmutableList());
-        } else {
-            // This should immediately get swept anyway. Should we use a poison object?
-            substatements = List.of();
-        }
-
-        if (allReused(declared) && allReused(effective)) {
+        // ... are any copy-sensitive?
+        if (allReused(declCopy) && allReused(effCopy)) {
             LOG.debug("Reusing after substatement check: {}", origEffective);
+            substatements = noRefs() ? REUSED_SUBSTATEMENTS
+                : reusePrototypeReplicas(Streams.concat(declCopy.stream(), effCopy.stream())
+                    .map(copy -> copy.toReusedChild(this)));
+            prototype.decRef();
             return origEffective;
         }
 
-        // Values are the effective copies, hence this efficienly deals with recursion.
-        return factory.createEffective(this, declared.stream().map(Entry::getValue),
-            effective.stream().map(Entry::getValue));
+        // *sigh*, ok, heavy lifting through a shallow copy
+        final List<ReactorStmtCtx<?, ?, ?>> declared = declCopy.stream()
+            .map(copy -> copy.toChildContext(this))
+            .collect(ImmutableList.toImmutableList());
+        final List<ReactorStmtCtx<?, ?, ?>> effective = effCopy.stream()
+            .map(copy -> copy.toChildContext(this))
+            .collect(ImmutableList.toImmutableList());
+        substatements = declared.isEmpty() ? effective
+            : Streams.concat(declared.stream(), effective.stream()).collect(ImmutableList.toImmutableList());
+        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());
     }
 
-    private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory,
-            final @NonNull Collection<? extends EffectiveStatement<?, ?>> origSubstatements) {
+    private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory, final @NonNull E original) {
         if (allSubstatementsContextIndependent()) {
             LOG.debug("Reusing substatements of: {}", prototype);
-            // FIXME: can we skip this if !haveRef()?
-            substatements = reusePrototypeReplicas();
+            substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
             prototype.decRef();
-            return factory.createEffective(this, origSubstatements);
+            return factory.copyEffective(this, original);
         }
 
         // 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);
-        if (sameSubstatements(origSubstatements, effective)) {
+        // Since we have forced instantiation to deal with this case, we also need to reset the 'modified' flag
+        setUnmodified();
+
+        if (sameSubstatements(original.effectiveSubstatements(), effective)) {
             LOG.debug("Reusing unchanged substatements of: {}", prototype);
-            return factory.createEffective(this, origSubstatements);
+            return factory.copyEffective(this, original);
         }
         return effective;
     }
 
     private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas() {
-        return Streams.concat(
-            prototype.streamDeclared().filter(StmtContext::isSupportedByFeatures),
-            prototype.streamEffective())
+        return reusePrototypeReplicas(Streams.concat(prototype.streamDeclared(), prototype.streamEffective()));
+    }
+
+    private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<StmtContext<?, ?, ?>> stream) {
+        return stream
             .map(stmt -> {
                 final ReplicaStatementContext<?, ?, ?> ret = ((ReactorStmtCtx<?, ?, ?>) stmt).replicaAsChildOf(this);
                 ret.buildEffective();
@@ -294,13 +337,13 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         return true;
     }
 
-    private static boolean allReused(final List<Entry<Mutable<?, ?, ?>, Mutable<?, ?, ?>>> entries) {
-        for (Entry<Mutable<?, ?, ?>, Mutable<?, ?, ?>> entry : entries) {
-            if (entry.getKey() != entry.getValue()) {
-                return false;
-            }
-        }
-        return true;
+    private static boolean allReused(final List<EffectiveCopy> entries) {
+        return entries.stream().allMatch(EffectiveCopy::isReused);
+    }
+
+    @Override
+    ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource() {
+        return isModified() ? this : prototype.unmodifiedEffectiveSource();
     }
 
     @Override
@@ -337,10 +380,10 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     }
 
     @Override
-    public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
+    <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
             final @NonNull Class<Z> type) {
         if (substatements instanceof List) {
-            return super.findSubstatementArgument(type);
+            return super.findSubstatementArgumentImpl(type);
         }
 
         final Optional<X> templateArg = prototype.findSubstatementArgument(type);
@@ -355,8 +398,8 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     }
 
     @Override
-    public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
-        return substatements instanceof List ? super.hasSubstatement(type)
+    boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
+        return substatements instanceof List ? super.hasSubstatementImpl(type)
             // We do not allow deletion of partially-materialized statements, hence this is accurate
             : prototype.hasSubstatement(type);
     }
@@ -429,18 +472,19 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     }
 
     @Override
-    Stream<? extends StmtContext<?, ?, ?>> streamDeclared() {
+    Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared() {
         return Stream.empty();
     }
 
     @Override
-    Stream<? extends StmtContext<?, ?, ?>> streamEffective() {
-        accessSubstatements();
-        return ensureEffectiveSubstatements().stream();
+    Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective() {
+        return ensureEffectiveSubstatements().stream().filter(StmtContext::isSupportedToBuildEffective);
     }
 
     private void accessSubstatements() {
-        verify(substatements != SWEPT_SUBSTATEMENTS, "Attempted to access substatements of %s", this);
+        if (substatements instanceof String) {
+            throw new VerifyException("Access to " + substatements + " substatements of " + this);
+        }
     }
 
     @Override
@@ -456,7 +500,7 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         final Object local = substatements;
         substatements = SWEPT_SUBSTATEMENTS;
         int count = 0;
-        if (local != null) {
+        if (local instanceof List) {
             final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local);
             sweep(list);
             count = countUnswept(list);
@@ -482,43 +526,24 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
         ret.addAll((Collection) buffer);
         substatements = ret;
+        setModified();
 
         prototype.decRef();
         return ret;
     }
 
-    // Statement copy mess starts here
     //
-    // FIXME: This is messy and is probably wrong in some corner case. Even if it is correct, the way how it is correct
-    //        relies on hard-coded maps. At the end of the day, the logic needs to be controlled by statement's
-    //        StatementSupport.
-    // FIXME: YANGTOOLS-652: this map looks very much like UsesStatementSupport.TOP_REUSED_DEF_SET
-    private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
-        YangStmtMapping.TYPE,
-        YangStmtMapping.TYPEDEF,
-        YangStmtMapping.USES);
-
-    private Map.Entry<Mutable<?, ?, ?>, Mutable<?, ?, ?>> effectiveCopy(final ReactorStmtCtx<?, ?, ?> stmt) {
-        // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses"
-        if (REUSED_DEF_SET.contains(stmt.definition().getPublicView())) {
-            return Map.entry(stmt, stmt.replicaAsChildOf(this));
-        }
+    // Statement copy mess starts here. As it turns out, it's not that much of a mess, but it does make your head spin
+    // sometimes. Tread softly because you tread on my dreams.
+    //
 
+    private EffectiveCopy effectiveCopy(final ReactorStmtCtx<?, ?, ?> stmt) {
         final ReactorStmtCtx<?, ?, ?> effective = stmt.asEffectiveChildOf(this, childCopyType, targetModule);
-        return effective == null ? null : Map.entry(stmt, effective);
+        return effective == null ? null : new EffectiveCopy(stmt, effective);
     }
 
     private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
             final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
-        final StatementDefinition def = substatement.publicDefinition();
-
-        // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses"
-        if (REUSED_DEF_SET.contains(def)) {
-            LOG.trace("Reusing substatement {} for {}", substatement, this);
-            buffer.add(substatement.replicaAsChildOf(this));
-            return;
-        }
-
         // 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.
         //
@@ -536,10 +561,6 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     }
 
     private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
-        // FIXME: YANGTOOLS-1195: this is not exactly what we want to do here, because we are dealing with two different
-        //                        requests: copy for inference purposes (this method), while we also copy for purposes
-        //                        of buildEffective() -- in which case we want to probably invoke asEffectiveChildOf()
-        //                        or similar
         return substatement.copyAsChildOf(this, childCopyType, targetModule);
     }
 
@@ -552,6 +573,7 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
             // resizing operation.
             materializedSchemaTree = new HashMap<>(4);
             substatements = materializedSchemaTree;
+            setModified();
         } else {
             verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
             materializedSchemaTree = castMaterialized(substatements);
@@ -591,7 +613,7 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
      */
     @Override
     @Deprecated
-    public Optional<SchemaPath> schemaPath() {
+    public SchemaPath schemaPath() {
         return substatementGetSchemaPath();
     }