Skip to content

Commit 2d856e7

Browse files
authored
cgen: fix fn (d Struct) a[T]() T { return d } when T is a sumtype (#25644)
1 parent d82e5f6 commit 2d856e7

2 files changed

Lines changed: 24 additions & 3 deletions

File tree

‎vlib/v/gen/c/struct.v‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,13 @@ fn (mut g Gen) struct_init(node ast.StructInit) {
4141
mut sym := g.table.final_sym(unwrapped_typ)
4242
if sym.kind == .sum_type {
4343
if node.typ.has_flag(.generic) && unwrapped_typ.is_ptr() {
44-
g.write('&(')
45-
g.write(g.type_default_sumtype(unwrapped_typ.set_nr_muls(0), sym))
46-
g.write(')')
44+
// handle promotions to a sumtype for generic functions like this one: `fn (d Struct) a[T]() T { return d }`
45+
// the value should be on the heap, since it is not known where it will be used:
46+
sumtype_type := unwrapped_typ.set_nr_muls(0)
47+
sumtype_name := g.styp(sumtype_type)
48+
g.write('HEAP(${sumtype_name}, (')
49+
g.write(g.type_default_sumtype(sumtype_type, sym))
50+
g.write('))')
4751
} else {
4852
g.write(g.type_default_sumtype(unwrapped_typ, sym))
4953
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
struct Struct {}
2+
3+
type SumType = Struct | int
4+
5+
fn (d Struct) a[T]() T {
6+
return T{}
7+
}
8+
9+
fn test_main() {
10+
s := Struct{}
11+
x := s.a[&SumType]()
12+
assert x is Struct
13+
println('first assert passed')
14+
println(x)
15+
assert x is Struct
16+
println('second assert passed')
17+
}

0 commit comments

Comments
 (0)