1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: add more checks for modulo

This commit is contained in:
Swastik Baranwal 2020-05-16 19:02:46 +05:30 committed by GitHub
parent 9b6ee8e77d
commit 37cf46d67a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 28 additions and 0 deletions

View File

@ -448,12 +448,16 @@ pub fn (mut c Checker) infix_expr(mut infix_expr ast.InfixExpr) table.Type {
c.error('mismatched types `$left.name` and `$right.name`', infix_expr.right.position())
} else if !left.is_int() && right.is_int() {
c.error('mismatched types `$left.name` and `$right.name`', infix_expr.left.position())
} else if left.kind == .f32 && right.kind == .f32 || left.kind == .f64 && right.kind == .f64 {
c.error('float modulo not allowed, use math.fmod() instead', infix_expr.left.position())
} else if left.kind in [.f32, .f64, .string, .array, .array_fixed, .map, .struct_] &&
!left.has_method(infix_expr.op.str()) {
c.error('mismatched types `$left.name` and `$right.name`', infix_expr.left.position())
} else if right.kind in [.f32, .f64, .string, .array, .array_fixed, .map, .struct_] &&
!right.has_method(infix_expr.op.str()) {
c.error('mismatched types `$left.name` and `$right.name`', infix_expr.right.position())
} else if infix_expr.right is ast.IntegerLiteral && infix_expr.right.str() == '0' {
c.error('modulo by zero', infix_expr.right.position())
}
}
else {}

View File

@ -0,0 +1,12 @@
vlib/v/checker/tests/float_modulo_err.v:2:13: error: float modulo not allowed, use math.fmod() instead
1 | fn main() {
2 | println(3.0 % 2.0)
| ~~~
3 | println(f32(3.0) % f32(2.0))
4 | }
vlib/v/checker/tests/float_modulo_err.v:3:17: error: float modulo not allowed, use math.fmod() instead
1 | fn main() {
2 | println(3.0 % 2.0)
3 | println(f32(3.0) % f32(2.0))
| ~~~
4 | }

View File

@ -0,0 +1,4 @@
fn main() {
println(3.0 % 2.0)
println(f32(3.0) % f32(2.0))
}

View File

@ -0,0 +1,5 @@
vlib/v/checker/tests/int_modulo_by_zero_err.v:2:17: error: modulo by zero
1 | fn main() {
2 | println(3 % 0)
| ^
3 | }

View File

@ -0,0 +1,3 @@
fn main() {
println(3 % 0)
}