checker: check reference return to be really reference (#7739)

pull/7750/head
Uwe Krüger 2020-12-31 12:42:22 +01:00 committed by GitHub
parent a9ab79d301
commit 74ea5ac99f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 42 additions and 1 deletions

View File

@ -52,7 +52,7 @@ pub mut:
// so that the user can set callbacks, read meta information, etc.
pub fn info() &LiveReloadInfo {
if C.g_live_info != 0 {
return C.g_live_info
return &LiveReloadInfo(C.g_live_info)
}
// When the current program is not compiled with -live, simply
// return a new empty struct LiveReloadInfo in order to prevent

View File

@ -2047,6 +2047,12 @@ pub fn (mut c Checker) return_stmt(mut return_stmt ast.Return) {
c.error('fn `$c.cur_fn.name` expects you to return a non reference type `${c.table.type_to_str(exp_type)}`, but you are returning `${c.table.type_to_str(got_typ)}` instead',
pos)
}
if (exp_type.is_ptr() || exp_type.is_pointer()) &&
(!got_typ.is_ptr() && !got_typ.is_pointer()) && got_typ != table.any_int_type {
pos := return_stmt.exprs[i].position()
c.error('fn `$c.cur_fn.name` expects you to return a reference type `${c.table.type_to_str(exp_type)}`, but you are returning `${c.table.type_to_str(got_typ)}` instead',
pos)
}
}
if exp_is_optional && return_stmt.exprs.len > 0 {
expr0 := return_stmt.exprs[0]

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/reference_return.vv:6:9: error: fn `f` expects you to return a reference type `&Aa`, but you are returning `Aa` instead
4 |
5 | fn f() &Aa {
6 | return Aa{
| ~~~
7 | a: 1
8 | }

View File

@ -0,0 +1,14 @@
struct Aa {
a int
}
fn f() &Aa {
return Aa{
a: 1
}
}
fn main() {
x := f()
println(x.a)
}

View File

@ -0,0 +1,14 @@
struct Aa {
a int
}
fn f() &Aa {
return &Aa{
a: 5
}
}
fn test_ref_return() {
x := f()
assert x.a == 5
}