ast, cgen: fix as cast with call expr (fix #19453) (#19462)

This commit is contained in:
yuyi 2023-09-29 16:59:14 +08:00 committed by GitHub
parent b5f71dffe4
commit 74997fd824
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 43 additions and 2 deletions

View file

@ -255,7 +255,8 @@ const (
'do_not_remove', 'do_not_remove',
'vlib/v/tests/const_fixed_array_containing_references_to_itself_test.v', // error C2099: initializer is not a constant 'vlib/v/tests/const_fixed_array_containing_references_to_itself_test.v', // error C2099: initializer is not a constant
'vlib/v/tests/const_and_global_with_same_name_test.v', // error C2099: initializer is not a constant 'vlib/v/tests/const_and_global_with_same_name_test.v', // error C2099: initializer is not a constant
'vlib/v/tests/sumtype_as_cast_test.v', // error: cannot support compound statement expression ({expr; expr; expr;}) 'vlib/v/tests/sumtype_as_cast_1_test.v', // error: cannot support compound statement expression ({expr; expr; expr;})
'vlib/v/tests/sumtype_as_cast_2_test.v', // error: cannot support compound statement expression ({expr; expr; expr;})
'vlib/v/tests/project_with_cpp_code/compiling_cpp_files_with_a_cplusplus_compiler_test.v', // TODO 'vlib/v/tests/project_with_cpp_code/compiling_cpp_files_with_a_cplusplus_compiler_test.v', // TODO
] ]
skip_on_windows = [ skip_on_windows = [

View file

@ -2079,6 +2079,15 @@ pub fn (e &Expr) is_lockable() bool {
} }
} }
// returns if an expression has call expr`
pub fn (e &Expr) has_fn_call() bool {
return match e {
CallExpr { true }
SelectorExpr { e.expr.has_fn_call() }
else { false }
}
}
// CTempVar is used in cgen only, to hold nodes for temporary variables // CTempVar is used in cgen only, to hold nodes for temporary variables
pub struct CTempVar { pub struct CTempVar {
pub: pub:

View file

@ -6564,7 +6564,7 @@ fn (mut g Gen) as_cast(node ast.AsCast) {
mut expr_type_sym := g.table.sym(g.unwrap_generic(node.expr_type)) mut expr_type_sym := g.table.sym(g.unwrap_generic(node.expr_type))
if mut expr_type_sym.info is ast.SumType { if mut expr_type_sym.info is ast.SumType {
dot := if node.expr_type.is_ptr() { '->' } else { '.' } dot := if node.expr_type.is_ptr() { '->' } else { '.' }
if node.expr is ast.CallExpr && !g.is_cc_msvc { if node.expr.has_fn_call() && !g.is_cc_msvc {
tmp_var := g.new_tmp_var() tmp_var := g.new_tmp_var()
expr_styp := g.typ(node.expr_type) expr_styp := g.typ(node.expr_type)
g.write('({ ${expr_styp} ${tmp_var} = ') g.write('({ ${expr_styp} ${tmp_var} = ')

View file

@ -0,0 +1,31 @@
type Numbers = int | string
struct Values {
value Numbers
}
struct Wrapper {
element []Values
mut:
index int
}
fn (mut instance Wrapper) get() Values {
instance.index++
return instance.element[0]
}
fn test_sumtype_as_cast() {
mut wrapper := Wrapper{
element: [
Values{
value: 1
},
Values{
value: '2'
},
]
}
println(wrapper.get().value as int)
assert wrapper.index == 1
}