Skip to content

Commit

Permalink
checker: add an error for returning an any value in pure V code (pr…
Browse files Browse the repository at this point in the history
…events invalid cgen) (fix #12623) (#22334)
  • Loading branch information
felipensp authored Sep 28, 2024
1 parent 372a402 commit 350846e
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
3 changes: 3 additions & 0 deletions vlib/v/checker/fn.v
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ fn (mut c Checker) fn_decl(mut node ast.FnDecl) {
node.return_type_pos)
}
if node.return_type != ast.void_type {
if node.language == .v && node.return_type.clear_option_and_result() == ast.any_type {
c.error('cannot use type `any` here', node.return_type_pos)
}
if ct_attr_idx := node.attrs.find_comptime_define() {
sexpr := node.attrs[ct_attr_idx].ct_expr.str()
c.error('only functions that do NOT return values can have `[if ${sexpr}]` tags',
Expand Down
42 changes: 42 additions & 0 deletions vlib/v/checker/tests/any_return_type_err.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
vlib/v/checker/tests/any_return_type_err.vv:4:19: error: cannot use type `any` here
2 | }
3 |
4 | fn (f Test) abc() any {
| ~~~
5 | return 0
6 | }
vlib/v/checker/tests/any_return_type_err.vv:8:20: error: cannot use type `any` here
6 | }
7 |
8 | fn (f Test) abc2() ?any {
| ~~~~
9 | return 0
10 | }
vlib/v/checker/tests/any_return_type_err.vv:12:20: error: cannot use type `any` here
10 | }
11 |
12 | fn (f Test) abc3() !any {
| ~~~~
13 | return 0
14 | }
vlib/v/checker/tests/any_return_type_err.vv:16:10: error: cannot use type `any` here
14 | }
15 |
16 | fn foo() any {
| ~~~
17 | return 3
18 | }
vlib/v/checker/tests/any_return_type_err.vv:20:11: error: cannot use type `any` here
18 | }
19 |
20 | fn foo2() ?any {
| ~~~~
21 | return 3
22 | }
vlib/v/checker/tests/any_return_type_err.vv:24:11: error: cannot use type `any` here
22 | }
23 |
24 | fn foo3() !any {
| ~~~~
25 | return 3
26 | }
30 changes: 30 additions & 0 deletions vlib/v/checker/tests/any_return_type_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
struct Test {
}

fn (f Test) abc() any {
return 0
}

fn (f Test) abc2() ?any {
return 0
}

fn (f Test) abc3() !any {
return 0
}

fn foo() any {
return 3
}

fn foo2() ?any {
return 3
}

fn foo3() !any {
return 3
}

fn main() {
println('any ${foo}')
}

0 comments on commit 350846e

Please sign in to comment.