cgen: fix enumval str() call on stringinterliteral (fix #24702) (#24705)

This commit is contained in:
Felipe Pena 2025-06-12 13:23:05 -03:00 committed by GitHub
parent b6ccca23a0
commit 4dc66e2675
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 1 deletions

View File

@ -98,12 +98,15 @@ fn (mut g Gen) gen_expr_to_string(expr ast.Expr, etype ast.Type) {
}
g.write('_S("<none>")')
} else if sym.kind == .enum {
if expr !is ast.EnumVal {
if expr !is ast.EnumVal || sym.has_method('str') {
str_fn_name := g.get_str_fn(typ)
g.write('${str_fn_name}(')
if typ.nr_muls() > 0 {
g.write('*'.repeat(typ.nr_muls()))
}
if expr is ast.EnumVal {
g.write2(sym.cname, '__')
}
g.enum_expr(expr)
g.write(')')
} else {

View File

@ -0,0 +1,26 @@
enum Traffic {
rx_bytes
tx_bytes
}
fn (t Traffic) str() string {
return match t {
.rx_bytes { 'rx-bytes' }
.tx_bytes { 'tx-bytes' }
}
}
fn Traffic.from_string(s string) ?Traffic {
return match s {
'rx-bytes' { .rx_bytes }
'tx-bytes' { .tx_bytes }
else { none }
}
}
fn test_main() {
traffic := Traffic.from_string('rx-bytes') or { return }
assert Traffic.rx_bytes.str() == 'rx-bytes'
assert '${traffic}' == 'rx-bytes'
assert '${Traffic.rx_bytes}' == 'rx-bytes'
}