Skip to content

Commit

Permalink
cgen: fix struct field init with optional fixed array
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Dec 18, 2024
1 parent afc07f4 commit c9522fc
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
12 changes: 12 additions & 0 deletions vlib/v/gen/c/assign.v
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,18 @@ fn (mut g Gen) expr_with_opt(expr ast.Expr, expr_typ ast.Type, ret_typ ast.Type)
return ''
}

fn (mut g Gen) expr_with_fixed_array_opt(expr ast.Expr, expr_typ ast.Type, ret_typ ast.Type) {
tmp_var := g.new_tmp_var()
stmt_str := g.go_before_last_stmt().trim_space()
styp := g.styp(expr_typ)
g.empty_line = true
g.writeln('${styp} ${tmp_var} = {.state = 0};')
g.write('memcpy(${tmp_var}.data, ')
g.expr(expr)
g.writeln(', sizeof(${g.styp(ret_typ)}));')
g.write2(stmt_str, tmp_var)
}

fn (mut g Gen) assign_stmt(node_ ast.AssignStmt) {
mut node := unsafe { node_ }
if node.is_static {
Expand Down
12 changes: 9 additions & 3 deletions vlib/v/gen/c/struct.v
Original file line number Diff line number Diff line change
Expand Up @@ -692,9 +692,15 @@ fn (mut g Gen) struct_init_field(sfield ast.StructInitField, language ast.Langua
field_unwrap_sym.info.elem_type, field_unwrap_sym.info.size)
}
ast.CastExpr, ast.CallExpr {
tmp_var := g.expr_with_var(sfield.expr, sfield.expected_type, false)
g.fixed_array_var_init(tmp_var, false, field_unwrap_sym.info.elem_type,
field_unwrap_sym.info.size)
if sfield.expected_type.has_flag(.option) && !field_unwrap_typ.has_flag(.option) {
g.expr_with_fixed_array_opt(sfield.expr, sfield.expected_type,
field_unwrap_typ)
} else {
tmp_var := g.expr_with_var(sfield.expr, sfield.expected_type,
false)
g.fixed_array_var_init(tmp_var, false, field_unwrap_sym.info.elem_type,
field_unwrap_sym.info.size)
}
}
ast.ArrayInit {
if sfield.expr.has_index {
Expand Down
15 changes: 15 additions & 0 deletions vlib/v/tests/structs/struct_field_init_with_fixed_array_opt_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
type Arr = [4]u8

struct Foo {
bar int
baz ?Arr
}

fn test_struct_field_init_with_fixed_array_opt() {
f := Foo{
bar: 1
baz: Arr([u8(5), 4, 3, 2]!)
}
println(f)
assert f.baz as Arr == [u8(5), 4, 3, 2]!
}

0 comments on commit c9522fc

Please sign in to comment.