From acf0b84523eda87899fd493b78e3fe668afedd84 Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 10 Jun 2020 19:18:59 +0800 Subject: [PATCH] cgen: fix array.filter(anon_fn) --- vlib/builtin/array_test.v | 15 +++++++++++++++ vlib/v/gen/cgen.v | 20 +++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index f412c58ba5..ce94ac592e 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -529,6 +529,21 @@ fn test_filter() { //assert arr.filter(arr % 2).len == 5 } +fn test_anon_fn_filter() { + filter_num := fn (i int) bool { + return i % 2 == 0 + } + assert [1,2,3,4,5].filter(filter_num) == [2,4] +} + +fn test_anon_fn_arg_filter() { + a := [1,2,3,4].filter(fn (i int) bool { + return i % 2 == 0 + }) + + assert a == [2,4] +} + fn map_test_helper_1(i int) int { return i * i } diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index f4296b4792..4b25c732e6 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -3245,11 +3245,29 @@ fn (mut g Gen) gen_filter(node ast.CallExpr) { match node.args[0].expr { ast.Ident { if it.kind == .function { - g.writeln('${node.args[0]}(it)') + g.write('${it.name}(it)') + } else if it.kind == .variable { + var_info := it.var_info() + sym_t := g.table.get_type_symbol(var_info.typ) + if sym_t.kind == .function { + g.write('${it.name}(it)') + } else { + g.expr(node.args[0].expr) + } } else { g.expr(node.args[0].expr) } } + ast.AnonFn { + pos := g.out.len + def_pos := g.definitions.len + g.stmt(it.decl) + fn_body := g.out.after(pos) + g.out.go_back(fn_body.len) + g.definitions.go_back(g.definitions.len - def_pos) + g.definitions.write(fn_body) + g.write('${it.decl.name}(it)') + } else { g.expr(node.args[0].expr) }