|
| 1 | +use clippy_utils::diagnostics::span_lint_and_help; |
| 2 | +use rustc_hir::*; |
| 3 | +use rustc_lint::{LateContext, LateLintPass}; |
| 4 | +use rustc_session::declare_lint_pass; |
| 5 | +use rustc_span::sym; |
| 6 | + |
| 7 | +declare_clippy_lint! { |
| 8 | + /// ### What it does |
| 9 | + /// Checks for direct implementations of `ToString`. |
| 10 | + /// ### Why is this bad? |
| 11 | + /// This trait is automatically implemented for any type which implements the `Display` trait. |
| 12 | + /// As such, `ToString` shouldn’t be implemented directly: `Display` should be implemented instead, |
| 13 | + /// and you get the `ToString` implementation for free. |
| 14 | + /// ### Example |
| 15 | + /// ```no_run |
| 16 | + /// impl ToString for Point { |
| 17 | + /// fn to_string(&self) -> String { |
| 18 | + /// format!("({}, {})", self.x, self.y) |
| 19 | + /// } |
| 20 | + /// } |
| 21 | + /// ``` |
| 22 | + /// Use instead: |
| 23 | + /// ```no_run |
| 24 | + /// impl fmt::Display for Point { |
| 25 | + /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 26 | + /// write!(f, "({}, {})", self.x, self.y) |
| 27 | + /// } |
| 28 | + /// } |
| 29 | + /// ``` |
| 30 | + #[clippy::version = "1.77.0"] |
| 31 | + pub TOSTRING_IMPL, |
| 32 | + style, |
| 33 | + "default lint description" |
| 34 | +} |
| 35 | + |
| 36 | +declare_lint_pass!(TostringImpl => [TOSTRING_IMPL]); |
| 37 | + |
| 38 | +impl<'tcx> LateLintPass<'tcx> for TostringImpl { |
| 39 | + fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx Item<'tcx>) { |
| 40 | + if let ItemKind::Impl(Impl { |
| 41 | + of_trait: Some(trait_ref), |
| 42 | + .. |
| 43 | + }) = it.kind |
| 44 | + && let Some(trait_did) = trait_ref.trait_def_id() |
| 45 | + && cx.tcx.is_diagnostic_item(sym::ToString, trait_did) |
| 46 | + { |
| 47 | + span_lint_and_help( |
| 48 | + cx, |
| 49 | + TOSTRING_IMPL, |
| 50 | + it.span, |
| 51 | + "direct implementation of `ToString`", |
| 52 | + None, |
| 53 | + "prefer implementing `Display` instead", |
| 54 | + ); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments