Skip to content

Commit

Permalink
ast, cgen: fix as cast with call expr (fix #19453) (#19462)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Sep 29, 2023
1 parent b5f71df commit 74997fd
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 2 deletions.
3 changes: 2 additions & 1 deletion cmd/tools/vtest-self.v
Expand Up @@ -255,7 +255,8 @@ const (
'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_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
]
skip_on_windows = [
Expand Down
9 changes: 9 additions & 0 deletions vlib/v/ast/ast.v
Expand Up @@ -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
pub struct CTempVar {
pub:
Expand Down
2 changes: 1 addition & 1 deletion vlib/v/gen/c/cgen.v
Expand Up @@ -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))
if mut expr_type_sym.info is ast.SumType {
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()
expr_styp := g.typ(node.expr_type)
g.write('({ ${expr_styp} ${tmp_var} = ')
Expand Down
File renamed without changes.
31 changes: 31 additions & 0 deletions vlib/v/tests/sumtype_as_cast_2_test.v
@@ -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
}

0 comments on commit 74997fd

Please sign in to comment.