From 35f2a0fb6674c00c2a66fd6e7ae98b828497db30 Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 17 May 2023 08:05:59 +0800 Subject: [PATCH] fmt: fix formating of fn decl with end comments (#18181) --- vlib/v/fmt/fmt.v | 21 ++++++++++++++++++- vlib/v/fmt/tests/fn_with_end_comments_keep.vv | 9 ++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 vlib/v/fmt/tests/fn_with_end_comments_keep.vv diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index 9234baf20..81b345789 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -1001,7 +1001,7 @@ pub fn (mut f Fmt) fn_decl(node ast.FnDecl) { f.attrs(node.attrs) f.write(node.stringify(f.table, f.cur_mod, f.mod2alias)) // `Expr` instead of `ast.Expr` in mod ast // Handle trailing comments after fn header declarations - if node.end_comments.len > 0 { + if node.no_body && node.end_comments.len > 0 { first_comment := node.end_comments[0] if first_comment.text.contains('\n') { f.writeln('\n') @@ -1045,6 +1045,25 @@ fn (mut f Fmt) fn_body(node ast.FnDecl) { f.stmts(node.stmts) } f.write('}') + if node.end_comments.len > 0 { + first_comment := node.end_comments[0] + if first_comment.text.contains('\n') { + f.writeln('\n') + } else { + f.write(' ') + } + f.comment(first_comment) + if node.end_comments.len > 1 { + f.writeln('\n') + comments := node.end_comments[1..] + for i, comment in comments { + f.comment(comment) + if i != comments.len - 1 { + f.writeln('\n') + } + } + } + } } if !node.is_anon { f.writeln('') diff --git a/vlib/v/fmt/tests/fn_with_end_comments_keep.vv b/vlib/v/fmt/tests/fn_with_end_comments_keep.vv new file mode 100644 index 000000000..da8ca512c --- /dev/null +++ b/vlib/v/fmt/tests/fn_with_end_comments_keep.vv @@ -0,0 +1,9 @@ +fn (c Color) is_blue() bool { + return c == .blue +} // method of enum + +fn (c Color) show_int() int { + return int(c) +} // method of enum + +fn main() {} -- 2.39.5