From 0945efebf120117abea27de6c3d34fc0873ca42a Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 15 Jan 2021 17:25:30 +0800 Subject: [PATCH] cgen: fix anon_fn_call (#8120) --- vlib/v/gen/cgen.v | 10 +++++++--- vlib/v/tests/anon_fn_call_test.v | 10 ++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/anon_fn_call_test.v diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 69f25a7352..0d964e0168 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -93,6 +93,7 @@ mut: map_fn_definitions []string // map equality functions that have been defined struct_fn_definitions []string // struct equality functions that have been defined auto_fn_definitions []string // auto generated functions defination list + anon_fn_definitions []string // anon generated functions defination list is_json_fn bool // inside json.encode() json_types []string // to avoid json gen duplicates pcs []ProfileCounterMeta // -prof profile counter fn_names => fn counter name @@ -341,6 +342,11 @@ pub fn cgen(files []ast.File, table &table.Table, pref &pref.Preferences) string b.writeln(fn_def) } } + if g.anon_fn_definitions.len > 0 { + for fn_def in g.anon_fn_definitions { + b.writeln(fn_def) + } + } b.writeln('\n// V out') b.write(g.out.str()) b.writeln('\n// THE END.') @@ -2361,12 +2367,10 @@ fn (mut g Gen) autofree_var_call(free_fn_name string, v ast.Var) { fn (mut g Gen) gen_anon_fn_decl(it 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.anon_fn_definitions << fn_body } fn (mut g Gen) map_fn_ptrs(key_typ table.TypeSymbol) (string, string, string, string) { diff --git a/vlib/v/tests/anon_fn_call_test.v b/vlib/v/tests/anon_fn_call_test.v new file mode 100644 index 0000000000..4ba7cf41ec --- /dev/null +++ b/vlib/v/tests/anon_fn_call_test.v @@ -0,0 +1,10 @@ +fn test_anon_fn_call() { + anon_fn := fn() string { + return test() + } + assert anon_fn() == 'Test' +} + +fn test() string { + return "Test" +}