Skip to content

Commit

Permalink
Rollup merge of #91437 - dtolnay:emptybrace, r=nagisa
Browse files Browse the repository at this point in the history
Pretty print empty blocks as {}

**Example:**

```rust
macro_rules! p {
    ($e:expr) => {
        println!("{}", stringify!($e));
    };
    ($i:item) => {
        println!("{}", stringify!($i));
    };
}

fn main() {
    p!(if true {});
    p!(struct S {});
}
```

**Before:**

```console
if true { }
struct S {
}
```

**After:**

```console
if true {}
struct S {}
```

This affects [`dbg!`](https://doc.rust-lang.org/std/macro.dbg.html), as well as ecosystem uses of stringify such as in [`anyhow::ensure!`](https://docs.rs/anyhow/1/anyhow/macro.ensure.html). Printing a `{ }` in today's heavily rustfmt'd world comes out looking jarring/sloppy.
  • Loading branch information
matthiaskrgr authored Dec 5, 2021
2 parents 214b2a1 + b516a8c commit a8f8f74
Show file tree
Hide file tree
Showing 63 changed files with 182 additions and 164 deletions.
68 changes: 44 additions & 24 deletions compiler/rustc_ast_pretty/src/pprust/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,14 +263,17 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
self.strsep(",", false, b, elts, op)
}

fn maybe_print_comment(&mut self, pos: BytePos) {
fn maybe_print_comment(&mut self, pos: BytePos) -> bool {
let mut has_comment = false;
while let Some(ref cmnt) = self.next_comment() {
if cmnt.pos < pos {
has_comment = true;
self.print_comment(cmnt);
} else {
break;
}
}
has_comment
}

fn print_comment(&mut self, cmnt: &Comment) {
Expand Down Expand Up @@ -570,7 +573,10 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
self.print_tts(tts, convert_dollar_crate);
self.end();
match delim {
DelimToken::Brace => self.bclose(span),
DelimToken::Brace => {
let empty = tts.is_empty();
self.bclose(span, empty);
}
_ => {
let token_str = self.token_kind_to_string(&token::CloseDelim(delim));
self.word(token_str)
Expand Down Expand Up @@ -642,17 +648,20 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
self.end(); // Close the head-box.
}

fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
self.maybe_print_comment(span.hi());
self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
fn bclose_maybe_open(&mut self, span: rustc_span::Span, empty: bool, close_box: bool) {
let has_comment = self.maybe_print_comment(span.hi());
if !empty || has_comment {
self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
}
self.word("}");
if close_box {
self.end(); // Close the outer-box.
}
}

fn bclose(&mut self, span: rustc_span::Span) {
self.bclose_maybe_open(span, true)
fn bclose(&mut self, span: rustc_span::Span, empty: bool) {
let close_box = true;
self.bclose_maybe_open(span, empty, close_box)
}

fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
Expand Down Expand Up @@ -1196,7 +1205,8 @@ impl<'a> State<'a> {
for item in items {
self.print_item(item);
}
self.bclose(item.span);
let empty = item.attrs.is_empty() && items.is_empty();
self.bclose(item.span, empty);
}
ModKind::Unloaded => {
self.s.word(";");
Expand All @@ -1216,7 +1226,8 @@ impl<'a> State<'a> {
}
self.bopen();
self.print_foreign_mod(nmod, &item.attrs);
self.bclose(item.span);
let empty = item.attrs.is_empty() && nmod.items.is_empty();
self.bclose(item.span, empty);
}
ast::ItemKind::GlobalAsm(ref asm) => {
self.head(visibility_qualified(&item.vis, "global_asm!"));
Expand Down Expand Up @@ -1291,7 +1302,8 @@ impl<'a> State<'a> {
for impl_item in items {
self.print_assoc_item(impl_item);
}
self.bclose(item.span);
let empty = item.attrs.is_empty() && items.is_empty();
self.bclose(item.span, empty);
}
ast::ItemKind::Trait(box ast::Trait {
is_auto,
Expand Down Expand Up @@ -1326,7 +1338,8 @@ impl<'a> State<'a> {
for trait_item in items {
self.print_assoc_item(trait_item);
}
self.bclose(item.span);
let empty = item.attrs.is_empty() && items.is_empty();
self.bclose(item.span, empty);
}
ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
self.head("");
Expand Down Expand Up @@ -1410,7 +1423,8 @@ impl<'a> State<'a> {
self.end();
self.maybe_print_trailing_comment(v.span, None);
}
self.bclose(span)
let empty = variants.is_empty();
self.bclose(span, empty)
}

crate fn print_visibility(&mut self, vis: &ast::Visibility) {
Expand Down Expand Up @@ -1441,20 +1455,24 @@ impl<'a> State<'a> {
crate fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) {
self.nbsp();
self.bopen();
self.hardbreak_if_not_bol();

for field in fields {
let empty = fields.is_empty();
if !empty {
self.hardbreak_if_not_bol();
self.maybe_print_comment(field.span.lo());
self.print_outer_attributes(&field.attrs);
self.print_visibility(&field.vis);
self.print_ident(field.ident.unwrap());
self.word_nbsp(":");
self.print_type(&field.ty);
self.s.word(",");

for field in fields {
self.hardbreak_if_not_bol();
self.maybe_print_comment(field.span.lo());
self.print_outer_attributes(&field.attrs);
self.print_visibility(&field.vis);
self.print_ident(field.ident.unwrap());
self.word_nbsp(":");
self.print_type(&field.ty);
self.s.word(",");
}
}

self.bclose(span)
self.bclose(span, empty);
}

crate fn print_struct(
Expand Down Expand Up @@ -1633,7 +1651,8 @@ impl<'a> State<'a> {
}
}

self.bclose_maybe_open(blk.span, close_box);
let empty = attrs.is_empty() && blk.stmts.is_empty();
self.bclose_maybe_open(blk.span, empty, close_box);
self.ann.post(self, AnnNode::Block(blk))
}

Expand Down Expand Up @@ -2010,7 +2029,8 @@ impl<'a> State<'a> {
for arm in arms {
self.print_arm(arm);
}
self.bclose(expr.span);
let empty = attrs.is_empty() && arms.is_empty();
self.bclose(expr.span, empty);
}
ast::ExprKind::Closure(
capture_clause,
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2174,7 +2174,7 @@ impl<'a> State<'a> {
match decl.output {
hir::FnRetTy::Return(ref ty) => {
self.print_type(&ty);
self.maybe_print_comment(ty.span.lo())
self.maybe_print_comment(ty.span.lo());
}
hir::FnRetTy::DefaultReturn(..) => unreachable!(),
}
Expand Down Expand Up @@ -2368,7 +2368,7 @@ impl<'a> State<'a> {
self.end();

if let hir::FnRetTy::Return(ref output) = decl.output {
self.maybe_print_comment(output.span.lo())
self.maybe_print_comment(output.span.lo());
}
}

Expand Down
8 changes: 4 additions & 4 deletions src/test/pretty/ast-stmt-expr-attr.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// pp-exact

fn main() { }
fn main() {}

#[cfg(FALSE)]
fn syntax() {
Expand Down Expand Up @@ -117,7 +117,7 @@ fn syntax() {
let _ = #[attr] foo!(#! [attr]);
let _ = #[attr] foo![];
let _ = #[attr] foo![#! [attr]];
let _ = #[attr] foo! { };
let _ = #[attr] foo! {};
let _ = #[attr] foo! { #! [attr] };
let _ = #[attr] Foo{bar: baz,};
let _ = #[attr] Foo{..foo};
Expand All @@ -135,7 +135,7 @@ fn syntax() {
foo!();

#[attr]
foo! { }
foo! {}

#[attr]
foo![];
Expand Down Expand Up @@ -170,6 +170,6 @@ fn syntax() {
{

#[attr]
foo! { }
foo! {}
}
}
2 changes: 1 addition & 1 deletion src/test/pretty/attr-derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ enum Enum {
Qwerty,
}

fn main() { }
fn main() {}
6 changes: 3 additions & 3 deletions src/test/pretty/auto-trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

// pp-exact

auto trait MyTrait { }
auto trait MyTrait {}

unsafe auto trait UnsafeMyTrait { }
unsafe auto trait UnsafeMyTrait {}

pub fn main() { }
pub fn main() {}
9 changes: 4 additions & 5 deletions src/test/pretty/block-comment-trailing-whitespace2.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
// compile-flags: --crate-type=lib

// pp-exact
fn f() {
} /*
The next line should not be indented.
fn f() {} /*
The next line should not be indented.
That one. It shouldn't have been indented.
*/
That one. It shouldn't have been indented.
*/
12 changes: 6 additions & 6 deletions src/test/pretty/closure-reform-pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@

// pp-exact

fn call_it(f: Box<FnMut(String) -> String>) { }
fn call_it(f: Box<FnMut(String) -> String>) {}

fn call_this<F>(f: F) where F: Fn(&str) + Send { }
fn call_this<F>(f: F) where F: Fn(&str) + Send {}

fn call_that<F>(f: F) where F: for<'a> Fn(&'a isize, &'a isize) -> isize { }
fn call_that<F>(f: F) where F: for<'a> Fn(&'a isize, &'a isize) -> isize {}

fn call_extern(f: fn() -> isize) { }
fn call_extern(f: fn() -> isize) {}

fn call_abid_extern(f: extern "C" fn() -> isize) { }
fn call_abid_extern(f: extern "C" fn() -> isize) {}

pub fn main() { }
pub fn main() {}
2 changes: 1 addition & 1 deletion src/test/pretty/disamb-stmt-expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
fn id<F>(f: F) -> isize where F: Fn() -> isize { f() }

fn wsucc(_n: isize) -> isize { id(|| { 1 }) - 0 }
fn main() { }
fn main() {}
2 changes: 1 addition & 1 deletion src/test/pretty/enum-variant-vis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

// Check that the visibility is printed on an enum variant.

fn main() { }
fn main() {}

#[cfg(FALSE)]
enum Foo { pub V, }
2 changes: 1 addition & 1 deletion src/test/pretty/example1.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// pp-exact

fn main() { }
fn main() {}
2 changes: 1 addition & 1 deletion src/test/pretty/example2.pp
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// pp-exact:example2.pp

fn main() { }
fn main() {}
2 changes: 1 addition & 1 deletion src/test/pretty/example2.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// pp-exact:example2.pp

fn main() { }
fn main() {}
2 changes: 1 addition & 1 deletion src/test/pretty/expanded-and-path-remap-80832.pp
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@
// pp-exact:expanded-and-path-remap-80832.pp
// compile-flags: --remap-path-prefix {{src-base}}=the/src

fn main() { }
fn main() {}
6 changes: 3 additions & 3 deletions src/test/pretty/fn-return.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// pp-exact

// Check that `fn f() -> () { }` does not print as `fn f() { }`.
// Check that `fn f() -> () {}` does not print as `fn f() {}`.

fn f() -> () { }
fn f() -> () {}

fn main() { }
fn main() {}
6 changes: 3 additions & 3 deletions src/test/pretty/fn-types.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// pp-exact

fn from_foreign_fn(_x: fn()) { }
fn from_stack_closure<F>(_x: F) where F: Fn() { }
fn main() { }
fn from_foreign_fn(_x: fn()) {}
fn from_stack_closure<F>(_x: F) where F: Fn() {}
fn main() {}
2 changes: 1 addition & 1 deletion src/test/pretty/fn-variadic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ pub unsafe extern "C" fn bar(_: i32, mut ap: ...) -> usize {
ap.arg::<usize>()
}

fn main() { }
fn main() {}
18 changes: 9 additions & 9 deletions src/test/pretty/if-attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,34 @@
fn simple_attr() {

#[attr]
if true { }
if true {}

#[allow_warnings]
if true { }
if true {}
}

#[cfg(FALSE)]
fn if_else_chain() {

#[first_attr]
if true { } else if false { } else { }
if true {} else if false {} else {}
}

#[cfg(FALSE)]
fn if_let() {

#[attr]
if let Some(_) = Some(true) { }
if let Some(_) = Some(true) {}
}

#[cfg(FALSE)]
fn let_attr_if() {
let _ = #[attr] if let _ = 0 { };
let _ = #[attr] if true { };
let _ = #[attr] if let _ = 0 {};
let _ = #[attr] if true {};

let _ = #[attr] if let _ = 0 { } else { };
let _ = #[attr] if true { } else { };
let _ = #[attr] if let _ = 0 {} else {};
let _ = #[attr] if true {} else {};
}


fn main() { }
fn main() {}
2 changes: 1 addition & 1 deletion src/test/pretty/issue-12590-a.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
#[path = "issue-12590-b.rs"]
mod issue_12590_b;

fn main() { }
fn main() {}
6 changes: 3 additions & 3 deletions src/test/pretty/issue-12590-c.pp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
#[path = "issue-12590-b.rs"]
mod issue_12590_b {

fn b() { }
fn main() { }
fn b() {}
fn main() {}
}
fn main() { }
fn main() {}
2 changes: 1 addition & 1 deletion src/test/pretty/issue-12590-c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
#[path = "issue-12590-b.rs"]
mod issue_12590_b;

fn main() { }
fn main() {}
Loading

0 comments on commit a8f8f74

Please sign in to comment.