From 19ff25d456d78d293ff38883bdc0b8a7f6323aee Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 31 Aug 2023 23:15:29 +0800 Subject: [PATCH] cgen: fix mixed fixed array and array initializing (#19246) --- vlib/v/gen/c/array.v | 36 +++++++++++++++++-- .../mixed_fixed_array_and_array_init_test.v | 24 +++++++++++++ 2 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/mixed_fixed_array_and_array_init_test.v diff --git a/vlib/v/gen/c/array.v b/vlib/v/gen/c/array.v index 41edc9895f..cd1a3536c9 100644 --- a/vlib/v/gen/c/array.v +++ b/vlib/v/gen/c/array.v @@ -53,6 +53,18 @@ fn (mut g Gen) array_init(node ast.ArrayInit, var_name string) { } else { if node.elem_type.has_flag(.option) { g.expr_with_opt(expr, node.expr_types[i], node.elem_type) + } else if elem_type.unaliased_sym.kind == .array_fixed + && expr in [ast.Ident, ast.SelectorExpr] { + g.write('{') + info := elem_type.unaliased_sym.info as ast.ArrayFixed + for idx in 0 .. info.size { + g.expr(expr) + g.write('[${idx}]') + if idx != info.size - 1 { + g.write(', ') + } + } + g.write('}') } else { g.expr_with_cast(expr, node.expr_types[i], node.elem_type) } @@ -153,11 +165,29 @@ fn (mut g Gen) fixed_array_init(node ast.ArrayInit, array_type Type, var_name st } g.write('{') if node.has_val { + elem_type := (array_type.unaliased_sym.info as ast.ArrayFixed).elem_type + elem_sym := g.table.final_sym(elem_type) for i, expr in node.exprs { - if expr.is_auto_deref_var() { - g.write('*') + if elem_sym.kind == .array_fixed && expr in [ast.Ident, ast.SelectorExpr] { + g.write('{') + info := array_type.unaliased_sym.info as ast.ArrayFixed + for idx in 0 .. info.size { + if expr.is_auto_deref_var() { + g.write('*') + } + g.expr(expr) + g.write('[${idx}]') + if idx != info.size - 1 { + g.write(', ') + } + } + g.write('}') + } else { + if expr.is_auto_deref_var() { + g.write('*') + } + g.expr(expr) } - g.expr(expr) if i != node.exprs.len - 1 { g.write(', ') } diff --git a/vlib/v/tests/mixed_fixed_array_and_array_init_test.v b/vlib/v/tests/mixed_fixed_array_and_array_init_test.v new file mode 100644 index 0000000000..dc124c6509 --- /dev/null +++ b/vlib/v/tests/mixed_fixed_array_and_array_init_test.v @@ -0,0 +1,24 @@ +fn test_mixed_fixed_array_and_array_init1() { + a := [0.312, 12.0213]! + b := [0.23, 2131.213]! + ab := [a, b] + println(ab) + assert '${ab}' == '[[0.312, 12.0213], [0.23, 2131.213]]' +} + +fn test_mixed_fixed_array_and_array_init2() { + a := [0.312, 12.0213]! + b := [0.23, 2131.213]! + mut ab := [a] + ab << b + println(ab) + assert '${ab}' == '[[0.312, 12.0213], [0.23, 2131.213]]' +} + +fn test_mixed_fixed_array_and_array_init3() { + a := [0.312, 12.0213]! + b := [0.23, 2131.213]! + mut ab := [a, b]! + println(ab) + assert '${ab}' == '[[0.312, 12.0213], [0.23, 2131.213]]' +}