rustfmt
rustfmt copied to clipboard
fix: respect trailing semicolon setting for last statements
Problem
https://github.com/rust-lang/rustfmt/issues/5797 fixed the trailing_semicolon rule, allowing it only for the last expression in the block. The side-effect of this change is that such snippet
fn main() {
println!("{}", greet());
}
fn greet() -> String {
return "Hello, b!".to_string();
}
will not get formatted into
fn main() {
println!("{}", greet());
}
fn greet() -> String {
return "Hello, b!".to_string()
}
(notice the ; in the greet function), even though return is the last expression here. It's happening because the implementation of is_last_expr() additionally checks for the type of expression for some reason unknown to me https://github.com/rust-lang/rustfmt/blob/46e5f14ae2300967d57ab8d032f446c07e0ed415/src/stmt.rs#L74-L88
Solution
This PR fixes that by checking only the is_last field of the Stmt struct when deciding whether to emit the semicolon.
fn main() {
println!("{}", greet());
}
fn greet() -> String {
return "Hello, b!".to_string();
}
fn foo() {}
fn main() {
return;
foo()
}
➜ rustfmt git:(trailing-semicolon-last-stmt) cargo run --bin rustfmt -- --check -- ~/Projects/semicolon/src/main.rs
Compiling rustfmt-nightly v1.7.0 (/Users/shekhirin/Projects/rustfmt)
Finished dev [unoptimized + debuginfo] target(s) in 0.61s
Running `target/debug/rustfmt --check -- /Users/shekhirin/Projects/semicolon/src/main.rs`
Diff in /Users/shekhirin/Projects/semicolon/src/main.rs:3:
}
fn greet() -> String {
- return "Hello, b!".to_string();
+ return "Hello, b!".to_string()
}
fn foo() {}
As you can see, the example from the original PR is still not getting formatted, while the trailing comma for the last return statement gets removed.
Will probably be a little while before I'm able to review this, but I wanted to note that there's a semi related PR (https://github.com/rust-lang/rustfmt/pull/6149) that adds a new option to trailing_semicolon. It feels like this would be complimentary to that work, but I'm not 100% sure.