Skip to content

Commit

Permalink
Don't drop blocks on foreign functions
Browse files Browse the repository at this point in the history
A code like

```rust
extern "C" {
    fn f() {
        fn g() {}
    }
}
```

is incorrect and does not compile. Today rustfmt formats this in a way
that is correct:

```rust
extern "C" {
    fn f();
}
```

But this loses information, and doesn't have to be done because we know
the content of the block if it is present. During development I don't
think rustfmt should drop the block in this context.

Closes rust-lang#4313
  • Loading branch information
ayazhafiz authored and dtolnay committed Nov 29, 2020
1 parent 9a1a8c4 commit fa969fc
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
18 changes: 17 additions & 1 deletion src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3043,7 +3043,23 @@ impl Rewrite for ast::ForeignItem {
let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));

let item_str = match self.kind {
ast::ForeignItemKind::Fn(_, ref fn_sig, ref generics, _) => rewrite_fn_base(
ast::ForeignItemKind::Fn(defaultness, ref fn_sig, ref generics, Some(ref body)) => {
let mut visitor = FmtVisitor::from_context(context);
visitor.block_indent = shape.indent;
visitor.last_pos = self.span.lo();
let inner_attrs = inner_attributes(&self.attrs);
let fn_ctxt = visit::FnCtxt::Foreign;
visitor.visit_fn(
visit::FnKind::Fn(fn_ctxt, self.ident, &fn_sig, &self.vis, Some(body)),
generics,
&fn_sig.decl,
self.span,
defaultness,
Some(&inner_attrs),
);
Some(visitor.buffer.to_owned())
}
ast::ForeignItemKind::Fn(_, ref fn_sig, ref generics, None) => rewrite_fn_base(
context,
shape.indent,
self.ident,
Expand Down
2 changes: 1 addition & 1 deletion src/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {

// Note that this only gets called for function definitions. Required methods
// on traits do not get handled here.
fn visit_fn(
pub(crate) fn visit_fn(
&mut self,
fk: visit::FnKind<'_>,
generics: &ast::Generics,
Expand Down
5 changes: 5 additions & 0 deletions tests/target/issue-4313.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
extern "C" {
fn f() {
fn g() {}
}
}

0 comments on commit fa969fc

Please sign in to comment.