From 8735694d1357300b523492c920dce61361a3efb6 Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Sun, 30 Jul 2023 08:41:11 +0530 Subject: [PATCH] parser: disallow declaring static functions as method receivers (#19007) --- vlib/v/parser/fn.v | 6 +++++- .../declare_static_fn_as_receiver_method_err.out | 7 +++++++ .../tests/declare_static_fn_as_receiver_method_err.vv | 11 +++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 vlib/v/parser/tests/declare_static_fn_as_receiver_method_err.out create mode 100644 vlib/v/parser/tests/declare_static_fn_as_receiver_method_err.vv diff --git a/vlib/v/parser/fn.v b/vlib/v/parser/fn.v index dd21e898e..128900797 100644 --- a/vlib/v/parser/fn.v +++ b/vlib/v/parser/fn.v @@ -292,7 +292,7 @@ fn (mut p Parser) fn_decl() ast.FnDecl { } mut name := '' mut type_sym := p.table.sym(rec.typ) - name_pos := p.tok.pos() + mut name_pos := p.tok.pos() if p.tok.kind == .name { mut check_name := '' // TODO high order fn @@ -304,6 +304,7 @@ fn (mut p Parser) fn_decl() ast.FnDecl { p.check(.dot) check_name = p.check_name() name = type_name + '__static__' + check_name // "foo__bar" + name_pos = name_pos.extend(p.prev_tok.pos()) } else { check_name = if language == .js { p.check_js_name() } else { p.check_name() } name = check_name @@ -452,6 +453,9 @@ run them via `v file.v` instead', } } } + if is_method && is_static_type_method { + p.error_with_pos('cannot declare a static function as a receiver method', name_pos) + } // Register if is_method { // Do not allow to modify / add methods to types from other modules diff --git a/vlib/v/parser/tests/declare_static_fn_as_receiver_method_err.out b/vlib/v/parser/tests/declare_static_fn_as_receiver_method_err.out new file mode 100644 index 000000000..a2b4086ea --- /dev/null +++ b/vlib/v/parser/tests/declare_static_fn_as_receiver_method_err.out @@ -0,0 +1,7 @@ +vlib/v/parser/tests/declare_static_fn_as_receiver_method_err.vv:4:12: error: cannot declare a static function as a receiver method + 2 | } + 3 | + 4 | fn (y Foo) Foo.new() Foo { + | ~~~~~~~ + 5 | return Foo{} + 6 | } diff --git a/vlib/v/parser/tests/declare_static_fn_as_receiver_method_err.vv b/vlib/v/parser/tests/declare_static_fn_as_receiver_method_err.vv new file mode 100644 index 000000000..b85cf2e2f --- /dev/null +++ b/vlib/v/parser/tests/declare_static_fn_as_receiver_method_err.vv @@ -0,0 +1,11 @@ +struct Foo { +} + +fn (y Foo) Foo.new() Foo { + return Foo{} +} + +fn main() { + x := Foo{}.new() + println(x) +} -- 2.39.5