From d00bb8e4e3c3d0210860a8c84423449d7d5e7362 Mon Sep 17 00:00:00 2001 From: Som Snytt Date: Tue, 1 Oct 2024 22:33:15 -0700 Subject: [PATCH] Always rewrite empty List() to Nil --- .../tools/dotc/transform/ArrayApply.scala | 2 +- .../tools/backend/jvm/ArrayApplyOptTest.scala | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala b/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala index 98ca8f2e2b5b..1a6ec307e289 100644 --- a/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala +++ b/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala @@ -76,7 +76,7 @@ class ArrayApply extends MiniPhase { tree.args match // (a, b, c) ~> new ::(a, new ::(b, new ::(c, Nil))) but only for reference types case StripAscription(Apply(wrapArrayMeth, List(StripAscription(rest: JavaSeqLiteral)))) :: Nil - if defn.WrapArrayMethods().contains(wrapArrayMeth.symbol) => + if rest.elems.isEmpty || defn.WrapArrayMethods().contains(wrapArrayMeth.symbol) => Some(rest.elems) case _ => None else None diff --git a/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala b/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala index c99de8fcf956..a1fe40e58b56 100644 --- a/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala +++ b/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala @@ -161,6 +161,42 @@ class ArrayApplyOptTest extends DottyBytecodeTest { } } + @Test def emptyListApplyAvoidsIntermediateArray = + checkApplyAvoidsIntermediateArray("EmptyList"): + """import scala.collection.immutable.Nil + |class Foo { + | def meth1: List[String] = List() + | def meth2: List[String] = Nil + |} + """.stripMargin + + @Test def emptyRefListApplyAvoidsIntermediateArray = + checkApplyAvoidsIntermediateArray("EmptyListOfRef"): + """import scala.collection.immutable.Nil + |class Foo { + | def meth1: List[String] = List[String]() + | def meth2: List[String] = Nil + |} + """.stripMargin + + @Test def emptyPrimitiveListApplyAvoidsIntermediateArray = + checkApplyAvoidsIntermediateArray("EmptyListOfInt"): + """import scala.collection.immutable.Nil + |class Foo { + | def meth1: List[Int] = List() + | def meth2: List[Int] = Nil + |} + """.stripMargin + + @Test def primitiveListApplyAvoidsIntermediateArray = + checkApplyAvoidsIntermediateArray("ListOfInt"): + """import scala.collection.immutable.{ ::, Nil } + |class Foo { + | def meth1: List[Int] = List(1, 2, 3) + | def meth2: List[Int] = new ::(1, new ::(2, new ::(3, Nil))) + |} + """.stripMargin + @Test def testListApplyAvoidsIntermediateArray = { checkApplyAvoidsIntermediateArray("List"): """import scala.collection.immutable.{ ::, Nil }