|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use rustc_errors::Applicability; |
| 3 | +use rustc_hir::*; |
| 4 | +use rustc_lint::{LateContext, LateLintPass}; |
| 5 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 6 | + |
| 7 | +declare_clippy_lint! { |
| 8 | + /// ### What it does |
| 9 | + /// Find traits that are not explicitely used in scope (like `AsRef::as_ref()`) |
| 10 | + /// but directly with the trait method (like `opt.as_ref()`). |
| 11 | + /// |
| 12 | + /// These traits can be imported anonymously with `use crate::Trait as _`. |
| 13 | + /// This avoids name collision with other traits (possibly with the same name). |
| 14 | + /// It also helps identify the traits in `use` statements. |
| 15 | + /// |
| 16 | + /// ### Why is this bad? |
| 17 | + /// This needlessly brings a trait in trait's namespace. |
| 18 | + /// |
| 19 | + /// ### Example |
| 20 | + /// ```rust |
| 21 | + /// use std::io::Read; |
| 22 | + /// fn main() { |
| 23 | + /// let mut b = "I'm your father!".as_bytes(); |
| 24 | + /// let mut buffer = [0; 10]; |
| 25 | + /// b.read(&mut buffer) |
| 26 | + /// } |
| 27 | + /// ``` |
| 28 | + /// Use instead: |
| 29 | + /// ```rust |
| 30 | + /// use std::io::Read as _; |
| 31 | + /// fn main() { |
| 32 | + /// let mut b = "I'm your father!".as_bytes(); |
| 33 | + /// let mut buffer = [0; 10]; |
| 34 | + /// b.read(&mut buffer) |
| 35 | + /// } |
| 36 | + /// ``` |
| 37 | + #[clippy::version = "1.69.0"] |
| 38 | + pub NEEDLESS_TRAITS_IN_SCOPE, |
| 39 | + pedantic, |
| 40 | + "trait is needlessly imported in trait's namespace, and can be anonymously imported" |
| 41 | +} |
| 42 | +declare_lint_pass!(NeedlessTraitsInScope => [NEEDLESS_TRAITS_IN_SCOPE]); |
| 43 | + |
| 44 | +impl<'tcx> LateLintPass<'tcx> for NeedlessTraitsInScope { |
| 45 | + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { |
| 46 | + // Only process `use` statements, ignore `UseKind::Glob` |
| 47 | + let ItemKind::Use(use_path, UseKind::Single) = item.kind else { |
| 48 | + return |
| 49 | + }; |
| 50 | + // Check if the `use` is aliased with ` as `. |
| 51 | + // If aliased, then do not process, it's probably for a good reason |
| 52 | + if item.ident != use_path.segments.last().unwrap().ident { |
| 53 | + return; |
| 54 | + } |
| 55 | + let path = use_path |
| 56 | + .segments |
| 57 | + .iter() |
| 58 | + .map(|segment| segment.ident) |
| 59 | + .fold(String::new(), |mut acc, ident| { |
| 60 | + if !acc.is_empty() { |
| 61 | + acc += "::"; |
| 62 | + } |
| 63 | + acc += ident.as_str(); |
| 64 | + acc |
| 65 | + }); |
| 66 | + span_lint_and_sugg( |
| 67 | + cx, |
| 68 | + NEEDLESS_TRAITS_IN_SCOPE, |
| 69 | + use_path.span, |
| 70 | + "trait is needlessly imported in trait's namespace", |
| 71 | + "you can import the trait anonymously", |
| 72 | + format!("{path} as _"), |
| 73 | + Applicability::MachineApplicable, |
| 74 | + ); |
| 75 | + } |
| 76 | +} |
0 commit comments