Skip to content

Commit

Permalink
fix: else was moved to wrong if sometimes when formatting minifie…
Browse files Browse the repository at this point in the history
…d code (#633)
  • Loading branch information
dsherret authored May 5, 2024
1 parent ea1a301 commit 4406be7
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
36 changes: 33 additions & 3 deletions src/generation/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8294,7 +8294,7 @@ fn gen_control_flow_separator(
}

struct GenHeaderWithConditionalBraceBodyOptions<'a> {
body_node: Node<'a>,
body_node: Stmt<'a>,
generated_header: PrintItems,
use_braces: UseBraces,
brace_position: BracePosition,
Expand Down Expand Up @@ -8324,8 +8324,12 @@ fn gen_header_with_conditional_brace_body<'a>(
items.push_info(end_header_ln);
let result = gen_conditional_brace_body(
GenConditionalBraceBodyOptions {
body_node: opts.body_node,
use_braces: opts.use_braces,
body_node: opts.body_node.into(),
use_braces: if force_use_braces_for_stmt(opts.body_node) {
UseBraces::Always
} else {
opts.use_braces
},
brace_position: opts.brace_position,
single_body_position: opts.single_body_position,
requires_braces_condition_ref: opts.requires_braces_condition_ref,
Expand All @@ -8343,6 +8347,32 @@ fn gen_header_with_conditional_brace_body<'a>(
}
}

fn force_use_braces_for_stmt(stmt: Stmt) -> bool {
match stmt {
Stmt::Block(block) => {
if block.stmts.len() != 1 {
true
} else {
force_use_braces_for_stmt(block.stmts[0])
}
}
// force braces for any children where no braces could be ambiguous
Stmt::Empty(_)
| Stmt::DoWhile(_)
| Stmt::For(_)
| Stmt::ForIn(_)
| Stmt::ForOf(_)
| Stmt::Decl(_)
| Stmt::If(_) // especially force for this as it may cause a bug
| Stmt::Labeled(_)
| Stmt::Switch(_)
| Stmt::Try(_)
| Stmt::While(_)
| Stmt::With(_) => true,
Stmt::Break(_) | Stmt::Continue(_) | Stmt::Debugger(_) | Stmt::Expr(_) | Stmt::Return(_) | Stmt::Throw(_) => false,
}
}

struct GenConditionalBraceBodyOptions<'a> {
body_node: Node<'a>,
use_braces: UseBraces,
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
#![allow(clippy::if_same_then_else)]
#![allow(clippy::vec_init_then_push)]
#![allow(clippy::type_complexity)]
#![allow(clippy::needless_lifetimes)] // todo: enable this in the future
#![allow(clippy::needless_lifetimes)]
#![deny(clippy::disallowed_methods)]
#![deny(clippy::disallowed_types)]
#![deny(clippy::print_stderr)]
Expand Down
7 changes: 7 additions & 0 deletions tests/specs/issues/issue0632.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
== should maintain if stmt ==
if(a){if(b){console.log(0);}}else if(d){console.log(1);}else{console.log(2);}

[expect]
if (a) { if (b) console.log(0); }
else if (d) console.log(1);
else console.log(2);

0 comments on commit 4406be7

Please sign in to comment.