fmt: respect user choice of newlines between functions without body (#8838)

pull/8859/head
Lukas Neubert 2021-02-20 15:00:30 +01:00 committed by GitHub
parent 783cee98d9
commit 329e3938d9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 7 deletions

View File

@ -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 {

View File

@ -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 {
}