From 3e3b2e25dbc5932a0f524e7c3db319fd6ff5a957 Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 12 Apr 2022 03:31:06 +0800 Subject: [PATCH] parser, fmt: fix the formatting of fn headers with inline comments (#14010) --- vlib/v/fmt/fmt.v | 5 ++++- .../fmt/tests/fn_headers_with_inline_comments_expected.vv | 7 +++++++ vlib/v/fmt/tests/fn_headers_with_inline_comments_input.vv | 6 ++++++ vlib/v/parser/fn.v | 3 +++ 4 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 vlib/v/fmt/tests/fn_headers_with_inline_comments_expected.vv create mode 100644 vlib/v/fmt/tests/fn_headers_with_inline_comments_input.vv diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index c5ebfdbd98..3d6ef34dc8 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -953,8 +953,11 @@ fn (mut f Fmt) fn_body(node ast.FnDecl) { if node.language == .v { if !node.no_body { f.write(' {') + f.comments(node.comments, inline: true) if node.stmts.len > 0 || node.pos.line_nr < node.pos.last_line { - f.writeln('') + if node.comments.len == 0 { + f.writeln('') + } f.stmts(node.stmts) } f.write('}') diff --git a/vlib/v/fmt/tests/fn_headers_with_inline_comments_expected.vv b/vlib/v/fmt/tests/fn_headers_with_inline_comments_expected.vv new file mode 100644 index 0000000000..0ca5f74205 --- /dev/null +++ b/vlib/v/fmt/tests/fn_headers_with_inline_comments_expected.vv @@ -0,0 +1,7 @@ +fn main() { // main + return +} + +fn print_hi() { // hi + println('hi') +} diff --git a/vlib/v/fmt/tests/fn_headers_with_inline_comments_input.vv b/vlib/v/fmt/tests/fn_headers_with_inline_comments_input.vv new file mode 100644 index 0000000000..2f290ea7f8 --- /dev/null +++ b/vlib/v/fmt/tests/fn_headers_with_inline_comments_input.vv @@ -0,0 +1,6 @@ +fn /*main*/main() { + return +} + +fn // hi +print_hi(){println('hi')} diff --git a/vlib/v/parser/fn.v b/vlib/v/parser/fn.v index 3072cfb921..e956f2e116 100644 --- a/vlib/v/parser/fn.v +++ b/vlib/v/parser/fn.v @@ -182,6 +182,7 @@ fn (mut p Parser) fn_decl() ast.FnDecl { mut is_ctor_new := false mut is_c2v_variadic := false mut is_markused := false + mut comments := []ast.Comment{} for fna in p.attrs { match fna.name { 'noreturn' { is_noreturn = true } @@ -205,6 +206,7 @@ fn (mut p Parser) fn_decl() ast.FnDecl { p.next() } p.check(.key_fn) + comments << p.eat_comments() p.open_scope() // C. || JS. mut language := ast.Language.v @@ -530,6 +532,7 @@ fn (mut p Parser) fn_decl() ast.FnDecl { scope: p.scope label_names: p.label_names end_comments: p.eat_comments(same_line: true) + comments: comments } if generic_names.len > 0 { p.table.register_fn_generic_types(fn_decl.fkey())