From d00237f02cd62b4f3722f2ddd7938f5da402e0dc Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Mon, 13 Mar 2023 06:56:13 -0300 Subject: [PATCH] cgen: fix code generated to option fn (fix #17604) (#17614) --- vlib/v/gen/c/fn.v | 2 +- vlib/v/tests/option_fn_test.v | 47 +++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/option_fn_test.v diff --git a/vlib/v/gen/c/fn.v b/vlib/v/gen/c/fn.v index 034205215c..5367fe0d1b 100644 --- a/vlib/v/gen/c/fn.v +++ b/vlib/v/gen/c/fn.v @@ -571,7 +571,7 @@ fn (mut g Gen) fn_decl_params(params []ast.Param, scope &ast.Scope, is_variadic } param_type_sym := g.table.sym(typ) mut param_type_name := g.typ(typ) // util.no_dots(param_type_sym.name) - if param_type_sym.kind == .function { + if param_type_sym.kind == .function && !typ.has_flag(.option) { info := param_type_sym.info as ast.FnType func := info.func g.write('${g.typ(func.return_type)} (*${caname})(') diff --git a/vlib/v/tests/option_fn_test.v b/vlib/v/tests/option_fn_test.v new file mode 100644 index 0000000000..473fa349e6 --- /dev/null +++ b/vlib/v/tests/option_fn_test.v @@ -0,0 +1,47 @@ +type HandlerFn = fn () + +fn new_static_router(route_not_found_handler ?fn ()) fn () { + return route_not_found_handler or { + fn () {} + } +} + +fn new_static_router2(route_not_found_handler ?HandlerFn) fn () { + return route_not_found_handler or { + fn () {} + } +} + +fn test_option_fn_alias_decl_with_none() { + b := new_static_router2(none) + $if b is $Function { + assert true + } $else { + assert false + } +} + +fn test_option_fn_decl_with_none() { + a := new_static_router(none) + $if a is $Function { + assert true + } $else { + assert false + } +} + +fn test_option_fn_passing_normal() { + anon_1 := fn () { + println(1) + } + c := new_static_router(anon_1) + assert c == anon_1 +} + +fn test_option_fn_passing_to_alias() { + anon_2 := fn () { + println(2) + } + d := new_static_router(anon_2) + assert d == anon_2 +}