Skip to content

Commit 4dc66e2

Browse files
authored
cgen: fix enumval str() call on stringinterliteral (fix #24702) (#24705)
1 parent b6ccca2 commit 4dc66e2

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

‎vlib/v/gen/c/str.v‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,15 @@ fn (mut g Gen) gen_expr_to_string(expr ast.Expr, etype ast.Type) {
9898
}
9999
g.write('_S("<none>")')
100100
} else if sym.kind == .enum {
101-
if expr !is ast.EnumVal {
101+
if expr !is ast.EnumVal || sym.has_method('str') {
102102
str_fn_name := g.get_str_fn(typ)
103103
g.write('${str_fn_name}(')
104104
if typ.nr_muls() > 0 {
105105
g.write('*'.repeat(typ.nr_muls()))
106106
}
107+
if expr is ast.EnumVal {
108+
g.write2(sym.cname, '__')
109+
}
107110
g.enum_expr(expr)
108111
g.write(')')
109112
} else {

‎vlib/v/tests/enums/enum_val_test.v‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
enum Traffic {
2+
rx_bytes
3+
tx_bytes
4+
}
5+
6+
fn (t Traffic) str() string {
7+
return match t {
8+
.rx_bytes { 'rx-bytes' }
9+
.tx_bytes { 'tx-bytes' }
10+
}
11+
}
12+
13+
fn Traffic.from_string(s string) ?Traffic {
14+
return match s {
15+
'rx-bytes' { .rx_bytes }
16+
'tx-bytes' { .tx_bytes }
17+
else { none }
18+
}
19+
}
20+
21+
fn test_main() {
22+
traffic := Traffic.from_string('rx-bytes') or { return }
23+
assert Traffic.rx_bytes.str() == 'rx-bytes'
24+
assert '${traffic}' == 'rx-bytes'
25+
assert '${Traffic.rx_bytes}' == 'rx-bytes'
26+
}

0 commit comments

Comments
 (0)