Skip to content

Commit

Permalink
checker, cgen: fix auto dereference mut variable in if expr (fix vlan…
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 authored and raw-bin committed Jul 2, 2024
1 parent 66d3cc1 commit ec83816
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
6 changes: 5 additions & 1 deletion vlib/v/checker/if.v
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,11 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
if node.typ == ast.void_type {
// first branch of if expression
node.is_expr = true
node.typ = stmt.typ
if stmt.expr.is_auto_deref_var() {
node.typ = stmt.typ.deref()
} else {
node.typ = stmt.typ
}
continue
} else if node.typ in [ast.float_literal_type, ast.int_literal_type] {
if node.typ == ast.int_literal_type {
Expand Down
3 changes: 3 additions & 0 deletions vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -2186,6 +2186,9 @@ fn (mut g Gen) stmt(node ast.Stmt) {
// }
old_is_void_expr_stmt := g.is_void_expr_stmt
g.is_void_expr_stmt = !node.is_expr
if node.expr.is_auto_deref_var() {
g.write('*')
}
if node.typ != ast.void_type && g.expected_cast_type != 0
&& node.expr !in [ast.IfExpr, ast.MatchExpr] {
g.expr_with_cast(node.expr, node.typ, g.expected_cast_type)
Expand Down
17 changes: 17 additions & 0 deletions vlib/v/tests/deref_mut_variable_in_if_expr_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
struct Foo {
str string
}

fn (mut f Foo) foo(f2 Foo) string {
return (if f.str != '' {
f
} else {
f2
}).str
}

fn test_deref_mut_var_in_if_expr() {
mut foo := Foo{}
dump(foo.foo(Foo{ str: 'a' }))
assert foo.foo(Foo{ str: 'a' }) == 'a'
}

0 comments on commit ec83816

Please sign in to comment.