From dff39bac78167881ca3384dd8637727fd9e215ba Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 23 Mar 2022 14:09:15 +0800 Subject: [PATCH] cgen: fix error for defining global anonymous functions (#13808) --- vlib/v/gen/c/cgen.v | 7 +++++++ vlib/v/gen/c/fn.v | 19 +++++++++++++++++++ vlib/v/tests/init_global_test.v | 12 ++++++++++++ 3 files changed, 38 insertions(+) diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 73b112bd2f..a0c13cdf91 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -4360,6 +4360,13 @@ fn (mut g Gen) global_decl(node ast.GlobalDecl) { } } styp := g.typ(field.typ) + mut anon_fn_expr := unsafe { field.expr } + if field.has_expr && mut anon_fn_expr is ast.AnonFn { + g.gen_anon_fn_decl(mut anon_fn_expr) + fn_type_name := g.get_anon_fn_type_name(mut anon_fn_expr, field.name) + g.definitions.writeln('$fn_type_name = ${g.table.sym(field.typ).name}; // global') + continue + } g.definitions.write_string('$visibility_kw$styp $attributes $field.name') if field.has_expr { if field.expr.is_literal() && should_init { diff --git a/vlib/v/gen/c/fn.v b/vlib/v/gen/c/fn.v index 445da57c66..15ddbc5b97 100644 --- a/vlib/v/gen/c/fn.v +++ b/vlib/v/gen/c/fn.v @@ -612,6 +612,25 @@ fn (mut g Gen) fn_decl_params(params []ast.Param, scope &ast.Scope, is_variadic return fargs, fargtypes, heap_promoted } +fn (mut g Gen) get_anon_fn_type_name(mut node ast.AnonFn, var_name string) string { + mut builder := strings.new_builder(64) + return_styp := g.typ(node.decl.return_type) + builder.write_string('$return_styp (*$var_name) (') + if node.decl.params.len == 0 { + builder.write_string('void)') + } else { + for i, param in node.decl.params { + param_styp := g.typ(param.typ) + builder.write_string('$param_styp $param.name') + if i != node.decl.params.len - 1 { + builder.write_string(', ') + } + } + builder.write_string(')') + } + return builder.str() +} + fn (mut g Gen) call_expr(node ast.CallExpr) { // g.write('/*call expr*/') // NOTE: everything could be done this way diff --git a/vlib/v/tests/init_global_test.v b/vlib/v/tests/init_global_test.v index b39d4d468b..4dae83c8f1 100644 --- a/vlib/v/tests/init_global_test.v +++ b/vlib/v/tests/init_global_test.v @@ -53,6 +53,11 @@ fn test_no_type() { assert testmap['asd'] == -7.25 } +fn test_fn_type() { + assert func2(22) == 22 + assert func3(22) == '22' +} + __global ( intmap map[string]int numberfns map[string]fn () int @@ -75,6 +80,13 @@ __global ( 'asd': -7.25 'yxc': 3.125 } + func1 = fn () {} + func2 = fn (n int) int { + return n + } + func3 = fn (n int) string { + return '$n' + } ) fn init() {