Skip to content

Commit

Permalink
Always rewrite empty List() to Nil (#21689)
Browse files Browse the repository at this point in the history
`List[String]()` was OK but not `List()` with `Nothing` inferred, which
is how people write it.

Follow-up to #17166

Noticed at scala/scala#10876
  • Loading branch information
sjrd authored Oct 2, 2024
2 parents 8244d67 + d00bb8e commit c332766
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/transform/ArrayApply.scala
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class ArrayApply extends MiniPhase {
tree.args match
// <List or Seq>(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
Expand Down
36 changes: 36 additions & 0 deletions compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down

0 comments on commit c332766

Please sign in to comment.