From c1731042956d7e80d0d8bc47e2162b86ef229178 Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Wed, 22 Feb 2023 17:40:07 +0530 Subject: [PATCH] cgen: add `&` before ptr arr elements (#17379) --- vlib/v/gen/c/auto_str_methods.v | 8 ++++++- .../printing_fixed_array_of_pointers.out | 4 ++-- vlib/v/tests/array_of_ptrs_test.v | 22 +++++++++++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/array_of_ptrs_test.v diff --git a/vlib/v/gen/c/auto_str_methods.v b/vlib/v/gen/c/auto_str_methods.v index f185950a5b..1324a45386 100644 --- a/vlib/v/gen/c/auto_str_methods.v +++ b/vlib/v/gen/c/auto_str_methods.v @@ -558,7 +558,13 @@ fn (mut g Gen) gen_str_for_array(info ast.Array, styp string, str_fn_name string } if should_use_indent_func(sym.kind) && !sym_has_str_method { if is_elem_ptr { - g.auto_str_funcs.writeln('\t\tstring x = indent_${elem_str_fn_name}(*it, indent_count);') + deref, deref_label := deref_kind(str_method_expects_ptr, is_elem_ptr, + typ) + 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\tstring x = indent_${elem_str_fn_name}(it, indent_count);') } diff --git a/vlib/v/slow_tests/inout/printing_fixed_array_of_pointers.out b/vlib/v/slow_tests/inout/printing_fixed_array_of_pointers.out index befcc58326..b2275db0cd 100644 --- a/vlib/v/slow_tests/inout/printing_fixed_array_of_pointers.out +++ b/vlib/v/slow_tests/inout/printing_fixed_array_of_pointers.out @@ -53,8 +53,8 @@ StructOfFixedArraysOfListeners{ [&0, &0] [&&0, &&0] ----------------------------------------------------- -[EventListener{ +[&EventListener{ x: 123 -}, EventListener{ +}, &EventListener{ x: 0 }] diff --git a/vlib/v/tests/array_of_ptrs_test.v b/vlib/v/tests/array_of_ptrs_test.v new file mode 100644 index 0000000000..69c967f6bf --- /dev/null +++ b/vlib/v/tests/array_of_ptrs_test.v @@ -0,0 +1,22 @@ +struct Point { + x int + y int +} + +fn test_array_of_ptr_str() { + point_1 := &Point{1, 2} + point_2 := &Point{3, 4} + point_3 := &Point{5, 6} + points := [point_1, point_2, point_3] + assert '${points}' == '[&Point{ + x: 1 + y: 2 +}, &Point{ + x: 3 + y: 4 +}, &Point{ + x: 5 + y: 6 +}] +'.trim_indent() +}