|
| 1 | +use clippy_utils::diagnostics::span_lint; |
| 2 | +use clippy_utils::sym; |
| 3 | +use rustc_errors::MultiSpan; |
| 4 | +use rustc_hir::*; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_session::declare_lint_pass; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// |
| 11 | + /// Finds manual impls of `TryFrom` with infallible error types. |
| 12 | + /// |
| 13 | + /// ### Why is this bad? |
| 14 | + /// |
| 15 | + /// Infalliable conversions should be implemented via `From` with the blanket conversion. |
| 16 | + /// |
| 17 | + /// ### Example |
| 18 | + /// ```no_run |
| 19 | + /// impl TryFrom<i16> for MyStruct { |
| 20 | + /// type Error = Infallible; |
| 21 | + /// fn try_from(other: i16) -> Result<Self, Infallible> { |
| 22 | + /// Ok(Self(other.into())) |
| 23 | + /// } |
| 24 | + /// } |
| 25 | + /// ``` |
| 26 | + /// Use instead: |
| 27 | + /// ```no_run |
| 28 | + /// impl From<i16> for MyStruct { |
| 29 | + /// fn from(other: i16) -> Self { |
| 30 | + /// Self(other) |
| 31 | + /// } |
| 32 | + /// } |
| 33 | + /// ``` |
| 34 | + #[clippy::version = "1.88.0"] |
| 35 | + pub INFALLIBLE_TRY_FROM, |
| 36 | + nursery, |
| 37 | + "default lint description" |
| 38 | +} |
| 39 | +declare_lint_pass!(InfallibleTryFrom => [INFALLIBLE_TRY_FROM]); |
| 40 | + |
| 41 | +impl<'tcx> LateLintPass<'tcx> for InfallibleTryFrom { |
| 42 | + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { |
| 43 | + let ItemKind::Impl(imp) = item.kind else { return }; |
| 44 | + let Some(r#trait) = imp.of_trait else { return }; |
| 45 | + let Some(trait_def_id) = r#trait.trait_def_id() else { |
| 46 | + return; |
| 47 | + }; |
| 48 | + if !cx.tcx.is_diagnostic_item(sym::TryFrom, trait_def_id) { |
| 49 | + return; |
| 50 | + } |
| 51 | + for ii in imp.items { |
| 52 | + if ii.kind == AssocItemKind::Type { |
| 53 | + let ii_id = ii.id; |
| 54 | + let ii = cx.tcx.hir_impl_item(ii.id); |
| 55 | + if ii.ident.name.as_str() != "Error" { |
| 56 | + continue; |
| 57 | + } |
| 58 | + let ii_ty = ii.expect_type(); |
| 59 | + let ii_ty_span = ii_ty.span; |
| 60 | + let ii_ty = clippy_utils::ty::ty_from_hir_ty(cx, ii_ty); |
| 61 | + if !ii_ty.is_inhabited_from(cx.tcx, ii_id.owner_id.to_def_id(), cx.typing_env()) { |
| 62 | + let mut span = MultiSpan::from_span(cx.tcx.def_span(item.owner_id.to_def_id())); |
| 63 | + span.push_span_label(ii_ty_span, "infallible error type"); |
| 64 | + span_lint( |
| 65 | + cx, |
| 66 | + INFALLIBLE_TRY_FROM, |
| 67 | + span, |
| 68 | + "infallible TryFrom impl; consider implementing From, instead", |
| 69 | + ); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments