From 4e498b43033a3db448653edc0538873bbbc4cc4e Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 10 Apr 2023 22:09:27 +0800 Subject: [PATCH] cgen: fix printing array of recursive reference struct (fix #17858) (#17922) --- vlib/v/gen/c/auto_str_methods.v | 14 +++++++++++++- ...ing_recursive_array_of_reference_struct.out | 5 +++++ ...ting_recursive_array_of_reference_struct.vv | 18 ++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 vlib/v/slow_tests/inout/printing_recursive_array_of_reference_struct.out create mode 100644 vlib/v/slow_tests/inout/printing_recursive_array_of_reference_struct.vv diff --git a/vlib/v/gen/c/auto_str_methods.v b/vlib/v/gen/c/auto_str_methods.v index b78d4e87cf..23bdd44878 100644 --- a/vlib/v/gen/c/auto_str_methods.v +++ b/vlib/v/gen/c/auto_str_methods.v @@ -969,9 +969,21 @@ fn (mut g Gen) gen_str_for_struct(info ast.Struct, styp string, typ_str string, funcprefix += '*' } } + mut is_field_array := false + if sym.info is ast.Array { + field_styp = g.typ(sym.info.elem_type).trim('*') + is_field_array = true + } else if sym.info is ast.ArrayFixed { + field_styp = g.typ(sym.info.elem_type).trim('*') + is_field_array = true + } // handle circular ref type of struct to the struct itself if styp == field_styp && !allow_circular { - fn_body.write_string('${funcprefix}_SLIT("")') + if is_field_array { + fn_body.write_string('it.${c_name(field.name)}.len > 0 ? ${funcprefix}_SLIT("[]") : ${funcprefix}_SLIT("[]")') + } else { + fn_body.write_string('${funcprefix}_SLIT("")') + } } else { // manage C charptr if field.typ in ast.charptr_types { diff --git a/vlib/v/slow_tests/inout/printing_recursive_array_of_reference_struct.out b/vlib/v/slow_tests/inout/printing_recursive_array_of_reference_struct.out new file mode 100644 index 0000000000..d7072d2fb7 --- /dev/null +++ b/vlib/v/slow_tests/inout/printing_recursive_array_of_reference_struct.out @@ -0,0 +1,5 @@ +&Person{ + name: 'John' + relatives: [] +} +Success diff --git a/vlib/v/slow_tests/inout/printing_recursive_array_of_reference_struct.vv b/vlib/v/slow_tests/inout/printing_recursive_array_of_reference_struct.vv new file mode 100644 index 0000000000..d9a716ddf5 --- /dev/null +++ b/vlib/v/slow_tests/inout/printing_recursive_array_of_reference_struct.vv @@ -0,0 +1,18 @@ +struct Person { + name string +mut: + relatives []&Person +} + +fn main() { + mut father := &Person{ + name: 'John' + } + mut mother := &Person{ + name: 'Jane' + relatives: [father] + } + father.relatives = [mother] + println(father) + println('Success') +}