mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
checker: add 1/0x0 1/0b0..
division by zero check (#5694)
This commit is contained in:
parent
1d10b150c5
commit
f41edef4c6
@ -552,11 +552,20 @@ pub fn (mut c Checker) infix_expr(mut infix_expr ast.InfixExpr) table.Type {
|
||||
}
|
||||
}
|
||||
if infix_expr.op in [.div, .mod] {
|
||||
if (infix_expr.right is ast.IntegerLiteral &&
|
||||
infix_expr.right.str() == '0') ||
|
||||
(infix_expr.right is ast.FloatLiteral && infix_expr.right.str().f64() == 0.0) {
|
||||
oper := if infix_expr.op == .div { 'division' } else { 'modulo' }
|
||||
c.error('$oper by zero', right_pos)
|
||||
match infix_expr.right as infix_right {
|
||||
ast.FloatLiteral {
|
||||
if infix_right.val.f64() == 0.0 {
|
||||
oper := if infix_expr.op == .div { 'division' } else { 'modulo' }
|
||||
c.error('$oper by zero', infix_right.pos)
|
||||
}
|
||||
}
|
||||
ast.IntegerLiteral {
|
||||
if infix_right.val.int() == 0 {
|
||||
oper := if infix_expr.op == .div { 'division' } else { 'modulo' }
|
||||
c.error('$oper by zero', infix_right.pos)
|
||||
}
|
||||
}
|
||||
else {}
|
||||
}
|
||||
}
|
||||
return_type = promoted_type
|
||||
|
@ -2,4 +2,25 @@ vlib/v/checker/tests/division_by_zero_int_err.v:2:12: error: division by zero
|
||||
1 | fn main() {
|
||||
2 | println(1/0)
|
||||
| ^
|
||||
3 | }
|
||||
3 | println(1/0x0)
|
||||
4 | println(1/0b0)
|
||||
vlib/v/checker/tests/division_by_zero_int_err.v:3:12: error: division by zero
|
||||
1 | fn main() {
|
||||
2 | println(1/0)
|
||||
3 | println(1/0x0)
|
||||
| ~~~
|
||||
4 | println(1/0b0)
|
||||
5 | println(1/0o0)
|
||||
vlib/v/checker/tests/division_by_zero_int_err.v:4:12: error: division by zero
|
||||
2 | println(1/0)
|
||||
3 | println(1/0x0)
|
||||
4 | println(1/0b0)
|
||||
| ~~~
|
||||
5 | println(1/0o0)
|
||||
6 | }
|
||||
vlib/v/checker/tests/division_by_zero_int_err.v:5:12: error: division by zero
|
||||
3 | println(1/0x0)
|
||||
4 | println(1/0b0)
|
||||
5 | println(1/0o0)
|
||||
| ~~~
|
||||
6 | }
|
||||
|
@ -1,3 +1,6 @@
|
||||
fn main() {
|
||||
println(1/0)
|
||||
println(1/0x0)
|
||||
println(1/0b0)
|
||||
println(1/0o0)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user