Skip to content

Commit

Permalink
cgen: fix map_set codegen for sumtype array variant with autofree (fix
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp authored Oct 17, 2024
1 parent ae04167 commit 8054808
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
15 changes: 14 additions & 1 deletion vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -3070,7 +3070,17 @@ fn (mut g Gen) gen_clone_assignment(var_type ast.Type, val ast.Expr, typ ast.Typ
if typ.share() == .shared_t {
g.write('(${shared_styp}*)__dup_shared_array(&(${shared_styp}){.mtx = {0}, .val =')
}
g.write(' array_clone_static_to_depth(')
is_sumtype := g.table.type_kind(var_type) == .sum_type
if is_sumtype {
variant_typ := g.typ(typ).replace('*', '')
fn_name := g.get_sumtype_casting_fn(typ, var_type)
g.write('${fn_name}(ADDR(${variant_typ}, array_clone_static_to_depth(')
if typ.is_ptr() {
g.write('*')
}
} else {
g.write(' array_clone_static_to_depth(')
}
g.expr(val)
if typ.share() == .shared_t {
g.write('->val')
Expand All @@ -3081,6 +3091,9 @@ fn (mut g Gen) gen_clone_assignment(var_type ast.Type, val ast.Expr, typ ast.Typ
if typ.share() == .shared_t {
g.write('}, sizeof(${shared_styp}))')
}
if is_sumtype {
g.write('))')
}
} else if right_sym.kind == .string {
// `str1 = str2` => `str1 = str2.clone()`
if var_type.has_flag(.option) {
Expand Down
29 changes: 29 additions & 0 deletions vlib/v/tests/sumtypes/sumtype_map_set_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
module main

pub type Value = f64 | []Value

fn test_no_ref() {
mut m := map[string]Value{}
var := Value([Value(1.0), Value(2.0), Value(3.0)])
arr := (var as []Value)
m['var'] = arr
dump(m)
if item := m['var'] {
assert (item as []Value)[1] == Value(2.0)
} else {
assert false
}
}

fn test_ref() {
mut m := map[string]Value{}
var := Value([Value(1.0), Value(2.0), Value(3.0)])
arr := &(var as []Value)
m['var'] = arr
dump(m)
if item := m['var'] {
assert (item as []Value)[1] == Value(2.0)
} else {
assert false
}
}

0 comments on commit 8054808

Please sign in to comment.