Test that subtypes can be injected after R8 compilation with the right keep rules

Bug: 134649660, 145271928
Change-Id: Ia92247f954792e6bf430525a67c13c097bd5fa3c
diff --git a/src/test/java/com/android/tools/r8/TestCompileResult.java b/src/test/java/com/android/tools/r8/TestCompileResult.java
index 13059f6..e3f52a1 100644
--- a/src/test/java/com/android/tools/r8/TestCompileResult.java
+++ b/src/test/java/com/android/tools/r8/TestCompileResult.java
@@ -126,6 +126,14 @@
       throws ExecutionException, IOException {
     assert getBackend() == runtime.getBackend();
     ClassSubject mainClassSubject = inspector().clazz(mainClass);
+    if (!mainClassSubject.isPresent()) {
+      for (Path classpathFile : additionalRunClassPath) {
+        mainClassSubject = new CodeInspector(classpathFile).clazz(mainClass);
+        if (mainClassSubject.isPresent()) {
+          break;
+        }
+      }
+    }
     assertThat("Did you forget a keep rule for the main method?", mainClassSubject, isPresent());
     if (runtime.isDex()) {
       return runArt(runtime, additionalRunClassPath, mainClassSubject.getFinalName(), args);
diff --git a/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/AbstractClassAlsoImplementedByMissingClassTest.java b/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/AbstractClassAlsoImplementedByMissingClassTest.java
new file mode 100644
index 0000000..4a7791a
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/AbstractClassAlsoImplementedByMissingClassTest.java
@@ -0,0 +1,139 @@
+// 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.ir.optimize.functionalinterfaces;
+
+import static com.android.tools.r8.utils.codeinspector.Matchers.isPresent;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.StringContains.containsString;
+
+import com.android.tools.r8.NeverClassInline;
+import com.android.tools.r8.TestBase;
+import com.android.tools.r8.TestParameters;
+import com.android.tools.r8.TestParametersCollection;
+import com.android.tools.r8.utils.codeinspector.ClassSubject;
+import com.android.tools.r8.utils.codeinspector.CodeInspector;
+import java.nio.file.Path;
+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 AbstractClassAlsoImplementedByMissingClassTest extends TestBase {
+
+  private final TestParameters parameters;
+
+  @Parameters(name = "{0}")
+  public static TestParametersCollection data() {
+    return getTestParameters().withAllRuntimesAndApiLevels().build();
+  }
+
+  public AbstractClassAlsoImplementedByMissingClassTest(TestParameters parameters) {
+    this.parameters = parameters;
+  }
+
+  /**
+   * Tests that it is possible to provide an implementation of an abstract class after the program
+   * has been compiled with R8, as long as the abstract class and its methods have been kept.
+   */
+  @Test
+  public void test() throws Exception {
+    Path r8Out =
+        testForR8(parameters.getBackend())
+            // C is not visible to the R8 compilation.
+            .addProgramClasses(TestClass.class, A.class, B.class)
+            // Helper is added on the classpath such that R8 doesn't know what it does.
+            .addClasspathClasses(Helper.class)
+            .addKeepMainRule(TestClass.class)
+            // Keeping A, A.<init>(), and A.kept() should make it possible to provide an
+            // implementation
+            // of A after the R8 compilation.
+            .addKeepRules(
+                "-keep class " + A.class.getTypeName() + " { void <init>(); void kept(); }")
+            .enableClassInliningAnnotations()
+            .setMinApi(parameters.getApiLevel())
+            .compile()
+            .inspect(this::inspect)
+            .writeToZip();
+
+    testForRuntime(parameters)
+        .addProgramClasses(C.class, Helper.class)
+        .addRunClasspathFiles(r8Out)
+        .run(parameters.getRuntime(), TestClass.class)
+        .assertFailureWithErrorThatMatches(containsString(ClassCastException.class.getTypeName()));
+  }
+
+  private void inspect(CodeInspector inspector) {
+    ClassSubject aClassSubject = inspector.clazz(A.class);
+    assertThat(aClassSubject.uniqueMethodWithName("kept"), isPresent());
+
+    ClassSubject bClassSubject = inspector.clazz(B.class);
+    assertThat(bClassSubject.uniqueMethodWithName("kept"), isPresent());
+
+    // A.notKept() and B.notKept() should not be present, because the only invoke instruction
+    // targeting A.notKept() should have been inlined.
+    assertThat(aClassSubject.uniqueMethodWithName("notKept"), not(isPresent()));
+    assertThat(bClassSubject.uniqueMethodWithName("notKept"), not(isPresent()));
+  }
+
+  static class TestClass {
+
+    public static void main(String[] args) {
+      // Casting `notAlwaysB` to B and invoking B.kept() would lead to a ClassCastException.
+      A notAlwaysB = System.currentTimeMillis() >= 0 ? Helper.getInstance() : new B();
+      notAlwaysB.kept();
+
+      // We should be able to inline A.notKept() when the receiver is guaranteed to be B.
+      A alwaysB = new B();
+      alwaysB.notKept();
+
+      System.out.println("The end");
+    }
+  }
+
+  abstract static class A {
+
+    abstract void kept();
+
+    abstract void notKept();
+  }
+
+  @NeverClassInline
+  static class B extends A {
+
+    @Override
+    public void kept() {
+      throw new RuntimeException();
+    }
+
+    @Override
+    public void notKept() {
+      System.out.println(" world!");
+    }
+  }
+
+  // Only declarations are visible via the classpath.
+  static class Helper {
+
+    static A getInstance() {
+      return new C();
+    }
+  }
+
+  // Not visible during the R8 compilation.
+  static class C extends A {
+
+    @Override
+    public void kept() {
+      System.out.print("Hello");
+    }
+
+    @Override
+    public void notKept() {
+      throw new RuntimeException();
+    }
+  }
+}
diff --git a/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/AbstractClassOnlyImplementedByMissingClassTest.java b/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/AbstractClassOnlyImplementedByMissingClassTest.java
new file mode 100644
index 0000000..14b1607
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/AbstractClassOnlyImplementedByMissingClassTest.java
@@ -0,0 +1,87 @@
+// 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.ir.optimize.functionalinterfaces;
+
+import com.android.tools.r8.TestBase;
+import com.android.tools.r8.TestParameters;
+import com.android.tools.r8.TestParametersCollection;
+import java.nio.file.Path;
+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 AbstractClassOnlyImplementedByMissingClassTest extends TestBase {
+
+  private final TestParameters parameters;
+
+  @Parameters(name = "{0}")
+  public static TestParametersCollection data() {
+    return getTestParameters().withAllRuntimesAndApiLevels().build();
+  }
+
+  public AbstractClassOnlyImplementedByMissingClassTest(TestParameters parameters) {
+    this.parameters = parameters;
+  }
+
+  /**
+   * Tests that it is possible to provide an implementation of an abstract class after the program
+   * has been compiled with R8, as long as the abstract class and its methods have been kept.
+   */
+  @Test
+  public void test() throws Exception {
+    Path r8Out =
+        testForR8(parameters.getBackend())
+            // B is not visible to the R8 compilation.
+            .addProgramClasses(TestClass.class, A.class)
+            // Helper is added on the classpath such that R8 doesn't know what it does.
+            .addClasspathClasses(Helper.class)
+            .addKeepMainRule(TestClass.class)
+            // Keeping A, A.<init>(), and A.m() should make it possible to provide an implementation
+            // of
+            // A after the R8 compilation.
+            .addKeepRules("-keep class " + A.class.getTypeName() + " { void <init>(); void m(); }")
+            .setMinApi(parameters.getApiLevel())
+            .compile()
+            .writeToZip();
+
+    testForRuntime(parameters)
+        .addProgramClasses(B.class, Helper.class)
+        .addRunClasspathFiles(r8Out)
+        .run(parameters.getRuntime(), TestClass.class)
+        .assertSuccessWithOutputLines("Hello world!", "The end");
+  }
+
+  static class TestClass {
+
+    public static void main(String[] args) {
+      Helper.getInstance().m();
+      System.out.println("The end");
+    }
+  }
+
+  abstract static class A {
+
+    abstract void m();
+  }
+
+  // Only declarations are visible via the classpath.
+  static class Helper {
+
+    static A getInstance() {
+      return new B();
+    }
+  }
+
+  // Not visible during the R8 compilation.
+  static class B extends A {
+
+    @Override
+    public void m() {
+      System.out.println("Hello world!");
+    }
+  }
+}
diff --git a/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/InterfaceAlsoImplementedByMissingClassTest.java b/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/InterfaceAlsoImplementedByMissingClassTest.java
new file mode 100644
index 0000000..18c5225
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/InterfaceAlsoImplementedByMissingClassTest.java
@@ -0,0 +1,135 @@
+// 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.ir.optimize.functionalinterfaces;
+
+import static com.android.tools.r8.utils.codeinspector.Matchers.isPresent;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import com.android.tools.r8.NeverClassInline;
+import com.android.tools.r8.TestBase;
+import com.android.tools.r8.TestParameters;
+import com.android.tools.r8.TestParametersCollection;
+import com.android.tools.r8.utils.codeinspector.ClassSubject;
+import com.android.tools.r8.utils.codeinspector.CodeInspector;
+import java.nio.file.Path;
+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 InterfaceAlsoImplementedByMissingClassTest extends TestBase {
+
+  private final TestParameters parameters;
+
+  @Parameters(name = "{0}")
+  public static TestParametersCollection data() {
+    return getTestParameters().withAllRuntimesAndApiLevels().build();
+  }
+
+  public InterfaceAlsoImplementedByMissingClassTest(TestParameters parameters) {
+    this.parameters = parameters;
+  }
+
+  /**
+   * Tests that it is possible to provide an implementation of an interface after the program has
+   * been compiled with R8, as long as the interface and its methods have been kept.
+   */
+  @Test
+  public void test() throws Exception {
+    Path r8Out =
+        testForR8(parameters.getBackend())
+            // B is not visible to the R8 compilation.
+            .addProgramClasses(TestClass.class, I.class, A.class)
+            // Helper is added on the classpath such that R8 doesn't know what it does.
+            .addClasspathClasses(Helper.class)
+            .addKeepMainRule(TestClass.class)
+            // Keeping I and I.kept() should make it possible to provide an implementation of
+            // I after the R8 compilation.
+            .addKeepRules("-keep class " + I.class.getTypeName() + " { void kept(); }")
+            .enableClassInliningAnnotations()
+            .setMinApi(parameters.getApiLevel())
+            .compile()
+            .inspect(this::inspect)
+            .writeToZip();
+
+    testForRuntime(parameters)
+        .addProgramClasses(B.class, Helper.class)
+        .addRunClasspathFiles(r8Out)
+        .run(parameters.getRuntime(), TestClass.class)
+        .assertSuccessWithOutputLines("Hello world!", "The end");
+  }
+
+  private void inspect(CodeInspector inspector) {
+    ClassSubject iClassSubject = inspector.clazz(I.class);
+    assertThat(iClassSubject.uniqueMethodWithName("kept"), isPresent());
+
+    ClassSubject aClassSubject = inspector.clazz(A.class);
+    assertThat(aClassSubject.uniqueMethodWithName("kept"), isPresent());
+
+    // TODO(b/134649660): I.notKept() and A.notKept() should not be present, because the only invoke
+    //  instruction targeting I.notKept() should have been inlined.
+    assertThat(iClassSubject.uniqueMethodWithName("notKept"), isPresent());
+    assertThat(aClassSubject.uniqueMethodWithName("notKept"), isPresent());
+  }
+
+  static class TestClass {
+
+    public static void main(String[] args) {
+      // Casting `notAlwaysA` to A and invoking A.kept() would lead to a ClassCastException.
+      I notAlwaysA = System.currentTimeMillis() >= 0 ? Helper.getInstance() : new A();
+      notAlwaysA.kept();
+
+      // We should be able to inline I.notKept() when the receiver is guaranteed to be A.
+      I alwaysA = new A();
+      alwaysA.notKept();
+
+      System.out.println("The end");
+    }
+  }
+
+  interface I {
+
+    void kept();
+
+    void notKept();
+  }
+
+  @NeverClassInline
+  static class A implements I {
+
+    @Override
+    public void kept() {
+      throw new RuntimeException();
+    }
+
+    @Override
+    public void notKept() {
+      System.out.println(" world!");
+    }
+  }
+
+  // Only declarations are visible via the classpath.
+  static class Helper {
+
+    static I getInstance() {
+      return new B();
+    }
+  }
+
+  // Not visible during the R8 compilation.
+  static class B implements I {
+
+    @Override
+    public void kept() {
+      System.out.print("Hello");
+    }
+
+    @Override
+    public void notKept() {
+      throw new RuntimeException();
+    }
+  }
+}
diff --git a/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/InterfaceOnlyImplementedByMissingClassTest.java b/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/InterfaceOnlyImplementedByMissingClassTest.java
new file mode 100644
index 0000000..01a21a0
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/ir/optimize/functionalinterfaces/InterfaceOnlyImplementedByMissingClassTest.java
@@ -0,0 +1,88 @@
+// 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.ir.optimize.functionalinterfaces;
+
+import com.android.tools.r8.TestBase;
+import com.android.tools.r8.TestParameters;
+import com.android.tools.r8.TestParametersCollection;
+import java.nio.file.Path;
+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 InterfaceOnlyImplementedByMissingClassTest extends TestBase {
+
+  private final TestParameters parameters;
+
+  @Parameters(name = "{0}")
+  public static TestParametersCollection data() {
+    return getTestParameters().withAllRuntimesAndApiLevels().build();
+  }
+
+  public InterfaceOnlyImplementedByMissingClassTest(TestParameters parameters) {
+    this.parameters = parameters;
+  }
+
+  /**
+   * Tests that it is possible to provide an implementation of an interface after the program has
+   * been compiled with R8, as long as the interface and its methods have been kept.
+   */
+  @Test
+  public void test() throws Exception {
+    Path r8Out =
+        testForR8(parameters.getBackend())
+            // A is not visible to the R8 compilation.
+            .addProgramClasses(TestClass.class, I.class)
+            // Helper is added on the classpath such that R8 doesn't know what it does.
+            .addClasspathClasses(Helper.class)
+            .addKeepMainRule(TestClass.class)
+            // Keeping I and I.m() should make it possible to provide an implementation of I after
+            // the
+            // R8 compilation.
+            .addKeepRules("-keep class " + I.class.getTypeName() + " { void m(); }")
+            .setMinApi(parameters.getApiLevel())
+            .compile()
+            .writeToZip();
+    ;
+
+    testForRuntime(parameters)
+        .addProgramClasses(A.class, Helper.class)
+        .addRunClasspathFiles(r8Out)
+        .run(parameters.getRuntime(), TestClass.class)
+        .assertSuccessWithOutputLines("Hello world!", "The end");
+  }
+
+  static class TestClass {
+
+    public static void main(String[] args) {
+      Helper.getInstance().m();
+      System.out.println("The end");
+    }
+  }
+
+  interface I {
+
+    void m();
+  }
+
+  // Only declarations are visible via the classpath.
+  static class Helper {
+
+    static I getInstance() {
+      return new A();
+    }
+  }
+
+  // Not visible during the R8 compilation.
+  static class A implements I {
+
+    @Override
+    public void m() {
+      System.out.println("Hello world!");
+    }
+  }
+}