From 585b5145faecec4ea05d31beec7c3374df6ad3ba Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 22 Jun 2022 19:54:04 +0800 Subject: [PATCH] cgen: fix auto string method generated for []&int{len:1} (#14829) --- vlib/v/gen/c/auto_str_methods.v | 12 ++++++++++-- vlib/v/tests/string_array_of_ref_type_test.v | 5 +++++ 2 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/string_array_of_ref_type_test.v diff --git a/vlib/v/gen/c/auto_str_methods.v b/vlib/v/gen/c/auto_str_methods.v index d4dd58e8b3..f4e92f51af 100644 --- a/vlib/v/gen/c/auto_str_methods.v +++ b/vlib/v/gen/c/auto_str_methods.v @@ -586,8 +586,16 @@ fn (mut g Gen) gen_str_for_array(info ast.Array, styp string, str_fn_name string // Note: we need to take account of whether the user has defined // `fn (x T) str() {` or `fn (x &T) str() {`, and convert accordingly deref, deref_label := deref_kind(str_method_expects_ptr, is_elem_ptr, typ) - g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _SLIT("$deref_label"));') - g.auto_str_funcs.writeln('\t\tstring x = ${elem_str_fn_name}( $deref it);') + if is_elem_ptr { + g.auto_str_funcs.writeln('\t\tstring x = _SLIT("nil");') + g.auto_str_funcs.writeln('\t\tif (it != 0) {') + g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write_string(&sb, _SLIT("$deref_label"));') + g.auto_str_funcs.writeln('\t\t\tx = ${elem_str_fn_name}(${deref}it);') + g.auto_str_funcs.writeln('\t\t}') + } else { + g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _SLIT("$deref_label"));') + g.auto_str_funcs.writeln('\t\tstring x = ${elem_str_fn_name}(${deref}it);') + } } } g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, x);') diff --git a/vlib/v/tests/string_array_of_ref_type_test.v b/vlib/v/tests/string_array_of_ref_type_test.v new file mode 100644 index 0000000000..abcb2de3d8 --- /dev/null +++ b/vlib/v/tests/string_array_of_ref_type_test.v @@ -0,0 +1,5 @@ +fn test_string_array_of_ref_type() { + a := []&int{len: 2} + println(a) + assert '$a' == '[nil, nil]' +}