Skip to content

Commit c332766

Browse files
authored
Always rewrite empty List() to Nil (#21689)
`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
2 parents 8244d67 + d00bb8e commit c332766

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

Diff for: compiler/src/dotty/tools/dotc/transform/ArrayApply.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ class ArrayApply extends MiniPhase {
7676
tree.args match
7777
// <List or Seq>(a, b, c) ~> new ::(a, new ::(b, new ::(c, Nil))) but only for reference types
7878
case StripAscription(Apply(wrapArrayMeth, List(StripAscription(rest: JavaSeqLiteral)))) :: Nil
79-
if defn.WrapArrayMethods().contains(wrapArrayMeth.symbol) =>
79+
if rest.elems.isEmpty || defn.WrapArrayMethods().contains(wrapArrayMeth.symbol) =>
8080
Some(rest.elems)
8181
case _ => None
8282
else None

Diff for: compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala

+36
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,42 @@ class ArrayApplyOptTest extends DottyBytecodeTest {
161161
}
162162
}
163163

164+
@Test def emptyListApplyAvoidsIntermediateArray =
165+
checkApplyAvoidsIntermediateArray("EmptyList"):
166+
"""import scala.collection.immutable.Nil
167+
|class Foo {
168+
| def meth1: List[String] = List()
169+
| def meth2: List[String] = Nil
170+
|}
171+
""".stripMargin
172+
173+
@Test def emptyRefListApplyAvoidsIntermediateArray =
174+
checkApplyAvoidsIntermediateArray("EmptyListOfRef"):
175+
"""import scala.collection.immutable.Nil
176+
|class Foo {
177+
| def meth1: List[String] = List[String]()
178+
| def meth2: List[String] = Nil
179+
|}
180+
""".stripMargin
181+
182+
@Test def emptyPrimitiveListApplyAvoidsIntermediateArray =
183+
checkApplyAvoidsIntermediateArray("EmptyListOfInt"):
184+
"""import scala.collection.immutable.Nil
185+
|class Foo {
186+
| def meth1: List[Int] = List()
187+
| def meth2: List[Int] = Nil
188+
|}
189+
""".stripMargin
190+
191+
@Test def primitiveListApplyAvoidsIntermediateArray =
192+
checkApplyAvoidsIntermediateArray("ListOfInt"):
193+
"""import scala.collection.immutable.{ ::, Nil }
194+
|class Foo {
195+
| def meth1: List[Int] = List(1, 2, 3)
196+
| def meth2: List[Int] = new ::(1, new ::(2, new ::(3, Nil)))
197+
|}
198+
""".stripMargin
199+
164200
@Test def testListApplyAvoidsIntermediateArray = {
165201
checkApplyAvoidsIntermediateArray("List"):
166202
"""import scala.collection.immutable.{ ::, Nil }

0 commit comments

Comments
 (0)