Skip to content

Commit c22a9eb

Browse files
authored
cgen: fix match option with case non option (fix #24047) (fix #24048) (#24051)
1 parent e491eb0 commit c22a9eb

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

vlib/v/gen/c/cgen.v

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2090,14 +2090,28 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) bool {
20902090
g.writeln(';')
20912091
} else {
20922092
// on assignment or struct field initialization
2093-
ret_typ := if g.inside_struct_init || g.inside_assign {
2093+
inside_assign_context := g.inside_struct_init
2094+
|| g.inside_assign
2095+
|| (!g.inside_return && g.inside_match_option)
2096+
ret_expr_typ := if inside_assign_context {
2097+
stmt.typ
2098+
} else {
2099+
g.fn_decl.return_type
2100+
}
2101+
ret_typ := if inside_assign_context {
20942102
stmt.typ
20952103
} else {
20962104
g.fn_decl.return_type.clear_flag(.option)
20972105
}
20982106
styp = g.base_type(ret_typ)
20992107
if stmt.expr is ast.CallExpr && stmt.expr.is_noreturn {
21002108
g.writeln(';')
2109+
} else if !ret_expr_typ.has_option_or_result()
2110+
&& !stmt.typ.has_option_or_result() && g.last_if_option_type != 0
2111+
&& !g.last_if_option_type.has_option_or_result() {
2112+
g.write('${tmp_var} = ')
2113+
g.expr_with_cast(stmt.expr, stmt.typ, ret_typ)
2114+
g.writeln(';')
21012115
} else {
21022116
g.write('_option_ok(&(${styp}[]) { ')
21032117
g.expr_with_cast(stmt.expr, stmt.typ, ret_typ)

vlib/v/gen/c/if.v

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,11 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
217217
}
218218
g.inside_if_result = true
219219
styp = styp.replace('*', '_ptr')
220+
} else {
221+
g.last_if_option_type = node.typ
222+
defer {
223+
g.last_if_option_type = tmp_if_option_type
224+
}
220225
}
221226
cur_line = g.go_before_last_stmt()
222227
g.empty_line = true
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
fn test_main() {
2+
v := match 12 {
3+
12 {
4+
x := if true { 'b' } else { some_func()? }
5+
assert x == 'b'
6+
x
7+
}
8+
else {
9+
none
10+
}
11+
}
12+
assert v? == 'b'
13+
}
14+
15+
fn some_func() ?string {
16+
return 'a'
17+
}

0 commit comments

Comments
 (0)