From 9921598c91d2a2483efb1607c8fcbf0ea2feaaa9 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 17 Dec 2022 13:15:17 -0300 Subject: [PATCH] cgen: fix struct field initialisation with a fixed array (#16692) --- .../tests/struct_fixed_array_init_test.out | 3 +++ .../tests/struct_fixed_array_init_test.vv | 17 +++++++++++++++++ vlib/v/gen/c/cgen.v | 18 ++++++++++++++++-- 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 vlib/v/checker/tests/struct_fixed_array_init_test.out create mode 100644 vlib/v/checker/tests/struct_fixed_array_init_test.vv diff --git a/vlib/v/checker/tests/struct_fixed_array_init_test.out b/vlib/v/checker/tests/struct_fixed_array_init_test.out new file mode 100644 index 000000000..d9899e798 --- /dev/null +++ b/vlib/v/checker/tests/struct_fixed_array_init_test.out @@ -0,0 +1,3 @@ +Sample{ + data: Data([5, 10, 15]) +} diff --git a/vlib/v/checker/tests/struct_fixed_array_init_test.vv b/vlib/v/checker/tests/struct_fixed_array_init_test.vv new file mode 100644 index 000000000..84587d92f --- /dev/null +++ b/vlib/v/checker/tests/struct_fixed_array_init_test.vv @@ -0,0 +1,17 @@ +module main + +type Data = [3]int | int + +struct Sample { + data Data +} + +fn test_main() { + test := Sample{ + data: [5, 10, 15]! + // data: 5 /* works fine */ + } + + println(test) + assert test.data.str() == 'Data([5, 10, 15])' +} diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index a014da9b1..f90424ae5 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -2473,9 +2473,23 @@ fn (mut g Gen) expr_with_cast(expr ast.Expr, got_type_raw ast.Type, expected_typ unwrapped_got_type = unwrapped_got_sym.info.types[g.aggregate_type_idx] unwrapped_got_sym = g.table.sym(unwrapped_got_type) } + fname := g.get_sumtype_casting_fn(unwrapped_got_type, unwrapped_expected_type) - g.call_cfn_for_casting_expr(fname, expr, expected_is_ptr, unwrapped_exp_sym.cname, - got_is_ptr, got_is_fn, got_styp) + + if expr is ast.ArrayInit && got_sym.kind == .array_fixed { + stmt_str := g.go_before_stmt(0).trim_space() + g.empty_line = true + tmp_var := g.new_tmp_var() + g.write('${got_styp} ${tmp_var} = ') + g.expr(expr) + g.write(';') + g.write(stmt_str) + g.write('${fname}(&${tmp_var})') + return + } else { + g.call_cfn_for_casting_expr(fname, expr, expected_is_ptr, unwrapped_exp_sym.cname, + got_is_ptr, got_is_fn, got_styp) + } } return } -- 2.39.5