checker: check unsigned integer compared with negative value (#13670)

pull/13683/head
yuyi 2022-03-07 16:26:40 +08:00 committed by GitHub
parent 36ec47cd20
commit e6270b05dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 0 deletions

View File

@ -819,6 +819,28 @@ pub fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
} else if need_overload && !gen_sym.has_method('<') && node.op == .gt {
c.error('cannot use `>` as `<=` operator method is not defined', left_right_pos)
}
} else if left_type in ast.integer_type_idxs && right_type in ast.integer_type_idxs {
is_left_type_signed := left_type in ast.signed_integer_type_idxs
|| left_type == ast.int_literal_type_idx
is_right_type_signed := right_type in ast.signed_integer_type_idxs
|| right_type == ast.int_literal_type_idx
if is_left_type_signed != is_right_type_signed {
if is_right_type_signed {
if mut node.right is ast.IntegerLiteral {
if node.right.val.int() < 0 {
c.error('unsigned integer cannot be compared with negative value',
node.right.pos)
}
}
} else if is_left_type_signed {
if mut node.left is ast.IntegerLiteral {
if node.left.val.int() < 0 {
c.error('unsigned integer cannot be compared with negative value',
node.left.pos)
}
}
}
}
}
}
.left_shift {

View File

@ -0,0 +1,13 @@
vlib/v/checker/tests/infix_unsigned_and_signed_int_err.vv:2:14: error: unsigned integer cannot be compared with negative value
1 | fn main() {
2 | if u32(1) < -1 {
| ~~
3 | println('unexpected')
4 | }
vlib/v/checker/tests/infix_unsigned_and_signed_int_err.vv:6:5: error: unsigned integer cannot be compared with negative value
4 | }
5 |
6 | if -1 > u32(1) {
| ~~
7 | println('unexpected')
8 | }

View File

@ -0,0 +1,9 @@
fn main() {
if u32(1) < -1 {
println('unexpected')
}
if -1 > u32(1) {
println('unexpected')
}
}