Skip to content

Commit

Permalink
cgen: fix returns struct with mut fixed array init (with/without gene…
Browse files Browse the repository at this point in the history
…rics) (fix #20361) (#20379)
  • Loading branch information
shove70 committed Jan 4, 2024
1 parent f6112b3 commit 870e618
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
5 changes: 4 additions & 1 deletion vlib/v/gen/c/array.v
Expand Up @@ -1339,9 +1339,12 @@ fn (mut g Gen) fixed_array_var_init(expr ast.Expr, size int) {
g.write('{')
for i in 0 .. size {
if expr.is_auto_deref_var() {
g.write('*')
g.write('(*')
}
g.expr(expr)
if expr.is_auto_deref_var() {
g.write(')')
}
g.write('[${i}]')
if i != size - 1 {
g.write(', ')
Expand Down
5 changes: 3 additions & 2 deletions vlib/v/gen/c/struct.v
Expand Up @@ -600,8 +600,9 @@ fn (mut g Gen) struct_init_field(sfield ast.StructInitField, language ast.Langua
inside_cast_in_heap := g.inside_cast_in_heap
g.inside_cast_in_heap = 0 // prevent use of pointers in child structs

if field_type_sym.kind == .array_fixed && sfield.expr in [ast.Ident, ast.SelectorExpr] {
info := field_type_sym.info as ast.ArrayFixed
field_unwrap_sym := g.table.sym(g.unwrap_generic(sfield.typ))
if field_unwrap_sym.kind == .array_fixed && sfield.expr in [ast.Ident, ast.SelectorExpr] {
info := field_unwrap_sym.info as ast.ArrayFixed
g.fixed_array_var_init(sfield.expr, info.size)
} else {
if sfield.typ != ast.voidptr_type && sfield.typ != ast.nil_type
Expand Down
32 changes: 32 additions & 0 deletions vlib/v/tests/struct_init_with_fixed_array_field_test.v
Expand Up @@ -26,3 +26,35 @@ fn test_struct_init_with_fixed_array_field() {
println(game.board)
assert '${game.board}' == '[x, o, x, o, o, x, x, x, o]'
}

// for issue 20361(part 1): returns struct with init mut fixed array fields without generics
struct Foo {
mut:
buf [3]int
}

pub fn returns_struct_with_mut_fixed_array_init(mut fixed [3]int) Foo {
return Foo{fixed}
}

fn test_returns_struct_with_mut_fixed_array_init() {
mut fixed := [3]int{}
mut foo := returns_struct_with_mut_fixed_array_init(mut fixed)
assert foo.buf == [0, 0, 0]!
}

// for issue 20361(part 2): returns struct with init mut fixed array fields with generics
struct Bar[T] {
mut:
buf T
}

pub fn returns_struct_with_mut_fixed_array_init_with_generics[T](mut fixed T) Bar[T] {
return Bar[T]{fixed}
}

fn test_returns_struct_with_mut_fixed_array_init_with_generics() {
mut fixed := [3]int{}
mut bar := returns_struct_with_mut_fixed_array_init_with_generics(mut fixed)
assert bar.buf == [0, 0, 0]!
}

0 comments on commit 870e618

Please sign in to comment.