Skip to content

Commit

Permalink
cgen: fix assigning option of array index
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Jan 13, 2025
1 parent d2b30df commit 389616c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
6 changes: 6 additions & 0 deletions vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -6718,6 +6718,12 @@ fn (mut g Gen) gen_or_block_stmts(cvar_name string, cast_typ string, stmts []ast
if expr_stmt.expr.is_return_used {
g.write('*(${cast_typ}*) ${cvar_name}.data = ')
}
} else if g.inside_opt_or_res && return_is_option && g.inside_assign {
g.write('_option_ok(&(${cast_typ}[]) { ')
g.expr_with_cast(expr_stmt.expr, expr_stmt.typ, return_type.clear_option_and_result())
g.writeln(' }, (${g.styp(return_type)}*)${cvar_name}.data, sizeof(${cast_typ}));')
g.indent--
return
} else {
g.write('*(${cast_typ}*) ${cvar_name}.data = ')
}
Expand Down
10 changes: 10 additions & 0 deletions vlib/v/tests/assign/assign_option_of_array_index_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
fn make_option() ?string {
return none
}

fn test_assign_option_of_array_index() {
arr := [make_option()]
unwrapped := arr[99] or { 'unknown' } // <- out of bounds access!
println('... ${unwrapped}')
assert '${unwrapped}' == "Option('unknown')"
}

0 comments on commit 389616c

Please sign in to comment.