From 4dc66e2675668abc4929b28139e41458ed09206c Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Thu, 12 Jun 2025 13:23:05 -0300 Subject: [PATCH] cgen: fix enumval str() call on stringinterliteral (fix #24702) (#24705) --- vlib/v/gen/c/str.v | 5 ++++- vlib/v/tests/enums/enum_val_test.v | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/enums/enum_val_test.v diff --git a/vlib/v/gen/c/str.v b/vlib/v/gen/c/str.v index f8e1ba0055..6d3bab7f05 100644 --- a/vlib/v/gen/c/str.v +++ b/vlib/v/gen/c/str.v @@ -98,12 +98,15 @@ fn (mut g Gen) gen_expr_to_string(expr ast.Expr, etype ast.Type) { } g.write('_S("")') } 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 { diff --git a/vlib/v/tests/enums/enum_val_test.v b/vlib/v/tests/enums/enum_val_test.v new file mode 100644 index 0000000000..8c5eafedf5 --- /dev/null +++ b/vlib/v/tests/enums/enum_val_test.v @@ -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' +}