|
| 1 | +use clippy_utils::{ |
| 2 | + diagnostics::{span_lint, span_lint_hir_and_then}, |
| 3 | + path_res, |
| 4 | + ty::implements_trait, |
| 5 | +}; |
| 6 | +use rustc_hir::{def_id::DefId, Item, ItemKind, Node}; |
| 7 | +use rustc_hir_analysis::hir_ty_to_ty; |
| 8 | +use rustc_lint::{LateContext, LateLintPass}; |
| 9 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 10 | +use rustc_span::sym; |
| 11 | + |
| 12 | +declare_clippy_lint! { |
| 13 | + /// ### What it does |
| 14 | + /// Checks for types named `Error` that implement `Error`. |
| 15 | + /// |
| 16 | + /// ### Why is this bad? |
| 17 | + /// It can become confusing when a codebase has 20 types all named `Error`, requiring either |
| 18 | + /// aliasing them in the `use` statement them or qualifying them like `my_module::Error`. This |
| 19 | + /// severely hinders readability. |
| 20 | + /// |
| 21 | + /// ### Example |
| 22 | + /// ```rust,ignore |
| 23 | + /// #[derive(Debug)] |
| 24 | + /// pub enum Error { ... } |
| 25 | + /// |
| 26 | + /// impl std::fmt::Display for Error { ... } |
| 27 | + /// |
| 28 | + /// impl std::error::Error for Error { ... } |
| 29 | + /// ``` |
| 30 | + #[clippy::version = "1.72.0"] |
| 31 | + pub ERROR_IMPL_ERROR, |
| 32 | + restriction, |
| 33 | + "types named `Error` that implement `Error`" |
| 34 | +} |
| 35 | +declare_lint_pass!(ErrorImplError => [ERROR_IMPL_ERROR]); |
| 36 | + |
| 37 | +impl<'tcx> LateLintPass<'tcx> for ErrorImplError { |
| 38 | + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { |
| 39 | + let Some(error_def_id) = cx.tcx.get_diagnostic_item(sym::Error) else { |
| 40 | + return; |
| 41 | + }; |
| 42 | + |
| 43 | + match item.kind { |
| 44 | + ItemKind::TyAlias(ty, _) if implements_trait(cx, hir_ty_to_ty(cx.tcx, ty), error_def_id, &[]) |
| 45 | + && item.ident.name == sym::Error => |
| 46 | + { |
| 47 | + span_lint( |
| 48 | + cx, |
| 49 | + ERROR_IMPL_ERROR, |
| 50 | + item.ident.span, |
| 51 | + "type alias named `Error` that implements `Error`", |
| 52 | + ); |
| 53 | + }, |
| 54 | + ItemKind::Impl(imp) if let Some(trait_def_id) = imp.of_trait.and_then(|t| t.trait_def_id()) |
| 55 | + && error_def_id == trait_def_id |
| 56 | + && let Some(def_id) = path_res(cx, imp.self_ty).opt_def_id().and_then(DefId::as_local) |
| 57 | + && let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id) |
| 58 | + && let Node::Item(ty_item) = cx.tcx.hir().get(hir_id) |
| 59 | + && ty_item.ident.name == sym::Error => |
| 60 | + { |
| 61 | + span_lint_hir_and_then( |
| 62 | + cx, |
| 63 | + ERROR_IMPL_ERROR, |
| 64 | + hir_id, |
| 65 | + ty_item.ident.span, |
| 66 | + "type named `Error` that implements `Error`", |
| 67 | + |diag| { |
| 68 | + diag.span_note(item.span, "`Error` was implemented here"); |
| 69 | + } |
| 70 | + ); |
| 71 | + } |
| 72 | + _ => {}, |
| 73 | + } |
| 74 | + {} |
| 75 | + } |
| 76 | +} |
0 commit comments