From dd8e19414e4637aeebc72524c962b5ad28966e2b Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 4 Oct 2023 02:12:30 +0800 Subject: [PATCH] parser: fix assigning static method to anon fn (#19499) --- vlib/v/parser/parser.v | 22 +++++++++++++++++++ .../assign_static_method_to_anon_fn_test.v | 15 +++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 vlib/v/tests/assign_static_method_to_anon_fn_test.v diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index 154fe847912cfa..b8efbf087ea18b 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -2825,6 +2825,28 @@ fn (mut p Parser) name_expr() ast.Expr { p.tok.pos()) } } + // `anon_fn := Foo.bar` assign static method + if !known_var && lit0_is_capital && p.peek_tok.kind == .dot && language == .v + && p.peek_token(2).kind == .name { + if func := p.table.find_fn(p.prepend_mod(p.tok.lit) + '__static__' + p.peek_token(2).lit) { + fn_type := ast.new_type(p.table.find_or_register_fn_type(func, false, + true)) + pos := p.tok.pos() + typ_name := p.check_name() + p.check(.dot) + field_name := p.check_name() + pos.extend(p.tok.pos()) + return ast.Ident{ + name: p.prepend_mod(typ_name) + '__static__' + field_name + mod: p.mod + kind: .function + info: ast.IdentFn{ + typ: fn_type + } + scope: p.scope + } + } + } // `Color.green` mut enum_name := p.check_name() enum_name_pos := p.prev_tok.pos() diff --git a/vlib/v/tests/assign_static_method_to_anon_fn_test.v b/vlib/v/tests/assign_static_method_to_anon_fn_test.v new file mode 100644 index 00000000000000..1e0747b2c677f2 --- /dev/null +++ b/vlib/v/tests/assign_static_method_to_anon_fn_test.v @@ -0,0 +1,15 @@ +struct Foo { +} + +fn Foo.bar() string { + println('bar') + return 'bar' +} + +fn test_assign_static_method_to_anon_fn() { + // vfmt off + anon_fn := Foo.bar + // vfmt on + ret := anon_fn() + assert ret == 'bar' +}