From 89fe82b7322418b3bdfe31c4ef1c40a08c953692 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20D=C3=A4schle?= Date: Thu, 5 May 2022 16:02:49 +0200 Subject: [PATCH] checker: fix returning error on reference results (#14313) --- vlib/v/checker/return.v | 9 ++++++--- vlib/v/tests/results_test.v | 8 ++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/vlib/v/checker/return.v b/vlib/v/checker/return.v index 08fce331e0..ae01f2f471 100644 --- a/vlib/v/checker/return.v +++ b/vlib/v/checker/return.v @@ -24,6 +24,7 @@ pub fn (mut c Checker) return_stmt(mut node ast.Return) { return } exp_is_optional := expected_type.has_flag(.optional) + exp_is_result := expected_type.has_flag(.result) mut expected_types := [expected_type] if expected_type_sym.info is ast.MultiReturn { expected_types = expected_type_sym.info.types @@ -72,11 +73,13 @@ pub fn (mut c Checker) return_stmt(mut node ast.Return) { } } } - // allow `none` & `error` return types for function that returns optional + // allow `none` & `error` return types for function that returns option or result option_type_idx := c.table.type_idxs['Option'] + result_type_idx := c.table.type_idxs['_result'] got_types_0_idx := got_types[0].idx() - if exp_is_optional - && got_types_0_idx in [ast.none_type_idx, ast.error_type_idx, option_type_idx] { + if (exp_is_optional + && got_types_0_idx in [ast.none_type_idx, ast.error_type_idx, option_type_idx]) + || (exp_is_result && got_types_0_idx in [ast.error_type_idx, result_type_idx]) { if got_types_0_idx == ast.none_type_idx && expected_type == ast.ovoid_type { c.error('returning `none` in functions, that have a `?` result type is not allowed anymore, either `return error(message)` or just `return` instead', node.pos) diff --git a/vlib/v/tests/results_test.v b/vlib/v/tests/results_test.v index e8d20a67c9..defee142a8 100644 --- a/vlib/v/tests/results_test.v +++ b/vlib/v/tests/results_test.v @@ -73,3 +73,11 @@ fn unsafe_return_error() !int { fn test_unsafe_return_error() { unsafe_return_error() or { assert err.msg() == 'abc' } } + +fn return_reference_type(path string) !&string { + if path.len == 0 { + return error('vfopen called with ""') + } + str := '' + return &str +}