Add more ifz tests using Kotlin !! and ?. operators.
Bug: 120649619
Change-Id: I47e92d1a52eab248a4af24db59f7de6949e0bfd3
diff --git a/src/test/java/com/android/tools/r8/kotlin/SimplifyIfNotNullKotlinTest.java b/src/test/java/com/android/tools/r8/kotlin/SimplifyIfNotNullKotlinTest.java
index 12fdaf9..779d8b1 100644
--- a/src/test/java/com/android/tools/r8/kotlin/SimplifyIfNotNullKotlinTest.java
+++ b/src/test/java/com/android/tools/r8/kotlin/SimplifyIfNotNullKotlinTest.java
@@ -73,4 +73,26 @@
});
}
+ @Test
+ public void test_example3() throws Exception {
+ final TestKotlinClass ex3 = new TestKotlinClass("non_null.Example3Kt");
+ final MethodSignature testMethodSignature =
+ new MethodSignature("neverThrowNPE", "void", ImmutableList.of("non_null.Foo"));
+
+ final String mainClassName = ex3.getClassName();
+ final String extraRules = keepAllMembers(mainClassName);
+ runTest(FOLDER, mainClassName, extraRules, app -> {
+ CodeInspector codeInspector = new CodeInspector(app);
+ ClassSubject clazz = checkClassIsKept(codeInspector, ex3.getClassName());
+
+ MethodSubject testMethod = checkMethodIsKept(clazz, testMethodSignature);
+ DexCode dexCode = getDexCode(testMethod);
+ long count = Arrays.stream(dexCode.instructions)
+ .filter(SimplifyIfNotNullKotlinTest::isIf).count();
+ // !! operator inside explicit null check should be gone.
+ // One explicit null-check as well as 4 bar? accesses.
+ assertEquals(5, count);
+ });
+ }
+
}
diff --git a/src/test/kotlinR8TestResources/non_null/example3.kt b/src/test/kotlinR8TestResources/non_null/example3.kt
new file mode 100644
index 0000000..9df7b20
--- /dev/null
+++ b/src/test/kotlinR8TestResources/non_null/example3.kt
@@ -0,0 +1,39 @@
+// Copyright (c) 2018, 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 non_null
+
+class Foo(val tag: String) {
+ var bar: Bar? = null
+ fun foo() {
+ println("Foo::$tag")
+ }
+}
+
+class Bar(var bar1: String?, var bar2: String?, var bar3: String?) {
+ constructor() : this(null, null, null)
+
+ fun bar() {
+ println("Bar::$bar1::$bar2::$bar3")
+ }
+}
+
+fun neverThrowNPE(a: Foo?) {
+ if (a != null) {
+ a!!.foo()
+ a.bar?.bar1 = a.tag + "$1"
+ a.bar?.bar2 = a.tag + "$2"
+ a.bar?.bar3 = a.tag + "$3"
+ a.bar?.bar()
+ } else {
+ println("-null-")
+ }
+}
+
+fun main(args: Array<String>) {
+ val foo = Foo("tag")
+ neverThrowNPE(foo)
+ foo.bar = Bar()
+ neverThrowNPE(foo)
+ neverThrowNPE(null)
+}