1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: fix array.filter(anon_fn)

This commit is contained in:
yuyi 2020-06-10 19:18:59 +08:00 committed by GitHub
parent 12faf9fcfa
commit acf0b84523
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 1 deletions

View File

@ -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
}

View File

@ -3245,10 +3245,28 @@ 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)