Skip to content

Commit b3930c3

Browse files
committed
checker: add error for .map() calling a fn with multiple return values (prevent inaccessible tuple leak)
1 parent 6c1ae4f commit b3930c3

File tree

4 files changed

+22
-3
lines changed

4 files changed

+22
-3
lines changed

doc/docs.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1064,10 +1064,10 @@ the `it` built-in variable to achieve a classic `map/filter` functional paradigm
10641064
```v
10651065
// using filter, map and negatives array slices
10661066
a := ['pippo.jpg', '01.bmp', '_v.txt', 'img_02.jpg', 'img_01.JPG']
1067-
res := a.filter(it#[-4..].to_lower() == '.jpg').map(fn (w string) (string, int) {
1068-
return w.to_upper(), w.len
1067+
res := a.filter(it#[-4..].to_lower() == '.jpg').map(fn (w string) string {
1068+
return w.to_upper()
10691069
})
1070-
// [('PIPPO.JPG', 9), ('IMG_02.JPG', 10), ('IMG_01.JPG', 10)]
1070+
// ['PIPPO.JPG', 'IMG_02.JPG', 'IMG_01.JPG']
10711071
```
10721072

10731073
### Fixed size arrays

vlib/v/checker/fn.v

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1707,6 +1707,10 @@ fn (mut c Checker) array_builtin_method_call(mut node ast.CallExpr, left_type as
17071707
else { arg_type }
17081708
}
17091709
node.return_type = c.table.find_or_register_array(c.unwrap_generic(ret_type))
1710+
ret_sym := c.table.sym(ret_type)
1711+
if ret_sym.kind == .multi_return {
1712+
c.error('returning multiple values is not supported in .map() calls', node.pos)
1713+
}
17101714
} else if method_name == 'filter' {
17111715
// check fn
17121716
c.check_map_and_filter(false, elem_typ, node)
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
vlib/v/checker/tests/map_func_return_multiple_values_err.vv:6:17: error: returning multiple values is not supported in .map() calls
2+
4 |
3+
5 | fn main() {
4+
6 | a := [1, 2, 3].map(fun)
5+
| ~~~~~~~~
6+
7 | println(a)
7+
8 | }
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn fun(n int) (int, string) {
2+
return n, n.str()
3+
}
4+
5+
fn main() {
6+
a := [1, 2, 3].map(fun)
7+
println(a)
8+
}

0 commit comments

Comments
 (0)