Skip to content

Commit 2b0938d

Browse files
authored
checker, cgen: fix auto dereference mut variable in if expr (fix #21309) (#21720)
1 parent 4d2c2da commit 2b0938d

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

vlib/v/checker/if.v

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,11 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
420420
if node.typ == ast.void_type {
421421
// first branch of if expression
422422
node.is_expr = true
423-
node.typ = stmt.typ
423+
if stmt.expr.is_auto_deref_var() {
424+
node.typ = stmt.typ.deref()
425+
} else {
426+
node.typ = stmt.typ
427+
}
424428
continue
425429
} else if node.typ in [ast.float_literal_type, ast.int_literal_type] {
426430
if node.typ == ast.int_literal_type {

vlib/v/gen/c/cgen.v

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2186,6 +2186,9 @@ fn (mut g Gen) stmt(node ast.Stmt) {
21862186
// }
21872187
old_is_void_expr_stmt := g.is_void_expr_stmt
21882188
g.is_void_expr_stmt = !node.is_expr
2189+
if node.expr.is_auto_deref_var() {
2190+
g.write('*')
2191+
}
21892192
if node.typ != ast.void_type && g.expected_cast_type != 0
21902193
&& node.expr !in [ast.IfExpr, ast.MatchExpr] {
21912194
g.expr_with_cast(node.expr, node.typ, g.expected_cast_type)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
struct Foo {
2+
str string
3+
}
4+
5+
fn (mut f Foo) foo(f2 Foo) string {
6+
return (if f.str != '' {
7+
f
8+
} else {
9+
f2
10+
}).str
11+
}
12+
13+
fn test_deref_mut_var_in_if_expr() {
14+
mut foo := Foo{}
15+
dump(foo.foo(Foo{ str: 'a' }))
16+
assert foo.foo(Foo{ str: 'a' }) == 'a'
17+
}

0 commit comments

Comments
 (0)