From ab04a589febb158bb9f28bc37292f35dd3af1451 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 2 Dec 2023 11:05:38 -0300 Subject: [PATCH] parser: add a more precise and helpful error message for `int!` and `int?` result type syntax (#20061) --- vlib/v/checker/tests/wrong_option_type.out | 5 +++++ vlib/v/checker/tests/wrong_option_type.vv | 3 +++ vlib/v/checker/tests/wrong_result_type.out | 5 +++++ vlib/v/checker/tests/wrong_result_type.vv | 3 +++ vlib/v/parser/fn.v | 7 +++++++ 5 files changed, 23 insertions(+) create mode 100644 vlib/v/checker/tests/wrong_option_type.out create mode 100644 vlib/v/checker/tests/wrong_option_type.vv create mode 100644 vlib/v/checker/tests/wrong_result_type.out create mode 100644 vlib/v/checker/tests/wrong_result_type.vv diff --git a/vlib/v/checker/tests/wrong_option_type.out b/vlib/v/checker/tests/wrong_option_type.out new file mode 100644 index 000000000..6ad0b4d49 --- /dev/null +++ b/vlib/v/checker/tests/wrong_option_type.out @@ -0,0 +1,5 @@ +vlib/v/checker/tests/wrong_option_type.vv:1:10: error: wrong syntax, it must be ?int, not int? + 1 | fn foo() int?{ + | ~~~ + 2 | return 0 + 3 | } diff --git a/vlib/v/checker/tests/wrong_option_type.vv b/vlib/v/checker/tests/wrong_option_type.vv new file mode 100644 index 000000000..5ebf6810f --- /dev/null +++ b/vlib/v/checker/tests/wrong_option_type.vv @@ -0,0 +1,3 @@ +fn foo() int?{ + return 0 +} \ No newline at end of file diff --git a/vlib/v/checker/tests/wrong_result_type.out b/vlib/v/checker/tests/wrong_result_type.out new file mode 100644 index 000000000..ee638e1da --- /dev/null +++ b/vlib/v/checker/tests/wrong_result_type.out @@ -0,0 +1,5 @@ +vlib/v/checker/tests/wrong_result_type.vv:1:10: error: wrong syntax, it must be !int, not int! + 1 | fn foo() int!{ + | ~~~ + 2 | return 0 + 3 | } diff --git a/vlib/v/checker/tests/wrong_result_type.vv b/vlib/v/checker/tests/wrong_result_type.vv new file mode 100644 index 000000000..9469c16e0 --- /dev/null +++ b/vlib/v/checker/tests/wrong_result_type.vv @@ -0,0 +1,3 @@ +fn foo() int!{ + return 0 +} \ No newline at end of file diff --git a/vlib/v/parser/fn.v b/vlib/v/parser/fn.v index a6758ea86..272386871 100644 --- a/vlib/v/parser/fn.v +++ b/vlib/v/parser/fn.v @@ -440,7 +440,14 @@ fn (mut p Parser) fn_decl() ast.FnDecl { return_type = p.parse_type() p.inside_fn_return = false return_type_pos = return_type_pos.extend(p.prev_tok.pos()) + + if p.tok.kind in [.question, .not] { + ret_type_sym := p.table.sym(return_type) + p.error_with_pos('wrong syntax, it must be ${p.tok.kind}${ret_type_sym.name}, not ${ret_type_sym.name}${p.tok.kind}', + return_type_pos) + } } + if p.tok.kind == .comma { mr_pos := return_type_pos.extend(p.peek_tok.pos()) p.error_with_pos('multiple return types in function declaration must use parentheses, e.g. (int, string)', -- 2.39.5