Skip to content

Commit 9e27ed2

Browse files
committed
Constant fold String.==
1 parent 8aae979 commit 9e27ed2

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

compiler/src/dotty/tools/dotc/typer/ConstFold.scala

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,11 @@ object ConstFold:
163163
case nme.MOD => Constant(x.doubleValue % y.doubleValue)
164164
case _ => null
165165
}
166+
private def foldStringOp(op: Name, x: Constant, y: Constant): Constant = op match {
167+
case nme.ADD => Constant(x.stringValue + y.stringValue)
168+
case nme.EQ => Constant(x.stringValue == y.stringValue)
169+
case _ => null
170+
}
166171

167172
private def foldBinop(op: Name, x: Constant, y: Constant): Constant =
168173
val optag =
@@ -176,7 +181,7 @@ object ConstFold:
176181
case LongTag => foldLongOp(op, x, y)
177182
case FloatTag => foldFloatOp(op, x, y)
178183
case DoubleTag => foldDoubleOp(op, x, y)
179-
case StringTag if op == nme.ADD => Constant(x.stringValue + y.stringValue)
184+
case StringTag => foldStringOp(op, x, y)
180185
case _ => null
181186
catch case ex: ArithmeticException => null // the code will crash at runtime,
182187
// but that is better than the

tests/pos/i10521.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
transparent inline def default(inline name: String): Any =
2+
inline if name == "Int" then 0
3+
else inline if name == "String" then ""
4+
else ???
5+
6+
7+
def test =
8+
default("Int")

tests/pos/stringConstantFold.scala

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def test =
2+
("A" + "B": "AB")
3+
4+
("A" == "A": true)
5+
("A" == "B": false)

0 commit comments

Comments
 (0)