Skip to content

Commit

Permalink
cgen: fix enum value string interpolation, like its declared enum und…
Browse files Browse the repository at this point in the history
…erlying type (fix vlang#22938) (vlang#22945)
  • Loading branch information
felipensp authored Nov 23, 2024
1 parent f8fb57d commit e4d24e8
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
19 changes: 19 additions & 0 deletions vlib/v/ast/table.v
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,25 @@ pub fn (t &Table) final_sym(typ Type) &TypeSymbol {
return invalid_type_symbol
}

// final_type returns the underlying type, if the final type is an Enum it returns the enum defined type (int one) otherwise the aliased/real type is returned
pub fn (t &Table) final_type(typ Type) Type {
mut idx := typ.idx()
if idx > 0 && idx < t.type_symbols.len {
cur_sym := t.type_symbols[idx]
if cur_sym.info is Alias {
idx = cur_sym.info.parent_type.idx()
aliased_sym := t.type_symbols[idx]
if aliased_sym.info is Enum {
return aliased_sym.info.typ
}
return cur_sym.info.parent_type
} else if cur_sym.info is Enum {
return cur_sym.info.typ
}
}
return typ
}

@[inline]
pub fn (t &Table) get_type_name(typ Type) string {
return t.sym(typ).name
Expand Down
6 changes: 1 addition & 5 deletions vlib/v/gen/c/str_intp.v
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,7 @@ fn (mut g Gen) str_format(node ast.StringInterLiteral, i int, fmts []u8) (u64, s
if node.exprs[i].is_auto_deref_var() {
typ = typ.deref()
}
sym := g.table.sym(typ)

if sym.kind == .alias {
typ = (sym.info as ast.Alias).parent_type
}
typ = g.table.final_type(typ)
mut remove_tail_zeros := false
fspec := fmts[i]
mut fmt_type := StrIntpType.si_no_str
Expand Down
14 changes: 14 additions & 0 deletions vlib/v/tests/enums/enum_print_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
@[type]
enum Nums {
one = 1
two = 2
ten = 10
}

fn test_main() {
mut str := []string{}
$for n in Nums.values {
str << '${n.name} ${n.value} ${n.value:d} ${int(n.value)} | ${n.value:o} ${n.value:x} ${n.value:X} ${n.value:b}'
}
assert str == ['one one 1 1 | 1 1 1 1', 'two two 2 2 | 2 2 2 10', 'ten ten 10 10 | 12 a A 1010']
}

0 comments on commit e4d24e8

Please sign in to comment.