Refactor nest tests.

Change-Id: Iecae15bdeb2dd9dceae13a29e2a50d0d0172bd44
diff --git a/src/test/examplesJava11/nestHostExample/BasicNestHostWithInnerClass.java b/src/test/examplesJava11/nestHostExample/BasicNestHostWithInnerClass.java
index 64aa388..06d328d 100644
--- a/src/test/examplesJava11/nestHostExample/BasicNestHostWithInnerClass.java
+++ b/src/test/examplesJava11/nestHostExample/BasicNestHostWithInnerClass.java
@@ -65,12 +65,12 @@
           + BasicNestedClass.staticMethod();
     }
 
-    public static void main(String[] args) {
-      BasicNestHostWithInnerClass outer = BasicNestedClass.createOuterInstance("field");
-      BasicNestedClass inner = BasicNestHostWithInnerClass.createNestedInstance("nest1SField");
+  }
+  public static void main(String[] args) {
+    BasicNestHostWithInnerClass outer = BasicNestedClass.createOuterInstance("field");
+    BasicNestedClass inner = BasicNestHostWithInnerClass.createNestedInstance("nest1SField");
 
-      System.out.println(outer.accessNested(inner));
-      System.out.println(inner.accessOuter(outer));
-    }
+    System.out.println(outer.accessNested(inner));
+    System.out.println(inner.accessOuter(outer));
   }
 }
diff --git a/src/test/java/com/android/tools/r8/JvmTestBuilder.java b/src/test/java/com/android/tools/r8/JvmTestBuilder.java
index c57dd27..d12f50b 100644
--- a/src/test/java/com/android/tools/r8/JvmTestBuilder.java
+++ b/src/test/java/com/android/tools/r8/JvmTestBuilder.java
@@ -142,8 +142,15 @@
 
   @Override
   public JvmTestBuilder addProgramFiles(Collection<Path> files) {
-    throw new Unimplemented(
-        "No support for adding paths directly (we need to compute the descriptor)");
+    for (Path file : files) {
+      if (FileUtils.isArchive(file)) {
+        classpath.add(file);
+      } else {
+        throw new Unimplemented(
+            "No support for adding paths directly (we need to compute the descriptor)");
+      }
+    }
+    return self();
   }
 
   @Override
diff --git a/src/test/java/com/android/tools/r8/TestBase.java b/src/test/java/com/android/tools/r8/TestBase.java
index 8839960..d1d53f3 100644
--- a/src/test/java/com/android/tools/r8/TestBase.java
+++ b/src/test/java/com/android/tools/r8/TestBase.java
@@ -61,7 +61,9 @@
 import java.util.Collections;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Objects;
 import java.util.concurrent.ExecutionException;
+import java.util.function.BiFunction;
 import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.jar.JarOutputStream;
@@ -166,13 +168,16 @@
   private static TemporaryFolder staticTemp = null;
 
   @BeforeClass
-  public static void testBaseBeforeClassSetup() {
+  public static void testBaseBeforeClassSetup() throws IOException {
     assert staticTemp == null;
     staticTemp = ToolHelper.getTemporaryFolderForTest();
+    staticTemp.create();
   }
 
   @AfterClass
   public static void testBaseBeforeClassTearDown() {
+    assert staticTemp != null;
+    staticTemp.delete();
     staticTemp = null;
   }
 
@@ -197,6 +202,35 @@
                 }));
   }
 
+  protected static <S, T, U> BiFunction<S, T, U> memoizeBiFunction(
+      ThrowableBiFunction<S, T, U> fn) {
+    class Pair {
+      final S first;
+      final T second;
+
+      public Pair(S first, T second) {
+        this.first = first;
+        this.second = second;
+      }
+
+      @Override
+      public boolean equals(Object obj) {
+        if (!(obj instanceof Pair)) {
+          return false;
+        }
+        Pair other = (Pair) obj;
+        return Objects.equals(first, other.first) && Objects.equals(second, other.second);
+      }
+
+      @Override
+      public int hashCode() {
+        return Objects.hash(first, second);
+      }
+    }
+    final Function<Pair, U> memoizedFn = memoizeFunction(pair -> fn.apply(pair.first, pair.second));
+    return (a, b) -> memoizedFn.apply(new Pair(a, b));
+  }
+
   /**
    * Check if tests should also run Proguard when applicable.
    */
diff --git a/src/test/java/com/android/tools/r8/ThrowableBiFunction.java b/src/test/java/com/android/tools/r8/ThrowableBiFunction.java
new file mode 100644
index 0000000..4ef9ef2
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/ThrowableBiFunction.java
@@ -0,0 +1,23 @@
+// Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+package com.android.tools.r8;
+
+import java.util.function.Function;
+
+public interface ThrowableBiFunction<Formal1, Formal2, Return> {
+  Return apply(Formal1 formal1, Formal2 formal2) throws Throwable;
+
+  default <T extends Throwable> Return applyWithHandler(
+      Formal1 formal1, Formal2 formal2, Function<Throwable, T> handler) throws T {
+    try {
+      return apply(formal1, formal2);
+    } catch (Throwable e) {
+      throw handler.apply(e);
+    }
+  }
+
+  default Return applyWithRuntimeException(Formal1 formal1, Formal2 formal2) {
+    return applyWithHandler(formal1, formal2, RuntimeException::new);
+  }
+}
diff --git a/src/test/java/com/android/tools/r8/desugar/NestAccessControl/NestAccessControlTest.java b/src/test/java/com/android/tools/r8/desugar/NestAccessControl/NestAccessControlTest.java
index 2fb0a08..e43594c 100644
--- a/src/test/java/com/android/tools/r8/desugar/NestAccessControl/NestAccessControlTest.java
+++ b/src/test/java/com/android/tools/r8/desugar/NestAccessControl/NestAccessControlTest.java
@@ -6,12 +6,30 @@
 
 import static com.android.tools.r8.utils.FileUtils.JAR_EXTENSION;
 import static org.hamcrest.core.StringContains.containsString;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 
+import com.android.tools.r8.CompilationFailedException;
+import com.android.tools.r8.D8TestCompileResult;
+import com.android.tools.r8.R8TestCompileResult;
+import com.android.tools.r8.R8TestRunResult;
 import com.android.tools.r8.TestBase;
 import com.android.tools.r8.TestParameters;
 import com.android.tools.r8.TestParametersCollection;
+import com.android.tools.r8.TestRuntime.CfVm;
 import com.android.tools.r8.ToolHelper;
+import com.android.tools.r8.graph.DexClass;
+import com.android.tools.r8.utils.AndroidApiLevel;
+import com.android.tools.r8.utils.StringUtils;
+import com.android.tools.r8.utils.codeinspector.CodeInspector;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.util.function.BiFunction;
+import java.util.function.Function;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
@@ -20,13 +38,58 @@
 @RunWith(Parameterized.class)
 public class NestAccessControlTest extends TestBase {
 
-  static final String EXAMPLE_DIR = ToolHelper.EXAMPLES_JAVA11_BUILD_DIR;
+  private static final Path EXAMPLE_DIR = Paths.get(ToolHelper.EXAMPLES_JAVA11_BUILD_DIR);
+  private static final Path JAR = EXAMPLE_DIR.resolve("nestHostExample" + JAR_EXTENSION);
+
+  private static final String EXPECTED = StringUtils.lines(
+      "fieldstaticFieldstaticFieldhostMethodstaticHostMethodstaticHostMethodnest1SFieldstaticNest1SFieldstaticNest1SFieldnest1SMethodstaticNest1SMethodstaticNest1SMethodnest2SFieldstaticNest2SFieldstaticNest2SFieldnest2SMethodstaticNest2SMethodstaticNest2SMethodnest1Fieldnest1Methodnest2Fieldnest2Method",
+      "fieldstaticFieldstaticFieldhostMethodstaticHostMethodstaticHostMethodnest1SFieldstaticNest1SFieldstaticNest1SFieldnest1SMethodstaticNest1SMethodstaticNest1SMethodnest2SFieldstaticNest2SFieldstaticNest2SFieldnest2SMethodstaticNest2SMethodstaticNest2SMethodnest1Fieldnest1Methodnest2Fieldnest2Method",
+      "fieldstaticFieldstaticFieldhostMethodstaticHostMethodstaticHostMethodnest1SFieldstaticNest1SFieldstaticNest1SFieldnest1SMethodstaticNest1SMethodstaticNest1SMethodnest2SFieldstaticNest2SFieldstaticNest2SFieldnest2SMethodstaticNest2SMethodstaticNest2SMethodnest1Fieldnest1Methodnest2Fieldnest2Method",
+      "fieldstaticFieldstaticFieldhostMethodstaticHostMethodstaticHostMethodnest1SFieldstaticNest1SFieldstaticNest1SFieldnest1SMethodstaticNest1SMethodstaticNest1SMethodnest2SFieldstaticNest2SFieldstaticNest2SFieldnest2SMethodstaticNest2SMethodstaticNest2SMethodnest1Fieldnest1Methodnest2Fieldnest2Method",
+      "staticInterfaceMethodstaticStaticInterfaceMethod",
+      "staticInterfaceMethodstaticStaticInterfaceMethod",
+      "staticInterfaceMethodstaticStaticInterfaceMethod",
+      "staticInterfaceMethodstaticStaticInterfaceMethod");
+  private static final ImmutableMap<String, String> MAIN_CLASSES_AND_EXPECTED_RESULTS = ImmutableMap
+      .of(
+          "BasicNestHostWithInnerClass", StringUtils.lines(
+              "nest1SFieldstaticNestFieldstaticNestFieldnestMethodstaticNestMethodstaticNestMethod",
+              "fieldstaticFieldstaticNestFieldhostMethodstaticHostMethodstaticNestMethod"),
+          "BasicNestHostWithAnonymousInnerClass", StringUtils
+              .lines("fieldstaticFieldstaticFieldhostMethodstaticHostMethodstaticHostMethod"),
+          "NestHostExample", EXPECTED);
+
+  private static Function<AndroidApiLevel, D8TestCompileResult> d8CompilationResult =
+      memoizeFunction(NestAccessControlTest::compileD8);
+
+  private static BiFunction<Backend, AndroidApiLevel, R8TestCompileResult> r8CompilationResult =
+      memoizeBiFunction(NestAccessControlTest::compileR8);
+
+  private static D8TestCompileResult compileD8(AndroidApiLevel minApi)
+      throws CompilationFailedException {
+    return testForD8(getStaticTemp()).addProgramFiles(JAR).setMinApi(minApi).compile();
+  }
+
+  private static R8TestCompileResult compileR8(Backend backend, AndroidApiLevel minApi)
+      throws CompilationFailedException {
+    return testForR8(getStaticTemp(), backend)
+        .noTreeShaking()
+        .noMinification()
+        .addKeepAllAttributes()
+        .addProgramFiles(JAR)
+        .setMinApi(minApi)
+        .compile();
+  }
 
   private final TestParameters parameters;
 
   @Parameters(name = "{0}")
   public static TestParametersCollection data() {
-    return getTestParameters().withDexRuntimes().build();
+    return getTestParameters()
+        .withCfRuntimesStartingFromIncluding(CfVm.JDK11)
+        .withDexRuntimes()
+        .withAllApiLevels()
+        .build();
   }
 
   public NestAccessControlTest(TestParameters parameters) {
@@ -34,12 +97,61 @@
   }
 
   @Test
-  public void testNestAccessControl() throws Exception {
-    testForD8()
-        .addProgramFiles(Paths.get(EXAMPLE_DIR, "nestHostExample" + JAR_EXTENSION))
-        .setMinApi(parameters.getRuntime())
-        .compile()
-        .run(parameters.getRuntime(), "nestHostExample.NestHostExample")
-        .assertFailureWithErrorThatMatches(containsString("IllegalAccessError"));
+  public void testJavaAndD8() throws Exception {
+    for (ImmutableMap.Entry<String,String> entry : MAIN_CLASSES_AND_EXPECTED_RESULTS.entrySet()) {
+      if (parameters.isCfRuntime()) {
+        testForJvm()
+            .addProgramFiles(JAR)
+            .run(parameters.getRuntime(), "nestHostExample."+ entry.getKey())
+            .assertSuccessWithOutput(entry.getValue());
+      } else {
+        assert parameters.isDexRuntime();
+        d8CompilationResult
+            .apply(parameters.getApiLevel())
+            .run(parameters.getRuntime(), "nestHostExample."+ entry.getKey())
+            // TODO(b/130529390): Assert expected once fixed.
+            .assertFailureWithErrorThatMatches(containsString("IllegalAccessError"));
+      }
+    }
+  }
+
+  @Test
+  public void testR8() throws Exception {
+    for (ImmutableMap.Entry<String,String> entry : MAIN_CLASSES_AND_EXPECTED_RESULTS.entrySet()) {
+      R8TestRunResult result =
+          r8CompilationResult
+              .apply(parameters.getBackend(), parameters.getApiLevel())
+              .run(parameters.getRuntime(), "nestHostExample."+ entry.getKey());
+      if (parameters.isCfRuntime()) {
+        result.assertSuccessWithOutput(entry.getValue());
+        result.inspect(NestAccessControlTest::checkNestMateAttributes);
+      } else {
+        // TODO(b/130529390): Assert expected once fixed.
+        result.assertFailureWithErrorThatMatches(containsString("IllegalAccessError"));
+      }
+    }
+  }
+
+  private static void checkNestMateAttributes(CodeInspector inspector) {
+    assertEquals(11, inspector.allClasses().size());
+    ImmutableSet<String> outerClassNames =
+        ImmutableSet.of(
+            "NestHostExample",
+            "BasicNestHostWithInnerClass",
+            "BasicNestHostWithAnonymousInnerClass");
+    inspector.forAllClasses(
+        classSubject -> {
+          DexClass dexClass = classSubject.getDexClass();
+          assertTrue(dexClass.isInANest());
+          if (outerClassNames.contains(dexClass.type.getName())) {
+            assertNull(dexClass.getNestHostClassAttribute());
+            assertFalse(dexClass.getNestMembersClassAttributes().isEmpty());
+          } else {
+            assertTrue(dexClass.getNestMembersClassAttributes().isEmpty());
+            assertTrue(
+                outerClassNames.contains(
+                    dexClass.getNestHostClassAttribute().getNestHost().getName()));
+          }
+        });
   }
 }
diff --git a/src/test/java/com/android/tools/r8/desugar/NestAccessControl/NestAttributesTest.java b/src/test/java/com/android/tools/r8/desugar/NestAccessControl/NestAttributesTest.java
deleted file mode 100644
index 208e0ab..0000000
--- a/src/test/java/com/android/tools/r8/desugar/NestAccessControl/NestAttributesTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-package com.android.tools.r8.desugar.NestAccessControl;
-
-import static com.android.tools.r8.utils.FileUtils.JAR_EXTENSION;
-import static junit.framework.TestCase.assertEquals;
-import static junit.framework.TestCase.assertNull;
-import static junit.framework.TestCase.assertTrue;
-import static org.junit.Assert.assertFalse;
-
-import com.android.tools.r8.TestBase;
-import com.android.tools.r8.TestParameters;
-import com.android.tools.r8.TestParametersCollection;
-import com.android.tools.r8.TestRuntime.CfVm;
-import com.android.tools.r8.ToolHelper;
-import com.android.tools.r8.graph.DexClass;
-import com.google.common.collect.ImmutableSet;
-import java.nio.file.Paths;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
-
-@RunWith(Parameterized.class)
-public class NestAttributesTest extends TestBase {
-
-  static final String EXAMPLE_DIR = ToolHelper.EXAMPLES_JAVA11_BUILD_DIR;
-
-  private final TestParameters parameters;
-
-  @Parameters(name = "{0}")
-  public static TestParametersCollection data() {
-    return getTestParameters().withCfRuntimesStartingFromIncluding(CfVm.JDK11).build();
-  }
-
-  public NestAttributesTest(TestParameters parameters) {
-    this.parameters = parameters;
-  }
-
-  @Test
-  public void testNestMatesAttributes() throws Exception {
-    testForR8(parameters.getBackend())
-        .addProgramFiles(Paths.get(EXAMPLE_DIR, "nestHostExample" + JAR_EXTENSION))
-        .addKeepAllClassesRule()
-        .compile()
-        .inspect(
-            inspector -> {
-              assertEquals(11, inspector.allClasses().size());
-              ImmutableSet<String> outerClassNames =
-                  ImmutableSet.of(
-                      "NestHostExample",
-                      "BasicNestHostWithInnerClass",
-                      "BasicNestHostWithAnonymousInnerClass");
-              inspector.forAllClasses(
-                  classSubject -> {
-                    DexClass dexClass = classSubject.getDexClass();
-                    assertTrue(dexClass.isInANest());
-                    if (outerClassNames.contains(dexClass.type.getName())) {
-                      assertNull(dexClass.getNestHostClassAttribute());
-                      assertFalse(dexClass.getNestMembersClassAttributes().isEmpty());
-                    } else {
-                      assertTrue(dexClass.getNestMembersClassAttributes().isEmpty());
-                      assertTrue(
-                          outerClassNames.contains(
-                              dexClass.getNestHostClassAttribute().getNestHost().getName()));
-                    }
-                  });
-            });
-  }
-}