Skip to content

Commit

Permalink
refactor ABI formatting (rust-lang#5845)
Browse files Browse the repository at this point in the history
fixes 5701

Whenever we see an `extern "Rust"` on a function, we don't strip it from the function.

If there's any future desire to have rustfmt remove an explicit "Rust" ABI, as it historically did prior to this change, then we can consider updating the rustfmt config surface to support that scenario
  • Loading branch information
fee1-dead authored Aug 14, 2023
1 parent b069aac commit 4b01e62
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 20 deletions.
2 changes: 0 additions & 2 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,6 @@ impl<'a> Item<'a> {
abi: format_extern(
ast::Extern::from_abi(fm.abi, DUMMY_SP),
config.force_explicit_abi(),
true,
),
vis: None,
body: fm
Expand Down Expand Up @@ -336,7 +335,6 @@ impl<'a> FnSig<'a> {
result.push_str(&format_extern(
self.ext,
context.config.force_explicit_abi(),
false,
));
result
}
Expand Down
1 change: 0 additions & 1 deletion src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -892,7 +892,6 @@ fn rewrite_bare_fn(
result.push_str(&format_extern(
bare_fn.ext,
context.config.force_explicit_abi(),
false,
));

result.push_str("fn");
Expand Down
29 changes: 12 additions & 17 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,23 +131,18 @@ pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
}

#[inline]
pub(crate) fn format_extern(
ext: ast::Extern,
explicit_abi: bool,
is_mod: bool,
) -> Cow<'static, str> {
let abi = match ext {
ast::Extern::None => "Rust".to_owned(),
ast::Extern::Implicit(_) => "C".to_owned(),
ast::Extern::Explicit(abi, _) => abi.symbol_unescaped.to_string(),
};

if abi == "Rust" && !is_mod {
Cow::from("")
} else if abi == "C" && !explicit_abi {
Cow::from("extern ")
} else {
Cow::from(format!(r#"extern "{abi}" "#))
pub(crate) fn format_extern(ext: ast::Extern, explicit_abi: bool) -> Cow<'static, str> {
match ext {
ast::Extern::None => Cow::from(""),
ast::Extern::Implicit(_) if explicit_abi => Cow::from("extern \"C\" "),
ast::Extern::Implicit(_) => Cow::from("extern "),
// turn `extern "C"` into `extern` when `explicit_abi` is set to false
ast::Extern::Explicit(abi, _) if abi.symbol_unescaped == sym::C && !explicit_abi => {
Cow::from("extern ")
}
ast::Extern::Explicit(abi, _) => {
Cow::from(format!(r#"extern "{}" "#, abi.symbol_unescaped))
}
}
}

Expand Down
1 change: 1 addition & 0 deletions tests/target/extern-rust.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
extern "Rust" fn uwu() {}

0 comments on commit 4b01e62

Please sign in to comment.