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

checker: fix external enum value resolution, i.e. enum { enum_value = C.VALUE } (#18401)

This commit is contained in:
Felipe Pena 2023-06-11 13:08:45 -03:00 committed by GitHub
parent 275b8a1294
commit 2e9c469158
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 23 additions and 4 deletions

View File

@ -372,8 +372,9 @@ pub fn (t &Table) find_method_with_embeds(sym &TypeSymbol, method_name string) !
} }
} }
// find_enum_field_val finds the int value from the enum name and enum field // find_enum_field_val finds the possible int value from the enum name and enum field
pub fn (t &Table) find_enum_field_val(name string, field_ string) i64 { // (returns `none` if the value cannot be resolved at compile time)
pub fn (t &Table) find_enum_field_val(name string, field_ string) ?i64 {
mut val := i64(0) mut val := i64(0)
enum_decl := t.enum_decls[name] enum_decl := t.enum_decls[name]
mut enum_vals := []i64{} mut enum_vals := []i64{}
@ -384,6 +385,7 @@ pub fn (t &Table) find_enum_field_val(name string, field_ string) i64 {
val = field.expr.val.i64() val = field.expr.val.i64()
break break
} }
return none
} else { } else {
if enum_vals.len > 0 { if enum_vals.len > 0 {
val = enum_vals.last() + 1 val = enum_vals.last() + 1
@ -396,6 +398,8 @@ pub fn (t &Table) find_enum_field_val(name string, field_ string) i64 {
if field.has_expr { if field.has_expr {
if field.expr is IntegerLiteral { if field.expr is IntegerLiteral {
enum_vals << field.expr.val.i64() enum_vals << field.expr.val.i64()
} else {
return none
} }
} else { } else {
if enum_vals.len > 0 { if enum_vals.len > 0 {

View File

@ -270,7 +270,9 @@ fn (mut c Checker) eval_comptime_const_expr(expr ast.Expr, nlevel int) ?ast.Comp
return c.eval_comptime_const_expr(expr.expr, nlevel + 1) return c.eval_comptime_const_expr(expr.expr, nlevel + 1)
} }
ast.EnumVal { ast.EnumVal {
return c.table.find_enum_field_val(expr.enum_name, expr.val) if val := c.table.find_enum_field_val(expr.enum_name, expr.val) {
return val
}
} }
ast.SizeOf { ast.SizeOf {
s, _ := c.table.type_size(expr.typ) s, _ := c.table.type_size(expr.typ)

View File

@ -250,8 +250,11 @@ fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
fixed_size = init_expr.expr.val.int() fixed_size = init_expr.expr.val.int()
} }
ast.EnumVal { ast.EnumVal {
fixed_size = c.table.find_enum_field_val(init_expr.expr.enum_name, if val := c.table.find_enum_field_val(init_expr.expr.enum_name,
init_expr.expr.val) init_expr.expr.val)
{
fixed_size = val
}
} }
else {} else {}
} }

View File

@ -0,0 +1,10 @@
import gx
const left = gx.align_left
fn test_main() {
align := left
assert dump(align.str()) == 'left'
assert dump(gx.align_left) == gx.align_left
assert gx.align_left.str() == 'left'
}