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

checker: fix enum max value validation (#18446)

This commit is contained in:
Felipe Pena 2023-06-16 03:48:47 -03:00 committed by GitHub
parent 05f2798c88
commit 84cf448f2f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 2 deletions

View File

@ -1674,6 +1674,7 @@ fn (mut c Checker) enum_decl(mut node ast.EnumDecl) {
mut overflows := false
mut uval := u64(0)
mut ival := i64(0)
if signed {
val := field.expr.val.i64()
ival = val
@ -1686,9 +1687,22 @@ fn (mut c Checker) enum_decl(mut node ast.EnumDecl) {
val := field.expr.val.u64()
uval = val
if val >= enum_umax {
c.error('enum value `${field.expr.val}` overflows the enum type `${senum_type}`, values of which have to be in [${enum_umin}, ${enum_umax}]',
field.expr.pos)
overflows = true
if val == enum_umax {
is_bin := field.expr.val.starts_with('0b')
is_oct := field.expr.val.starts_with('0o')
is_hex := field.expr.val.starts_with('0x')
if is_hex {
overflows = val.hex() != enum_umax.hex()
} else if !is_bin && !is_oct && !is_hex {
overflows = field.expr.val.str() != enum_umax.str()
}
}
if overflows {
c.error('enum value `${field.expr.val}` overflows the enum type `${senum_type}`, values of which have to be in [${enum_umin}, ${enum_umax}]',
field.expr.pos)
}
}
}
if !overflows && !c.pref.translated && !c.file.is_translated

View File

@ -0,0 +1,27 @@
enum Nums as u8 {
one
two
three = 0xff
}
enum Nums2 as u32 {
one
two
three = 0xFFFFFFFF
}
enum Nums3 as u64 {
one
two
three = 0xFFFFFFFFFFFFFFFF
}
fn test_main() {
mut a := Nums.one
assert a == Nums.one
assert int(Nums.three) == 0xff
assert Nums.three == unsafe { Nums(255) }
assert u64(Nums2.three) == 0xFFFFFFFF
assert u64(Nums3.three) == 0xFFFFFFFFFFFFFFFF
}