diff --git a/vlib/v/checker/return.v b/vlib/v/checker/return.v index 1ca9a846fd..f263ff5d11 100644 --- a/vlib/v/checker/return.v +++ b/vlib/v/checker/return.v @@ -104,6 +104,12 @@ pub fn (mut c Checker) return_stmt(mut node ast.Return) { c.error('cannot use `${c.table.type_to_str(got_typ)}` as type `${c.table.type_to_str(exp_type)}` in return argument', pos) } + if got_typ.has_flag(.result) && (!exp_type.has_flag(.result) + || c.table.type_to_str(got_typ) != c.table.type_to_str(exp_type)) { + pos := node.exprs[expr_idxs[i]].pos() + c.error('cannot use `${c.table.type_to_str(got_typ)}` as type `${c.table.type_to_str(exp_type)}` in return argument', + pos) + } if node.exprs[expr_idxs[i]] !is ast.ComptimeCall && !c.check_types(got_typ, exp_type) { got_typ_sym := c.table.sym(got_typ) mut exp_typ_sym := c.table.sym(exp_type) diff --git a/vlib/v/checker/tests/return_result_type_mismatch.out b/vlib/v/checker/tests/return_result_type_mismatch.out new file mode 100644 index 0000000000..a659431644 --- /dev/null +++ b/vlib/v/checker/tests/return_result_type_mismatch.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/return_result_type_mismatch.vv:8:9: error: cannot use `!int` as type `?int` in return argument + 6 | // Option + 7 | fn bar(a int) ?int { + 8 | return foo(a) + | ~~~~~~ + 9 | } + 10 | diff --git a/vlib/v/checker/tests/return_result_type_mismatch.vv b/vlib/v/checker/tests/return_result_type_mismatch.vv new file mode 100644 index 0000000000..4d06d2cef2 --- /dev/null +++ b/vlib/v/checker/tests/return_result_type_mismatch.vv @@ -0,0 +1,14 @@ +// Result +fn foo(a int) !int { + return a + 1 +} + +// Option +fn bar(a int) ?int { + return foo(a) +} + +fn main() { + x := bar(1)? + println('$x') +}