Skip to content

Commit

Permalink
cgen: fix code generation when the function returns mut fixed array (fix
Browse files Browse the repository at this point in the history
  • Loading branch information
shove70 committed Jan 3, 2024
1 parent 7c9f9f8 commit 2c824f4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
9 changes: 7 additions & 2 deletions vlib/v/gen/c/cgen.v
Expand Up @@ -5284,7 +5284,7 @@ fn (mut g Gen) return_stmt(node ast.Return) {
g.autofree_scope_vars(node.pos.pos - 1, node.pos.line_nr, true)
g.write('return ')
}
if expr0.is_auto_deref_var() {
if expr0.is_auto_deref_var() && !fn_return_is_fixed_array {
if g.fn_decl.return_type.is_ptr() {
var_str := g.expr_string(expr0)
g.write(var_str.trim('&'))
Expand All @@ -5303,7 +5303,12 @@ fn (mut g Gen) return_stmt(node ast.Return) {
if fn_return_is_fixed_array && !node.types[0].has_flag(.option) {
g.writeln('{0};')
if node.exprs[0] is ast.Ident {
g.write('memcpy(${tmpvar}.ret_arr, ${g.expr_string(node.exprs[0])}, sizeof(${g.typ(node.types[0])})) /*ret*/')
typ := if expr0.is_auto_deref_var() {
node.types[0].deref()
} else {
node.types[0]
}
g.write('memcpy(${tmpvar}.ret_arr, ${g.expr_string(node.exprs[0])}, sizeof(${g.typ(typ)})) /*ret*/')
} else if node.exprs[0] in [ast.ArrayInit, ast.StructInit] {
if node.exprs[0] is ast.ArrayInit && node.exprs[0].is_fixed
&& node.exprs[0].has_init {
Expand Down
11 changes: 11 additions & 0 deletions vlib/v/tests/return_fixed_array_test.v
Expand Up @@ -21,3 +21,14 @@ fn test_without_alias() {
a := return_fixed_array()
assert a == [1, 2, 3]!
}

// for issue 20366: returns mut fixed array
fn returns_mut_fixed_array(mut fixed_array [3]int) [3]int {
return fixed_array
}

fn test_returns_mut_fixed_array() {
mut fixed := [3]int{}
res := returns_mut_fixed_array(mut fixed)
assert res == [0, 0, 0]!
}

0 comments on commit 2c824f4

Please sign in to comment.