mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
checker: check integer literals (#10706)
This commit is contained in:
parent
310bb1a8a6
commit
aa5b609d95
@ -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 {
|
||||
|
@ -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)
|
||||
|
8
vlib/v/checker/tests/oversized_int_lit.out
Normal file
8
vlib/v/checker/tests/oversized_int_lit.out
Normal 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
|
||||
| ~~~~~~~~~~~~~~~~~~~~
|
2
vlib/v/checker/tests/oversized_int_lit.vv
Normal file
2
vlib/v/checker/tests/oversized_int_lit.vv
Normal file
@ -0,0 +1,2 @@
|
||||
assert 18446744073709551616 > 0
|
||||
assert -9223372036854775809 < 0
|
Loading…
Reference in New Issue
Block a user