@@ -41,6 +41,7 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
41
41
mut ret_type := ast.void_type
42
42
mut nbranches_with_return := 0
43
43
mut nbranches_without_return := 0
44
+ mut must_be_option := false
44
45
for mut branch in node.branches {
45
46
if node.is_expr {
46
47
c.stmts_ending_with_expression (mut branch.stmts, c.expected_or_type)
@@ -77,6 +78,7 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
77
78
c.expr (mut stmt.expr)
78
79
})
79
80
unwrapped_expected_type := c.unwrap_generic (node.expected_type)
81
+ must_be_option = must_be_option || expr_type == ast.none_type
80
82
stmt.typ = expr_type
81
83
if first_iteration {
82
84
if unwrapped_expected_type.has_option_or_result ()
@@ -127,6 +129,9 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
127
129
}
128
130
}
129
131
}
132
+ if must_be_option && ret_type == ast.none_type && expr_type != ret_type {
133
+ ret_type = expr_type.set_flag (.option)
134
+ }
130
135
if stmt.typ != ast.error_type && ! is_noreturn_callexpr (stmt.expr) {
131
136
ret_sym := c.table.sym (ret_type)
132
137
stmt_sym := c.table.sym (stmt.typ)
@@ -249,7 +254,7 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
249
254
c.error ('invalid match expression, must supply at least one value other than `none`' ,
250
255
node.pos)
251
256
}
252
- node.return_type = ret_type
257
+ node.return_type = if must_be_option { ret_type. set_flag (.option) } else { ret_type }
253
258
cond_var := c.get_base_name (& node.cond)
254
259
if cond_var != '' {
255
260
mut cond_is_auto_heap := false
@@ -268,7 +273,7 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
268
273
}
269
274
}
270
275
}
271
- return ret_type
276
+ return node.return_type
272
277
}
273
278
274
279
fn (mut c Checker) check_match_branch_last_stmt (last_stmt ast.ExprStmt, ret_type ast.Type, expr_type ast.Type) {
@@ -285,8 +290,10 @@ fn (mut c Checker) check_match_branch_last_stmt(last_stmt ast.ExprStmt, ret_type
285
290
return
286
291
}
287
292
}
288
- c.error ('return type mismatch, it should be `${ret_sym.name} `, but it is instead `${c.table.type_to_str(expr_type)} `' ,
289
- last_stmt.pos)
293
+ if expr_type != ast.none_type && ret_type != ast.none_type {
294
+ c.error ('return type mismatch, it should be `${ret_sym.name} `, but it is instead `${c.table.type_to_str(expr_type)} `' ,
295
+ last_stmt.pos)
296
+ }
290
297
}
291
298
} else if expr_type == ast.void_type && ret_type.idx () == ast.void_type_idx
292
299
&& ret_type.has_option_or_result () {
0 commit comments