Cleanup unrecognized statement wrapping
[yangtools.git] / yang / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / InferredStatementContext.java
index 2af56a77f133e902284851f5cad23ae725b217c0..8c2c3db91512708aa24a7e826d16bd12718c1fc1 100644 (file)
@@ -34,7 +34,6 @@ 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;
@@ -81,12 +80,14 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
 
     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;
@@ -117,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()
@@ -212,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);
     }
 
@@ -222,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)) {
+            // 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();
@@ -233,7 +237,15 @@ 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
+        // ... 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)
@@ -243,15 +255,17 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
             .filter(Objects::nonNull)
             .collect(Collectors.toUnmodifiableList());
 
+        // ... are any copy-sensitive?
         if (allReused(declCopy) && allReused(effCopy)) {
             LOG.debug("Reusing after substatement check: {}", origEffective);
-            // FIXME: can we skip this if !haveRef()?
-            substatements = reusePrototypeReplicas(Streams.concat(declCopy.stream(), effCopy.stream())
-                .map(copy -> copy.toReusedChild(this)));
+            substatements = noRefs() ? REUSED_SUBSTATEMENTS
+                : reusePrototypeReplicas(Streams.concat(declCopy.stream(), effCopy.stream())
+                    .map(copy -> copy.toReusedChild(this)));
             prototype.decRef();
             return origEffective;
         }
 
+        // *sigh*, ok, heavy lifting through a shallow copy
         final List<ReactorStmtCtx<?, ?, ?>> declared = declCopy.stream()
             .map(copy -> copy.toChildContext(this))
             .collect(ImmutableList.toImmutableList());
@@ -263,14 +277,14 @@ 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());
     }
 
     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.copyEffective(this, original);
         }
@@ -278,6 +292,9 @@ 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);
+        // 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.copyEffective(this, original);
@@ -286,8 +303,7 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     }
 
     private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas() {
-        return reusePrototypeReplicas(Streams.concat(
-            prototype.streamDeclared(), prototype.streamEffective()));
+        return reusePrototypeReplicas(Streams.concat(prototype.streamDeclared(), prototype.streamEffective()));
     }
 
     private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<StmtContext<?, ?, ?>> stream) {
@@ -325,6 +341,11 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
         return entries.stream().allMatch(EffectiveCopy::isReused);
     }
 
+    @Override
+    ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource() {
+        return isModified() ? this : prototype.unmodifiedEffectiveSource();
+    }
+
     @Override
     boolean hasEmptySubstatements() {
         if (substatements == null) {
@@ -359,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);
@@ -377,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);
     }
@@ -461,7 +482,9 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
     }
 
     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
@@ -477,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);
@@ -503,6 +526,7 @@ 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;
@@ -549,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);