1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: fix casting sumtype as fntype (#15612)

This commit is contained in:
yuyi 2022-08-31 15:45:47 +08:00 committed by GitHub
parent 64f403e997
commit 4d6b8cbfd8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 39 additions and 13 deletions

View File

@ -2103,9 +2103,12 @@ fn (mut g Gen) write_sumtype_casting_fn(fun SumtypeCastingFn) {
got, exp := fun.got, fun.exp got, exp := fun.got, fun.exp
got_sym, exp_sym := g.table.sym(got), g.table.sym(exp) got_sym, exp_sym := g.table.sym(got), g.table.sym(exp)
mut got_cname, exp_cname := got_sym.cname, exp_sym.cname mut got_cname, exp_cname := got_sym.cname, exp_sym.cname
mut type_idx := g.type_sidx(got)
if got_sym.info is ast.FnType { if got_sym.info is ast.FnType {
if got_sym.info.is_anon { if got_sym.info.is_anon {
got_name := 'fn ${g.table.fn_type_source_signature(got_sym.info.func)}'
got_cname = 'anon_fn_${g.table.fn_type_signature(got_sym.info.func)}' got_cname = 'anon_fn_${g.table.fn_type_signature(got_sym.info.func)}'
type_idx = g.table.type_idxs[got_name].str()
} }
} }
mut sb := strings.new_builder(128) mut sb := strings.new_builder(128)
@ -2128,7 +2131,7 @@ fn (mut g Gen) write_sumtype_casting_fn(fun SumtypeCastingFn) {
// if the variable is not used, the C compiler will optimize it away // if the variable is not used, the C compiler will optimize it away
sb.writeln('\t$embed_cname* ${embed_name}_ptr = memdup($accessor, sizeof($embed_cname));') sb.writeln('\t$embed_cname* ${embed_name}_ptr = memdup($accessor, sizeof($embed_cname));')
} }
sb.write_string('\treturn ($exp_cname){ ._$got_cname = ptr, ._typ = ${g.type_sidx(got)}') sb.write_string('\treturn ($exp_cname){ ._$got_cname = ptr, ._typ = $type_idx')
for field in (exp_sym.info as ast.SumType).fields { for field in (exp_sym.info as ast.SumType).fields {
mut ptr := 'ptr' mut ptr := 'ptr'
mut type_cname := got_cname mut type_cname := got_cname

View File

@ -1,2 +1,6 @@
Fn Fn(fn () int)
Fn Fn(fn (int) int)
123
123
321
321

View File

@ -1,13 +1,32 @@
type Fn = fn () int | fn (int) int type Fn = fn () int | fn (int) int
fn main() { fn abc(n int) Fn {
f1 := Fn(fn (a int) int { if n == 1 {
return a return fn () int {
}) return 123
println(typeof(f1).name) }
} else {
f2 := Fn(fn () int { return fn (x int) int {
return 22 return x
}) }
println(typeof(f2).name) }
}
fn main() {
println(abc(1))
println(abc(2))
x1 := abc(1)
y1 := x1 as fn () int
println(y1())
if x1 is fn () int {
println(x1())
}
x2 := abc(2)
y2 := x2 as fn (int) int
println(y2(321))
if x2 is fn (int) int {
println(x2(321))
}
} }