cgen: fix codegen for match with sumtype ptrptr (fix #23776) (#23785)

This commit is contained in:
Felipe Pena 2025-02-22 20:00:14 -03:00 committed by GitHub
parent 3f44780be4
commit ffdc1ab702
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 38 additions and 0 deletions

View File

@ -3904,6 +3904,9 @@ fn (mut g Gen) typeof_expr(node ast.TypeOf) {
// When encountering a .sum_type, typeof() should be done at runtime,
// because the subtype of the expression may change:
g.write('charptr_vstring_literal(v_typeof_sumtype_${sym.cname}( (')
if typ.nr_muls() > 0 {
g.write('*'.repeat(typ.nr_muls()))
}
g.expr(node.expr)
g.write(')._typ ))')
} else if sym.kind == .array_fixed {

View File

@ -208,7 +208,14 @@ fn (mut g Gen) match_expr_sumtype(node ast.MatchExpr, is_expr bool, cond_var str
g.write_v_source_line_info(branch)
g.write('if (')
}
need_deref := node.cond_type.nr_muls() > 1
if need_deref {
g.write2('(', '*'.repeat(node.cond_type.nr_muls() - 1))
}
g.write(cond_var)
if need_deref {
g.write(')')
}
cur_expr := unsafe { &branch.exprs[sumtype_index] }
if cond_sym.kind == .sum_type {
g.write('${dot_or_ptr}_typ == ')

View File

@ -0,0 +1,28 @@
pub type Command = Assign | Call
pub struct Assign {}
pub struct Call {
mut:
text string
}
fn test_main() {
mut command_arr_ptr := [&Command(Call{})]
mut command_arr_el_ptr := &command_arr_ptr[0] // type is && ?
match mut command_arr_el_ptr {
Call {
command_arr_el_ptr.text = 'foo'
}
Assign {}
}
if mut command_arr_el_ptr is Call {
assert command_arr_el_ptr.text == 'foo'
} else {
assert false
}
assert typeof(command_arr_el_ptr) == 'Call'
assert typeof(command_arr_ptr) == '[]&Command'
}