Skip to content

Commit 9851367

Browse files
authored
cgen: fix struct fixed array field init with default value (fix #22392) (#22399)
1 parent e242584 commit 9851367

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

vlib/v/gen/c/struct.v

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,7 @@ fn (mut g Gen) zero_struct_field(field ast.StructField) bool {
387387
g.inside_cast_in_heap = old_inside_cast_in_heap
388388
}
389389
sym := g.table.sym(field.typ)
390+
final_sym := g.table.final_sym(field.typ)
390391
field_name := if sym.language == .v { c_name(field.name) } else { field.name }
391392
if sym.info is ast.Struct {
392393
if sym.info.fields.len == 0 {
@@ -450,6 +451,26 @@ fn (mut g Gen) zero_struct_field(field ast.StructField) bool {
450451
g.expr_with_tmp_var(field.default_expr, field.default_expr_typ, field.typ,
451452
tmp_var)
452453
return true
454+
} else if final_sym.info is ast.ArrayFixed && field.default_expr !is ast.ArrayInit {
455+
tmp_var := g.new_tmp_var()
456+
s := g.go_before_last_stmt()
457+
g.empty_line = true
458+
styp := g.typ(field.typ)
459+
g.writeln('${styp} ${tmp_var} = {0};')
460+
g.write('memcpy(${tmp_var}, ')
461+
g.expr(field.default_expr)
462+
g.writeln(', sizeof(${styp}));')
463+
g.empty_line = false
464+
g.write(s)
465+
g.write('{')
466+
for i in 0 .. final_sym.info.size {
467+
g.write('${tmp_var}[${i}]')
468+
if i != final_sym.info.size - 1 {
469+
g.write(', ')
470+
}
471+
}
472+
g.write('}')
473+
return true
453474
}
454475
g.expr(field.default_expr)
455476
} else if field.typ.has_flag(.option) {
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
type Mat4 = [16]f32
2+
3+
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 {
4+
return [
5+
x0,
6+
x1,
7+
x2,
8+
x3,
9+
x4,
10+
x5,
11+
x6,
12+
x7,
13+
x8,
14+
x9,
15+
x10,
16+
x11,
17+
x12,
18+
x13,
19+
x14,
20+
x15,
21+
]!
22+
}
23+
24+
pub fn unit_m4() Mat4 {
25+
return mat4(f32(1), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
26+
}
27+
28+
struct GameObject {
29+
mut:
30+
transform Mat4 = unit_m4()
31+
}
32+
33+
fn test_struct_field_fixed_array_init_with_default_value() {
34+
p := GameObject{}
35+
println(p)
36+
assert p.transform[0] == 1.0
37+
assert p.transform[1] == 0.0
38+
assert p.transform[5] == 1.0
39+
}

0 commit comments

Comments
 (0)