From 584597aa3d678d814f73428f87db0485559c4c33 Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 12 Aug 2022 22:23:14 +0800 Subject: [PATCH] checker: check mismatch of return result type (#15413) --- vlib/v/checker/return.v | 6 ++++++ .../checker/tests/return_result_type_mismatch.out | 7 +++++++ .../v/checker/tests/return_result_type_mismatch.vv | 14 ++++++++++++++ 3 files changed, 27 insertions(+) create mode 100644 vlib/v/checker/tests/return_result_type_mismatch.out create mode 100644 vlib/v/checker/tests/return_result_type_mismatch.vv diff --git a/vlib/v/checker/return.v b/vlib/v/checker/return.v index 1ca9a846f..f263ff5d1 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 000000000..a65943164 --- /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 000000000..4d06d2cef --- /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') +} -- 2.39.5