From 8e8e808fc9442c1259835c44144fb1a6d7a31ddd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20D=C3=A4schle?= Date: Fri, 2 Oct 2020 09:32:07 +0200 Subject: [PATCH] gen: fix sumtype custom str (#6534) --- vlib/v/gen/auto_str_methods.v | 9 +++------ vlib/v/tests/sumtype_str_test.v | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/vlib/v/gen/auto_str_methods.v b/vlib/v/gen/auto_str_methods.v index 2c7338596d..f17bc6c862 100644 --- a/vlib/v/gen/auto_str_methods.v +++ b/vlib/v/gen/auto_str_methods.v @@ -297,7 +297,7 @@ fn (mut g Gen) gen_str_for_struct(info table.Struct, styp, str_fn_name string) { for field in info.fields { sym := g.table.get_type_symbol(field.typ) if !sym.has_method('str') { - mut typ := field.typ + mut typ := field.typ if typ.is_ptr() { typ = typ.deref() } @@ -383,16 +383,13 @@ fn struct_auto_str_func(sym table.TypeSymbol, field_type table.Type, fn_name, fi } if has_custom_str { return '${fn_name}($obj)' - } else { - return 'indent_${fn_name}($obj, indent_count + 1)' } - } else if sym.kind in [.array, .array_fixed, .map] { + return 'indent_${fn_name}($obj, indent_count + 1)' + } else if sym.kind in [.array, .array_fixed, .map, .sum_type] { if has_custom_str { return '${fn_name}(it->${c_name(field_name)})' } return 'indent_${fn_name}(it->${c_name(field_name)}, indent_count + 1)' - } else if sym.kind == .sum_type { - return 'indent_${fn_name}(it->${c_name(field_name)}, indent_count + 1)' } else { mut method_str := 'it->${c_name(field_name)}' if sym.kind == .bool { diff --git a/vlib/v/tests/sumtype_str_test.v b/vlib/v/tests/sumtype_str_test.v index 4e68b09223..3b7984965b 100644 --- a/vlib/v/tests/sumtype_str_test.v +++ b/vlib/v/tests/sumtype_str_test.v @@ -57,3 +57,21 @@ fn test_pointer() { st := ST(0) assert '${&st}' == '&ST(0)' } + +struct Xyz {} + +type Hola = Abc | Xyz + +fn (h Hola) str() string { + return 'Hola' +} + +struct HolaContainer { + h Hola +} + +fn test_custom_str_method() { + h := HolaContainer{} + assert h.str() == 'HolaContainer {\n h: Hola\n}' + assert '$h' == 'HolaContainer {\n h: Hola\n}' +}