checker: check integer literals (#10706)

pull/10723/head
shadowninja55 2021-07-09 07:02:10 -04:00 committed by GitHub
parent 310bb1a8a6
commit aa5b609d95
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 36 additions and 1 deletions

View File

@ -487,6 +487,31 @@ pub fn (mut c Checker) string_inter_lit(mut node ast.StringInterLiteral) ast.Typ
return ast.string_type
}
pub fn (mut c Checker) int_lit(mut node ast.IntegerLiteral) ast.Type {
if node.val.len < 17 {
// can not be a too large number, no need for more expensive checks
return ast.int_literal_type
}
lit := node.val.replace('_', '').all_after('-')
is_neg := node.val.starts_with('-')
limit := if is_neg { '9223372036854775808' } else { '18446744073709551615' }
message := 'integer literal $node.val overflows int'
if lit.len > limit.len {
c.error(message, node.pos)
} else if lit.len == limit.len {
for i, digit in lit {
if digit > limit[i] {
c.error(message, node.pos)
} else if digit < limit[i] {
break
}
}
}
return ast.int_literal_type
}
pub fn (mut c Checker) infer_fn_generic_types(f ast.Fn, mut call_expr ast.CallExpr) {
mut inferred_types := []ast.Type{}
for gi, gt_name in f.generic_names {

View File

@ -5004,7 +5004,7 @@ pub fn (mut c Checker) expr(node ast.Expr) ast.Type {
return c.infix_expr(mut node)
}
ast.IntegerLiteral {
return ast.int_literal_type
return c.int_lit(mut node)
}
ast.LockExpr {
return c.lock_expr(mut node)

View File

@ -0,0 +1,8 @@
vlib/v/checker/tests/oversized_int_lit.vv:1:8: error: integer literal 18446744073709551616 overflows int
1 | assert 18446744073709551616 > 0
| ~~~~~~~~~~~~~~~~~~~~
2 | assert -9223372036854775809 < 0
vlib/v/checker/tests/oversized_int_lit.vv:2:8: error: integer literal -9223372036854775809 overflows int
1 | assert 18446744073709551616 > 0
2 | assert -9223372036854775809 < 0
| ~~~~~~~~~~~~~~~~~~~~

View File

@ -0,0 +1,2 @@
assert 18446744073709551616 > 0
assert -9223372036854775809 < 0