Skip to content

Commit 90696e9

Browse files
committed
Add error for illegal singleton ops
Division by 0 and modulo by 0 would otherwise crash the compiler. Throwing an error prints an error message positioned on the operator, and does not prevent other type errors from being found and shown.
1 parent c9a296d commit 90696e9

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

compiler/src/dotty/tools/dotc/core/Types.scala

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3643,8 +3643,14 @@ object Types {
36433643
case tpnme.Plus => constantFold2(intValue, _ + _)
36443644
case tpnme.Minus => constantFold2(intValue, _ - _)
36453645
case tpnme.Times => constantFold2(intValue, _ * _)
3646-
case tpnme.Div => constantFold2(intValue, _ / _)
3647-
case tpnme.Mod => constantFold2(intValue, _ % _)
3646+
case tpnme.Div => constantFold2(intValue, {
3647+
case (_, 0) => throw new TypeError("Division by 0")
3648+
case (a, b) => a / b
3649+
})
3650+
case tpnme.Mod => constantFold2(intValue, {
3651+
case (_, 0) => throw new TypeError("Modulo by 0")
3652+
case (a, b) => a % b
3653+
})
36483654
case tpnme.Lt => constantFold2(intValue, _ < _)
36493655
case tpnme.Gt => constantFold2(intValue, _ > _)
36503656
case tpnme.Ge => constantFold2(intValue, _ >= _)

tests/neg/singleton-ops.scala

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,14 @@ object Test {
2525
val t7: -2 * -2 = 4
2626

2727
val t8: 10 / 2 = 5
28-
val t9: 11 / 2 = 5 // Integer division
28+
val t9: 11 / -2 = -5 // Integer division
2929
val t10: 2 / 4 = 2 // error
30-
val t11: -1 / -1 = 1
30+
val t11: -1 / 0 = 1 // error
3131

3232
val t12: 10 % 3 = 1
3333
val t13: 12 % 2 = 1 // error
3434
val t14: 1 % -3 = 1
35-
val t15: -3 % -2 = 0 // error
35+
val t15: -3 % 0 = 0 // error
3636

3737
val t16: 1 < 0 = false
3838
val t17: 0 < 1 = true

0 commit comments

Comments
 (0)