From 5b272332fb00d520c60ec6bc959c9a29d832cdc3 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 25 Jan 2025 14:40:09 -0300 Subject: [PATCH] cgen: fix codegen for const fixed array initialization with another const as item (fix #23565) (#23572) --- vlib/v/gen/c/cgen.v | 7 +++++-- vlib/v/gen/c/consts_and_globals.v | 10 ++++++++++ .../consts/const_fixed_array_with_var_item_test.v | 7 +++++++ 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/consts/const_fixed_array_with_var_item_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index cc75bdf57..29b032fde 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -6076,14 +6076,17 @@ fn (mut g Gen) check_expr_is_const(expr ast.Expr) bool { ast.InfixExpr { return g.check_expr_is_const(expr.left) && g.check_expr_is_const(expr.right) } - ast.Ident, ast.StructInit, ast.EnumVal { + ast.Ident { + return expr.kind == .function || g.table.final_sym(expr.obj.typ).kind != .array_fixed + } + ast.StructInit, ast.EnumVal { return true } ast.CastExpr { return g.check_expr_is_const(expr.expr) } ast.PrefixExpr { - return g.check_expr_is_const(expr.right) + return expr.right is ast.Ident || g.check_expr_is_const(expr.right) } else { return false diff --git a/vlib/v/gen/c/consts_and_globals.v b/vlib/v/gen/c/consts_and_globals.v index b6d6c4fca..bb4dc7a9f 100644 --- a/vlib/v/gen/c/consts_and_globals.v +++ b/vlib/v/gen/c/consts_and_globals.v @@ -367,6 +367,16 @@ fn (mut g Gen) const_decl_init_later_msvc_string_fixed_array(mod string, name st elem_typ := g.styp(elem_expr.typ) init.writeln(g.expr_string_surround('\tmemcpy(${cname}[${i}], (${elem_typ})', elem_expr, ', sizeof(${elem_typ}));')) + } else if elem_expr is ast.Ident { + elem_typ := elem_expr.obj.typ + if g.table.final_sym(elem_typ).kind == .array_fixed { + elem_styp := g.styp(elem_expr.obj.typ) + init.writeln(g.expr_string_surround('\tmemcpy(${cname}[${i}], ', elem_expr, + ', sizeof(${elem_styp}));')) + } else { + init.writeln(g.expr_string_surround('\t${cname}[${i}] = ', elem_expr, + ';')) + } } else { init.writeln(g.expr_string_surround('\t${cname}[${i}] = ', elem_expr, ';')) } diff --git a/vlib/v/tests/consts/const_fixed_array_with_var_item_test.v b/vlib/v/tests/consts/const_fixed_array_with_var_item_test.v new file mode 100644 index 000000000..f9bb8ac0b --- /dev/null +++ b/vlib/v/tests/consts/const_fixed_array_with_var_item_test.v @@ -0,0 +1,7 @@ +const f = [u8(0), 1, 2]! + +const ff = [[u8(1), 2, 3]!, [u8(5), 4, 3]!, f]! + +fn test_main() { + assert ff == [[u8(1), 2, 3]!, [u8(5), 4, 3]!, [u8(0), 1, 2]!]! +} -- 2.39.5