cgen: fix error for defining global anonymous functions (#13808)

pull/13810/head
yuyi 2022-03-23 14:09:15 +08:00 committed by GitHub
parent e3dca82f9c
commit dff39bac78
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 0 deletions

View File

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

View File

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

View File

@ -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() {