Skip to content

Commit 3e60ac2

Browse files
committed
Don't drop blocks on foreign functions
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
1 parent 37ec56d commit 3e60ac2

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

Diff for: src/formatting/items.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -3134,7 +3134,23 @@ impl Rewrite for ast::ForeignItem {
31343134
let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
31353135

31363136
let item_str = match self.kind {
3137-
ast::ForeignItemKind::Fn(_, ref fn_sig, ref generics, _) => rewrite_fn_base(
3137+
ast::ForeignItemKind::Fn(defaultness, ref fn_sig, ref generics, Some(ref body)) => {
3138+
let mut visitor = FmtVisitor::from_context(context);
3139+
visitor.block_indent = shape.indent;
3140+
visitor.last_pos = self.span.lo();
3141+
let inner_attrs = inner_attributes(&self.attrs);
3142+
let fn_ctxt = visit::FnCtxt::Foreign;
3143+
visitor.visit_fn(
3144+
visit::FnKind::Fn(fn_ctxt, self.ident, &fn_sig, &self.vis, Some(body)),
3145+
generics,
3146+
&fn_sig.decl,
3147+
self.span,
3148+
defaultness,
3149+
Some(&inner_attrs),
3150+
);
3151+
Some(visitor.buffer.to_owned())
3152+
}
3153+
ast::ForeignItemKind::Fn(_, ref fn_sig, ref generics, None) => rewrite_fn_base(
31383154
context,
31393155
shape.indent,
31403156
self.ident,

Diff for: src/formatting/visitor.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
361361

362362
// Note that this only gets called for function definitions. Required methods
363363
// on traits do not get handled here.
364-
fn visit_fn(
364+
pub(crate) fn visit_fn(
365365
&mut self,
366366
fk: visit::FnKind<'_>,
367367
generics: &ast::Generics,

Diff for: tests/target/issue-4313.rs

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
extern "C" {
2+
fn f() {
3+
fn g() {}
4+
}
5+
}

0 commit comments

Comments
 (0)