From 985136721ed7532ba0fef984d72a5da325814d09 Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 3 Oct 2024 16:31:36 +0800 Subject: [PATCH] cgen: fix struct fixed array field init with default value (fix #22392) (#22399) --- vlib/v/gen/c/struct.v | 21 ++++++++++ ...fixed_array_init_with_default_value_test.v | 39 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 vlib/v/tests/structs/struct_field_fixed_array_init_with_default_value_test.v diff --git a/vlib/v/gen/c/struct.v b/vlib/v/gen/c/struct.v index 5cc175b91..7a8cecbc3 100644 --- a/vlib/v/gen/c/struct.v +++ b/vlib/v/gen/c/struct.v @@ -387,6 +387,7 @@ fn (mut g Gen) zero_struct_field(field ast.StructField) bool { g.inside_cast_in_heap = old_inside_cast_in_heap } sym := g.table.sym(field.typ) + final_sym := g.table.final_sym(field.typ) field_name := if sym.language == .v { c_name(field.name) } else { field.name } if sym.info is ast.Struct { if sym.info.fields.len == 0 { @@ -450,6 +451,26 @@ fn (mut g Gen) zero_struct_field(field ast.StructField) bool { g.expr_with_tmp_var(field.default_expr, field.default_expr_typ, field.typ, tmp_var) return true + } else if final_sym.info is ast.ArrayFixed && field.default_expr !is ast.ArrayInit { + tmp_var := g.new_tmp_var() + s := g.go_before_last_stmt() + g.empty_line = true + styp := g.typ(field.typ) + g.writeln('${styp} ${tmp_var} = {0};') + g.write('memcpy(${tmp_var}, ') + g.expr(field.default_expr) + g.writeln(', sizeof(${styp}));') + g.empty_line = false + g.write(s) + g.write('{') + for i in 0 .. final_sym.info.size { + g.write('${tmp_var}[${i}]') + if i != final_sym.info.size - 1 { + g.write(', ') + } + } + g.write('}') + return true } g.expr(field.default_expr) } else if field.typ.has_flag(.option) { diff --git a/vlib/v/tests/structs/struct_field_fixed_array_init_with_default_value_test.v b/vlib/v/tests/structs/struct_field_fixed_array_init_with_default_value_test.v new file mode 100644 index 000000000..d7de97aa8 --- /dev/null +++ b/vlib/v/tests/structs/struct_field_fixed_array_init_with_default_value_test.v @@ -0,0 +1,39 @@ +type Mat4 = [16]f32 + +pub fn mat4(x0 f32, x1 f32, x2 f32, x3 f32, x4 f32, x5 f32, x6 f32, x7 f32, x8 f32, x9 f32, x10 f32, x11 f32, x12 f32, x13 f32, x14 f32, x15 f32) Mat4 { + return [ + x0, + x1, + x2, + x3, + x4, + x5, + x6, + x7, + x8, + x9, + x10, + x11, + x12, + x13, + x14, + x15, + ]! +} + +pub fn unit_m4() Mat4 { + return mat4(f32(1), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) +} + +struct GameObject { +mut: + transform Mat4 = unit_m4() +} + +fn test_struct_field_fixed_array_init_with_default_value() { + p := GameObject{} + println(p) + assert p.transform[0] == 1.0 + assert p.transform[1] == 0.0 + assert p.transform[5] == 1.0 +} -- 2.39.5