Skip to content

Commit fa969fc

Browse files
ayazhafizdtolnay
authored andcommitted
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 9a1a8c4 commit fa969fc

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

src/items.rs

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

30453045
let item_str = match self.kind {
3046-
ast::ForeignItemKind::Fn(_, ref fn_sig, ref generics, _) => rewrite_fn_base(
3046+
ast::ForeignItemKind::Fn(defaultness, ref fn_sig, ref generics, Some(ref body)) => {
3047+
let mut visitor = FmtVisitor::from_context(context);
3048+
visitor.block_indent = shape.indent;
3049+
visitor.last_pos = self.span.lo();
3050+
let inner_attrs = inner_attributes(&self.attrs);
3051+
let fn_ctxt = visit::FnCtxt::Foreign;
3052+
visitor.visit_fn(
3053+
visit::FnKind::Fn(fn_ctxt, self.ident, &fn_sig, &self.vis, Some(body)),
3054+
generics,
3055+
&fn_sig.decl,
3056+
self.span,
3057+
defaultness,
3058+
Some(&inner_attrs),
3059+
);
3060+
Some(visitor.buffer.to_owned())
3061+
}
3062+
ast::ForeignItemKind::Fn(_, ref fn_sig, ref generics, None) => rewrite_fn_base(
30473063
context,
30483064
shape.indent,
30493065
self.ident,

src/visitor.rs

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

371371
// Note that this only gets called for function definitions. Required methods
372372
// on traits do not get handled here.
373-
fn visit_fn(
373+
pub(crate) fn visit_fn(
374374
&mut self,
375375
fk: visit::FnKind<'_>,
376376
generics: &ast::Generics,

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)