Skip to content

Commit cb44f59

Browse files
authored
checker, cgen: fix error for if expr with generic sumtype (#14056)
1 parent 4f14f77 commit cb44f59

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

vlib/v/checker/if.v

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
204204
}
205205
}
206206
if node.is_expr && c.table.sym(former_expected_type).kind == .sum_type {
207+
node.typ = former_expected_type
207208
continue
208209
}
209210
if is_noreturn_callexpr(last_expr.expr) {

vlib/v/gen/c/if.v

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,12 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
7474
g.expr(branch.cond)
7575
g.write(' ? ')
7676
}
77+
prev_expected_cast_type := g.expected_cast_type
78+
if node.is_expr && g.table.sym(node.typ).kind == .sum_type {
79+
g.expected_cast_type = node.typ
80+
}
7781
g.stmts(branch.stmts)
82+
g.expected_cast_type = prev_expected_cast_type
7883
}
7984
if node.branches.len == 1 {
8085
g.write(': 0')
@@ -195,11 +200,12 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
195200
}
196201
}
197202
if needs_tmp_var {
203+
prev_expected_cast_type := g.expected_cast_type
198204
if node.is_expr && g.table.sym(node.typ).kind == .sum_type {
199205
g.expected_cast_type = node.typ
200206
}
201207
g.stmts_with_tmp_var(branch.stmts, tmp)
202-
g.expected_cast_type = 0
208+
g.expected_cast_type = prev_expected_cast_type
203209
} else {
204210
// restore if_expr stmt header pos
205211
stmt_pos := g.nth_stmt_pos(0)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
type Opt<T> = None<T> | Some<T>
2+
3+
struct None<T> {}
4+
5+
struct Some<T> {
6+
mut:
7+
value T
8+
}
9+
10+
fn operation(r int) Opt<int> {
11+
return if r > 0 { Some<int>{r} } else { None<int>{} }
12+
}
13+
14+
fn test_if_expr_with_generic_sumtype() {
15+
op := operation(1)
16+
assert Opt<int>(Some<int>{1}) == op
17+
}

0 commit comments

Comments
 (0)