fix(prettier): remove extra empty lines inside the function body (#1365)

I'm not sure that's the right approach. But we can handle it this way for now
This commit is contained in:
Dunqing 2023-11-17 14:03:26 +08:00 committed by GitHub
parent 210dbd3ff2
commit 1116afa7bc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 24 additions and 8 deletions

View file

@ -17,7 +17,7 @@ pub(super) fn print_block<'a>(
parts.push(ss!("static "));
}
parts.push(ss!("{"));
if let Some(doc) = print_block_body(p, stmts, directives) {
if let Some(doc) = print_block_body(p, stmts, directives, true) {
parts.push(indent![p, hardline!(), doc]);
parts.push(hardline!());
}
@ -29,6 +29,7 @@ pub(super) fn print_block_body<'a>(
p: &mut Prettier<'a>,
stmts: &Vec<'a, Statement<'a>>,
directives: Option<&Vec<'a, Directive>>,
remove_last_statement_hardline: bool,
) -> Option<Doc<'a>> {
let has_directives = directives.is_some_and(|directives| !directives.is_empty());
let has_body = stmts.iter().any(|stmt| !matches!(stmt, Statement::EmptyStatement(_)));
@ -41,12 +42,12 @@ pub(super) fn print_block_body<'a>(
if has_directives {
if let Some(directives) = directives {
parts.extend(statement::print_statement_sequence(p, directives));
parts.extend(statement::print_statement_sequence(p, directives, false));
}
}
if !stmts.is_empty() {
parts.extend(statement::print_statement_sequence(p, stmts));
parts.extend(statement::print_statement_sequence(p, stmts, remove_last_statement_hardline));
}
Some(Doc::Array(parts))

View file

@ -35,6 +35,8 @@ pub(super) fn print_function<'a>(p: &mut Prettier<'a>, func: &Function<'a>) -> D
parts.push(p.str(";"));
}
parts.push(hardline!());
Doc::Array(parts)
}

View file

@ -52,7 +52,7 @@ where
impl<'a> Format<'a> for Program<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
block::print_block_body(p, &self.body, Some(&self.directives)).unwrap_or(ss!(""))
block::print_block_body(p, &self.body, Some(&self.directives), false).unwrap_or(ss!(""))
}
}

View file

@ -7,10 +7,24 @@ use super::Format;
pub(super) fn print_statement_sequence<'a, F: Format<'a>>(
p: &mut Prettier<'a>,
stmts: &Vec<'a, F>,
remove_last_statement_hardline: bool,
) -> Vec<'a, Doc<'a>> {
let mut parts = p.vec();
for stmt in stmts {
parts.push(stmt.format(p));
for (index, stmt) in stmts.iter().enumerate() {
let mut docs = stmt.format(p);
if remove_last_statement_hardline && index == stmts.len() - 1 {
match docs {
Doc::Array(ref mut docs) | Doc::Group(ref mut docs) => {
if matches!(docs.last(), Some(Doc::Hardline)) {
docs.pop();
}
}
_ => {}
}
}
parts.push(docs);
}
parts
}

View file

@ -1,4 +1,4 @@
Compatibility: 10/173 (5.78%)
Compatibility: 11/173 (6.36%)
# Failed
@ -110,7 +110,6 @@ Compatibility: 10/173 (5.78%)
* newline
* no-semi
* no-semi-babylon-extensions
* non-strict
* nullish-coalescing
* numeric-separators
* object-prop-break-in