|
| 1 | +use clippy_utils::diagnostics::span_lint; |
| 2 | +use clippy_utils::ty::implements_trait; |
| 3 | +use rustc_hir::{Item, ItemKind}; |
| 4 | +use rustc_lint::{LateContext, LateLintPass}; |
| 5 | +use rustc_middle::ty::Visibility; |
| 6 | +use rustc_session::declare_lint_pass; |
| 7 | +use rustc_span::sym; |
| 8 | + |
| 9 | +declare_clippy_lint! { |
| 10 | + /// ### What it does |
| 11 | + /// Checks for potentially forgotten implementations of `Error` for public types. |
| 12 | + /// |
| 13 | + /// ### Why is this bad? |
| 14 | + /// `Error` provides a common interface for errors. |
| 15 | + /// Errors not implementing `Error` can not be used with functions that expect it. |
| 16 | + /// |
| 17 | + /// ### Example |
| 18 | + /// ```no_run |
| 19 | + /// #[derive(Debug)] |
| 20 | + /// pub struct ParseError; |
| 21 | + /// |
| 22 | + /// impl core::fmt::Display for ParseError { ... } |
| 23 | + /// ``` |
| 24 | + /// Use instead: |
| 25 | + /// ```no_run |
| 26 | + /// #[derive(Debug)] |
| 27 | + /// pub struct ParseError; |
| 28 | + /// |
| 29 | + /// impl core::fmt::Display for ParseError { ... } |
| 30 | + /// |
| 31 | + /// impl core::error::Error for ParseError { ... } |
| 32 | + /// ``` |
| 33 | + #[clippy::version = "1.87.0"] |
| 34 | + pub MISSING_ERROR_IMPL, |
| 35 | + suspicious, |
| 36 | + "exported types with potentially forgotten `Error` implementation" |
| 37 | +} |
| 38 | + |
| 39 | +declare_lint_pass!(MissingErrorImpl => [MISSING_ERROR_IMPL]); |
| 40 | + |
| 41 | +impl<'tcx> LateLintPass<'tcx> for MissingErrorImpl { |
| 42 | + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { |
| 43 | + match item.kind { |
| 44 | + ItemKind::Enum(_, generics) | ItemKind::Struct(_, generics) => { |
| 45 | + let is_error_candidate = { |
| 46 | + let name: &str = item.ident.name.as_str(); |
| 47 | + name.ends_with("Error") && name != "Error" |
| 48 | + }; |
| 49 | + if is_error_candidate |
| 50 | + // Only check public items, as missing impls for private items are easy to fix. |
| 51 | + && (cx.tcx.visibility(item.owner_id.def_id) == Visibility::Public) |
| 52 | + // Check whether Error is implemented, |
| 53 | + // skipping generic types as we'd have to ask whether there is an error impl |
| 54 | + // for any instantiation of it. |
| 55 | + && generics.params.is_empty() |
| 56 | + && let ty = cx.tcx.type_of(item.owner_id).instantiate_identity() |
| 57 | + && let Some(error_def_id) = cx.tcx.get_diagnostic_item(sym::Error) |
| 58 | + && !implements_trait(cx, ty, error_def_id, &[]) |
| 59 | + { |
| 60 | + span_lint( |
| 61 | + cx, |
| 62 | + MISSING_ERROR_IMPL, |
| 63 | + item.ident.span, |
| 64 | + "error type doesn't implement `Error`", |
| 65 | + ); |
| 66 | + } |
| 67 | + }, |
| 68 | + _ => {}, |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments