Skip to content

Commit 2f2efb7

Browse files
authored
parser: allow using a, b and it as var names, when using the builtin array methods (fix #25729) (#25755)
1 parent 3555998 commit 2f2efb7

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

vlib/v/parser/assign.v

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ fn (mut p Parser) check_undefined_variables(names []string, val ast.Expr) ! {
4949
}
5050
ast.CallExpr {
5151
p.check_undefined_variables(names, val.left)!
52+
// arr.sort(a < b) , arr.sorted(a < b), it := [2,3,4].map(it*2), it := [2,3,4].filter(it % 2 == 0), etc.
53+
if val.args.len == 1
54+
&& val.name in ['sort', 'sorted', 'map', 'filter', 'any', 'all', 'count'] {
55+
return
56+
}
5257
for arg in val.args {
5358
p.check_undefined_variables(names, arg.expr)!
5459
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// should allow `a:=arr.sorted(a < b)` use `a` as var name
2+
fn test_skip_check_sort_arg_a_b() {
3+
arr := [4, 2, 1, 3]
4+
a := arr.sorted(a < b)
5+
assert a == [1, 2, 3, 4]
6+
b := arr.sorted(a > b)
7+
assert b == [4, 3, 2, 1]
8+
}
9+
10+
// should allow `it:=arr.map(it*2)` use `it` as var name
11+
fn test_skip_check_map_arg_it() {
12+
it := [4, 2, 1, 3].map(it * 2)
13+
assert it == [8, 4, 2, 6]
14+
}
15+
16+
// should allow `it:=arr.filter(it%2==0)` use `it` as var name
17+
fn test_skip_check_filter_arg_it() {
18+
it := [4, 2, 1, 3].filter(it % 2 == 0)
19+
assert it == [4, 2]
20+
}
21+
22+
// should allow `it:=arr.any(it%2==0)` use `it` as var name
23+
fn test_skip_check_any_arg_it() {
24+
it := [4, 2, 1, 3].any(it % 2 == 0)
25+
assert it
26+
}
27+
28+
// should allow `it:=arr.all(it%2==0)` use `it` as var name
29+
fn test_skip_check_all_arg_it() {
30+
it := [4, 2, 1, 3].all(it % 2 == 0)
31+
assert !it
32+
}
33+
34+
// should allow `it:=arr.count(it%2==0)` use `it` as var name
35+
fn test_skip_check_count_arg_it() {
36+
it := [4, 2, 1, 3].count(it % 2 == 0)
37+
assert it == 2
38+
}

0 commit comments

Comments
 (0)