|
| 1 | +use clippy_utils::diagnostics::span_lint; |
| 2 | +use rustc_ast::visit::FnKind; |
| 3 | +use rustc_ast::{Extern, FnHeader, FnSig, ForeignMod, Item, ItemKind, NodeId}; |
| 4 | +use rustc_lint::{EarlyContext, EarlyLintPass}; |
| 5 | +use rustc_session::declare_lint_pass; |
| 6 | +use rustc_span::Span; |
| 7 | + |
| 8 | +const LINT_MSG: &str = "`extern` missing explicit ABI"; |
| 9 | + |
| 10 | +declare_clippy_lint! { |
| 11 | + /// ### What it does |
| 12 | + /// Checks for usage of `extern` without an explicit ABI. |
| 13 | + /// |
| 14 | + /// ### Why is this bad? |
| 15 | + /// Explicitly declaring the ABI improves readability. |
| 16 | + // |
| 17 | + /// ### Example |
| 18 | + /// ```no_run |
| 19 | + /// extern fn foo() {} |
| 20 | + /// |
| 21 | + /// extern { |
| 22 | + /// fn bar(); |
| 23 | + /// } |
| 24 | + /// ``` |
| 25 | + /// Use instead: |
| 26 | + /// ```no_run |
| 27 | + /// extern "C" fn foo() {} |
| 28 | + /// |
| 29 | + /// extern "C" { |
| 30 | + /// fn bar(); |
| 31 | + /// } |
| 32 | + /// ``` |
| 33 | + #[clippy::version = "1.83.0"] |
| 34 | + pub EXTERN_WITHOUT_ABI, |
| 35 | + style, |
| 36 | + "`extern` missing explicit ABI" |
| 37 | +} |
| 38 | + |
| 39 | +declare_lint_pass!(ExternWithoutAbi => [EXTERN_WITHOUT_ABI]); |
| 40 | + |
| 41 | +impl EarlyLintPass for ExternWithoutAbi { |
| 42 | + fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) { |
| 43 | + if let ItemKind::ForeignMod(ref foreign_mod) = item.kind |
| 44 | + && let ForeignMod { abi: None, .. } = foreign_mod |
| 45 | + { |
| 46 | + span_lint(cx, EXTERN_WITHOUT_ABI, item.span, LINT_MSG); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, _: Span, _: NodeId) { |
| 51 | + if let FnKind::Fn(_, _, sig, ..) = kind |
| 52 | + && let FnSig { header, .. } = sig |
| 53 | + && let FnHeader { |
| 54 | + ext: Extern::Implicit(span), |
| 55 | + .. |
| 56 | + } = header |
| 57 | + { |
| 58 | + span_lint(cx, EXTERN_WITHOUT_ABI, *span, LINT_MSG); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments