Skip to content

Commit

Permalink
cgen: fix option sumtype auto deref (#19919)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Nov 18, 2023
1 parent 976c5fb commit 53e1e5e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
9 changes: 8 additions & 1 deletion vlib/v/gen/c/cgen.v
Expand Up @@ -4465,7 +4465,7 @@ fn (mut g Gen) ident(node ast.Ident) {
g.write('${name}.val')
return
}
is_option = node.info.is_option
is_option = node.info.is_option || (node.obj is ast.Var && node.obj.typ.has_flag(.option))
if node.obj is ast.Var {
is_auto_heap = node.obj.is_auto_heap
&& (!g.is_assign_lhs || g.assign_op != .decl_assign)
Expand All @@ -4479,6 +4479,10 @@ fn (mut g Gen) ident(node ast.Ident) {
g.write('(')
if obj_sym.kind == .sum_type && !is_auto_heap {
g.write('*')
if is_option {
styp := g.base_type(node.obj.typ)
g.write('(*(${styp}*)')
}
} else if g.inside_casting_to_str && g.table.is_interface_var(node.obj) {
g.write('*')
}
Expand All @@ -4504,6 +4508,9 @@ fn (mut g Gen) ident(node ast.Ident) {
sym := g.table.sym(cast_sym.info.types[g.aggregate_type_idx])
g.write('${dot}_${sym.cname}')
} else {
if is_option {
g.write('.data)')
}
g.write('${dot}_${cast_sym.cname}')
}
}
Expand Down
16 changes: 16 additions & 0 deletions vlib/v/tests/option_sumtype_test.v
@@ -0,0 +1,16 @@
pub type TType = []int | string

pub fn teste() ?TType {
return TType([1, 2])
}

fn test_main() {
x := teste()
if x is []int {
dump(x)
y := x as []int
assert y == [1, 2]
return
}
assert false
}

0 comments on commit 53e1e5e

Please sign in to comment.