From b3a9701129e650d50dd6c98912fcbbef7ce614cd Mon Sep 17 00:00:00 2001 From: shove Date: Sat, 11 Nov 2023 00:15:53 +0800 Subject: [PATCH] cgen: fix gen interface to string(fix #19788) (#19829) --- vlib/v/gen/c/str.v | 7 ++++++- vlib/v/tests/interface_str_method_test.v | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/vlib/v/gen/c/str.v b/vlib/v/gen/c/str.v index e07b732be587c5..eb9f5d3e4efad6 100644 --- a/vlib/v/gen/c/str.v +++ b/vlib/v/gen/c/str.v @@ -113,12 +113,17 @@ fn (mut g Gen) gen_expr_to_string(expr ast.Expr, etype ast.Type) { if is_ptr && !is_var_mut { ref_str := '&'.repeat(typ.nr_muls()) g.write('str_intp(1, _MOV((StrIntpData[]){{_SLIT("${ref_str}"), ${si_s_code} ,{.d_s = isnil(') - if is_ptr && typ.has_flag(.option) { + if typ.has_flag(.option) { g.write('*(${g.base_type(exp_typ)}*)&') g.expr(expr) g.write('.data') g.write(') ? _SLIT("Option(&nil)") : ') } else { + inside_casting_to_str_old := g.inside_casting_to_str + g.inside_casting_to_str = false + defer { + g.inside_casting_to_str = inside_casting_to_str_old + } g.expr(expr) g.write(') ? _SLIT("nil") : ') } diff --git a/vlib/v/tests/interface_str_method_test.v b/vlib/v/tests/interface_str_method_test.v index 4bce9f62ba1dfb..9096e442e15067 100644 --- a/vlib/v/tests/interface_str_method_test.v +++ b/vlib/v/tests/interface_str_method_test.v @@ -18,3 +18,18 @@ fn test_interface_str_method() { ret := printer(s) assert ret == 's' } + +// for test interface gen to string +interface Abc {} + +struct Xyz {} + +fn test_interface_gen_to_string() { + d := Abc(Xyz{}) + mut res := '' + if d is Xyz { + println(d) + res = '${d}' + } + assert res == '&Xyz{}' +}