From 2f2efb73397af9d7cd757c09bac2de8c1e591699 Mon Sep 17 00:00:00 2001 From: kbkpbot Date: Tue, 18 Nov 2025 00:18:15 +0800 Subject: [PATCH] parser: allow using `a`, `b` and `it` as var names, when using the builtin array methods (fix #25729) (#25755) --- vlib/v/parser/assign.v | 5 ++++ vlib/v/tests/skip_sort_arg_check_test.v | 38 +++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 vlib/v/tests/skip_sort_arg_check_test.v diff --git a/vlib/v/parser/assign.v b/vlib/v/parser/assign.v index 64a954775..06fc68be8 100644 --- a/vlib/v/parser/assign.v +++ b/vlib/v/parser/assign.v @@ -49,6 +49,11 @@ fn (mut p Parser) check_undefined_variables(names []string, val ast.Expr) ! { } ast.CallExpr { p.check_undefined_variables(names, val.left)! + // arr.sort(a < b) , arr.sorted(a < b), it := [2,3,4].map(it*2), it := [2,3,4].filter(it % 2 == 0), etc. + if val.args.len == 1 + && val.name in ['sort', 'sorted', 'map', 'filter', 'any', 'all', 'count'] { + return + } for arg in val.args { p.check_undefined_variables(names, arg.expr)! } diff --git a/vlib/v/tests/skip_sort_arg_check_test.v b/vlib/v/tests/skip_sort_arg_check_test.v new file mode 100644 index 000000000..b7719028d --- /dev/null +++ b/vlib/v/tests/skip_sort_arg_check_test.v @@ -0,0 +1,38 @@ +// should allow `a:=arr.sorted(a < b)` use `a` as var name +fn test_skip_check_sort_arg_a_b() { + arr := [4, 2, 1, 3] + a := arr.sorted(a < b) + assert a == [1, 2, 3, 4] + b := arr.sorted(a > b) + assert b == [4, 3, 2, 1] +} + +// should allow `it:=arr.map(it*2)` use `it` as var name +fn test_skip_check_map_arg_it() { + it := [4, 2, 1, 3].map(it * 2) + assert it == [8, 4, 2, 6] +} + +// should allow `it:=arr.filter(it%2==0)` use `it` as var name +fn test_skip_check_filter_arg_it() { + it := [4, 2, 1, 3].filter(it % 2 == 0) + assert it == [4, 2] +} + +// should allow `it:=arr.any(it%2==0)` use `it` as var name +fn test_skip_check_any_arg_it() { + it := [4, 2, 1, 3].any(it % 2 == 0) + assert it +} + +// should allow `it:=arr.all(it%2==0)` use `it` as var name +fn test_skip_check_all_arg_it() { + it := [4, 2, 1, 3].all(it % 2 == 0) + assert !it +} + +// should allow `it:=arr.count(it%2==0)` use `it` as var name +fn test_skip_check_count_arg_it() { + it := [4, 2, 1, 3].count(it % 2 == 0) + assert it == 2 +} -- 2.39.5