From 329e3938d9efddbcb6c5e3560a4ff0ae2ed7e631 Mon Sep 17 00:00:00 2001 From: Lukas Neubert Date: Sat, 20 Feb 2021 15:00:30 +0100 Subject: [PATCH] fmt: respect user choice of newlines between functions without body (#8838) --- vlib/v/fmt/fmt.v | 23 +++++++++++++++++------ vlib/v/fmt/tests/newlines_keep.vv | 7 ++++++- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index 9067876bb9..a368c789bc 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -304,18 +304,29 @@ pub fn (f Fmt) imp_stmt_str(imp ast.Import) string { fn (mut f Fmt) should_insert_newline_before_stmt(stmt ast.Stmt, prev_stmt ast.Stmt) bool { prev_line_nr := prev_stmt.position().last_line + // No need to insert a newline if there is already one + if f.out.last_n(2) == '\n\n' { + return false + } + // Force a newline after a block of HashStmts if prev_stmt is ast.HashStmt && stmt !is ast.HashStmt && stmt !is ast.ExprStmt { return true } - // The stmt either has or shouldn't have a newline before - if stmt.position().line_nr - prev_line_nr <= 1 || f.out.last_n(2) == '\n\n' { + // Force a newline after a block of function declarations + if prev_stmt is ast.FnDecl { + if prev_stmt.no_body && stmt !is ast.FnDecl { + return true + } + } + // The stmt shouldn't have a newline before + if stmt.position().line_nr - prev_line_nr <= 1 { return false } // Imports are handled special hence they are ignored here if stmt is ast.Import || prev_stmt is ast.Import { return false } - // Attributes are not respected in the stmts position, so we have to check it manually + // Attributes are not respected in the stmts position, so this requires a manual check if stmt is ast.StructDecl { if stmt.attrs.len > 0 && stmt.attrs[0].pos.line_nr - prev_line_nr <= 1 { return false @@ -640,7 +651,7 @@ pub fn (mut f Fmt) struct_decl(node ast.StructDecl) { f.write('>') } if node.fields.len == 0 && node.embeds.len == 0 && node.pos.line_nr == node.pos.last_line { - f.writeln(' {}\n') + f.writeln(' {}') return } f.writeln(' {') @@ -1120,10 +1131,10 @@ pub fn (mut f Fmt) fn_decl(node ast.FnDecl) { f.write('}') } if !node.is_anon { - f.writeln('\n') + f.writeln('') } } else { - f.writeln('\n') + f.writeln('') } // Mark all function's used type so that they are not removed from imports for arg in node.params { diff --git a/vlib/v/fmt/tests/newlines_keep.vv b/vlib/v/fmt/tests/newlines_keep.vv index 74e5389866..01665c0d50 100644 --- a/vlib/v/fmt/tests/newlines_keep.vv +++ b/vlib/v/fmt/tests/newlines_keep.vv @@ -2,6 +2,11 @@ [manualfree] module websocket +fn C.no_body_function() +fn C.another_one(x int) + +fn C.separated_from_my_body_and_the_above() + fn main() {} // This should stay between both functions @@ -15,5 +20,5 @@ fn y_with_attr() { // doc comment above an attributed struct [typedef] -struct Foo { +struct FooWithAttr { }