summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/clippy_lints/src/error_impl_error.rs
blob: 379af9b2234c280d7b734c9c5ac317396a457a01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use clippy_utils::diagnostics::{span_lint, span_lint_hir_and_then};
use clippy_utils::path_res;
use clippy_utils::ty::implements_trait;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{Item, ItemKind};
use rustc_hir_analysis::hir_ty_to_ty;
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::Visibility;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;

declare_clippy_lint! {
    /// ### What it does
    /// Checks for types named `Error` that implement `Error`.
    ///
    /// ### Why is this bad?
    /// It can become confusing when a codebase has 20 types all named `Error`, requiring either
    /// aliasing them in the `use` statement or qualifying them like `my_module::Error`. This
    /// hinders comprehension, as it requires you to memorize every variation of importing `Error`
    /// used across a codebase.
    ///
    /// ### Example
    /// ```rust,ignore
    /// #[derive(Debug)]
    /// pub enum Error { ... }
    ///
    /// impl std::fmt::Display for Error { ... }
    ///
    /// impl std::error::Error for Error { ... }
    /// ```
    #[clippy::version = "1.72.0"]
    pub ERROR_IMPL_ERROR,
    restriction,
    "exported types named `Error` that implement `Error`"
}
declare_lint_pass!(ErrorImplError => [ERROR_IMPL_ERROR]);

impl<'tcx> LateLintPass<'tcx> for ErrorImplError {
    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
        let Some(error_def_id) = cx.tcx.get_diagnostic_item(sym::Error) else {
            return;
        };

        match item.kind {
            ItemKind::TyAlias(ty, _) if implements_trait(cx, hir_ty_to_ty(cx.tcx, ty), error_def_id, &[])
                && item.ident.name == sym::Error
                && is_visible_outside_module(cx, item.owner_id.def_id) =>
            {
                span_lint(
                    cx,
                    ERROR_IMPL_ERROR,
                    item.ident.span,
                    "exported type alias named `Error` that implements `Error`",
                );
            },
            ItemKind::Impl(imp) if let Some(trait_def_id) = imp.of_trait.and_then(|t| t.trait_def_id())
                && error_def_id == trait_def_id
                && let Some(def_id) = path_res(cx, imp.self_ty).opt_def_id().and_then(DefId::as_local)
                && let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id)
                && let Some(ident) = cx.tcx.opt_item_ident(def_id.to_def_id())
                && ident.name == sym::Error
                && is_visible_outside_module(cx, def_id) =>
            {
                span_lint_hir_and_then(
                    cx,
                    ERROR_IMPL_ERROR,
                    hir_id,
                    ident.span,
                    "exported type named `Error` that implements `Error`",
                    |diag| {
                        diag.span_note(item.span, "`Error` was implemented here");
                    }
                );
            }
            _ => {},
        }
    }
}

/// Do not lint private `Error`s, i.e., ones without any `pub` (minus `pub(self)` of course) and
/// which aren't reexported
fn is_visible_outside_module(cx: &LateContext<'_>, def_id: LocalDefId) -> bool {
    !matches!(
        cx.tcx.visibility(def_id),
        Visibility::Restricted(mod_def_id) if cx.tcx.parent_module_from_def_id(def_id).to_def_id() == mod_def_id
    )
}