|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::source::snippet_with_applicability; |
| 3 | +use rustc_errors::Applicability; |
| 4 | +use rustc_hir::{Item, ItemKind}; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 7 | +use rustc_target::spec::abi::Abi; |
| 8 | + |
| 9 | +declare_clippy_lint! { |
| 10 | + /// ### What it does |
| 11 | + /// Checks for Rust ABI functions with the `#[no_mangle]` attribute. |
| 12 | + /// |
| 13 | + /// ### Why is this bad? |
| 14 | + /// The Rust ABI is not stable, but in many simple cases matches |
| 15 | + /// enough with the C ABI that it is possible to forget to add |
| 16 | + /// `extern "C"` to a function called from C. Changes to the |
| 17 | + /// Rust ABI can break this at any point. |
| 18 | + /// |
| 19 | + /// ### Example |
| 20 | + /// ```rust |
| 21 | + /// #[no_mangle] |
| 22 | + /// fn example(arg_one: u32, arg_two: usize) {} |
| 23 | + /// ``` |
| 24 | + /// |
| 25 | + /// Use instead: |
| 26 | + /// ```rust |
| 27 | + /// #[no_mangle] |
| 28 | + /// extern "C" fn example(arg_one: u32, arg_two: usize) {} |
| 29 | + /// ``` |
| 30 | + #[clippy::version = "1.69.0"] |
| 31 | + pub NO_MANGLE_WITH_RUST_ABI, |
| 32 | + pedantic, |
| 33 | + "convert Rust ABI functions to C ABI" |
| 34 | +} |
| 35 | +declare_lint_pass!(NoMangleWithRustAbi => [NO_MANGLE_WITH_RUST_ABI]); |
| 36 | + |
| 37 | +impl<'tcx> LateLintPass<'tcx> for NoMangleWithRustAbi { |
| 38 | + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { |
| 39 | + if let ItemKind::Fn(fn_sig, _, _) = &item.kind { |
| 40 | + let attrs = cx.tcx.hir().attrs(item.hir_id()); |
| 41 | + let mut applicability = Applicability::MachineApplicable; |
| 42 | + let snippet = snippet_with_applicability(cx, fn_sig.span, "..", &mut applicability); |
| 43 | + for attr in attrs { |
| 44 | + if let Some(ident) = attr.ident() |
| 45 | + && ident.name == rustc_span::sym::no_mangle |
| 46 | + && fn_sig.header.abi == Abi::Rust |
| 47 | + && !snippet.contains("extern") { |
| 48 | + |
| 49 | + let suggestion = snippet.split_once("fn") |
| 50 | + .map_or(String::new(), |(first, second)| format!(r#"{first}extern "C" fn{second}"#)); |
| 51 | + |
| 52 | + span_lint_and_sugg( |
| 53 | + cx, |
| 54 | + NO_MANGLE_WITH_RUST_ABI, |
| 55 | + fn_sig.span, |
| 56 | + "attribute #[no_mangle] set on a Rust ABI function", |
| 57 | + "try", |
| 58 | + suggestion, |
| 59 | + applicability |
| 60 | + ); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments