|
| 1 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 2 | +use clippy_utils::source::snippet; |
| 3 | +use rustc_errors::{Applicability, SuggestionStyle}; |
| 4 | +use rustc_hir::def_id::LocalDefId; |
| 5 | +use rustc_hir::intravisit::FnKind; |
| 6 | +use rustc_hir::{ |
| 7 | + Body, FnDecl, FnRetTy, GenericArg, GenericBound, ImplItem, ImplItemKind, ItemKind, TraitBoundModifier, TraitItem, |
| 8 | + TraitItemKind, TyKind, |
| 9 | +}; |
| 10 | +use rustc_hir_analysis::hir_ty_to_ty; |
| 11 | +use rustc_lint::{LateContext, LateLintPass}; |
| 12 | +use rustc_middle::ty::{self, ClauseKind, TyCtxt}; |
| 13 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 14 | +use rustc_span::Span; |
| 15 | + |
| 16 | +declare_clippy_lint! { |
| 17 | + /// ### What it does |
| 18 | + /// Looks for bounds in `impl Trait` in return position that are implied by other bounds. |
| 19 | + /// This can happen when a trait is specified that another trait already has as a supertrait |
| 20 | + /// (e.g. `fn() -> impl Deref + DerefMut<Target = i32>` has an unnecessary `Deref` bound, |
| 21 | + /// because `Deref` is a supertrait of `DerefMut`) |
| 22 | + /// |
| 23 | + /// ### Why is this bad? |
| 24 | + /// Specifying more bounds than necessary adds needless complexity for the reader. |
| 25 | + /// |
| 26 | + /// ### Limitations |
| 27 | + /// This lint does not check for implied bounds transitively. Meaning that |
| 28 | + /// it does't check for implied bounds from supertraits of supertraits |
| 29 | + /// (e.g. `trait A {} trait B: A {} trait C: B {}`, then having an `fn() -> impl A + C`) |
| 30 | + /// |
| 31 | + /// ### Example |
| 32 | + /// ```rust |
| 33 | + /// # use std::ops::{Deref,DerefMut}; |
| 34 | + /// fn f() -> impl Deref<Target = i32> + DerefMut<Target = i32> { |
| 35 | + /// // ^^^^^^^^^^^^^^^^^^^ unnecessary bound, already implied by the `DerefMut` trait bound |
| 36 | + /// Box::new(123) |
| 37 | + /// } |
| 38 | + /// ``` |
| 39 | + /// Use instead: |
| 40 | + /// ```rust |
| 41 | + /// # use std::ops::{Deref,DerefMut}; |
| 42 | + /// fn f() -> impl DerefMut<Target = i32> { |
| 43 | + /// Box::new(123) |
| 44 | + /// } |
| 45 | + /// ``` |
| 46 | + #[clippy::version = "1.73.0"] |
| 47 | + pub IMPLIED_BOUNDS_IN_IMPLS, |
| 48 | + complexity, |
| 49 | + "specifying bounds that are implied by other bounds in `impl Trait` type" |
| 50 | +} |
| 51 | +declare_lint_pass!(ImpliedBoundsInImpls => [IMPLIED_BOUNDS_IN_IMPLS]); |
| 52 | + |
| 53 | +/// This function tries to, for all type parameters in a supertype predicate `GenericTrait<U>`, |
| 54 | +/// check if the substituted type in the implied-by bound matches with what's subtituted in the |
| 55 | +/// implied type. |
| 56 | +/// |
| 57 | +/// Consider this example. |
| 58 | +/// ```rust,ignore |
| 59 | +/// trait GenericTrait<T> {} |
| 60 | +/// trait GenericSubTrait<T, U, V>: GenericTrait<U> {} |
| 61 | +/// ^ trait_predicate_args: [Self#0, U#2] |
| 62 | +/// impl GenericTrait<i32> for () {} |
| 63 | +/// impl GenericSubTrait<(), i32, ()> for () {} |
| 64 | +/// impl GenericSubTrait<(), [u8; 8], ()> for () {} |
| 65 | +/// |
| 66 | +/// fn f() -> impl GenericTrait<i32> + GenericSubTrait<(), [u8; 8], ()> { |
| 67 | +/// ^^^ implied_args ^^^^^^^^^^^^^^^ implied_by_args |
| 68 | +/// (we are interested in `[u8; 8]` specifically, as that |
| 69 | +/// is what `U` in `GenericTrait<U>` is substituted with) |
| 70 | +/// () |
| 71 | +/// } |
| 72 | +/// ``` |
| 73 | +/// Here i32 != [u8; 8], so this will return false. |
| 74 | +fn is_same_generics( |
| 75 | + tcx: TyCtxt<'_>, |
| 76 | + trait_predicate_args: &[ty::GenericArg<'_>], |
| 77 | + implied_by_args: &[GenericArg<'_>], |
| 78 | + implied_args: &[GenericArg<'_>], |
| 79 | +) -> bool { |
| 80 | + trait_predicate_args |
| 81 | + .iter() |
| 82 | + .enumerate() |
| 83 | + .skip(1) // skip `Self` implicit arg |
| 84 | + .all(|(arg_index, arg)| { |
| 85 | + if let Some(ty) = arg.as_type() |
| 86 | + && let &ty::Param(ty::ParamTy{ index, .. }) = ty.kind() |
| 87 | + // Since `trait_predicate_args` and type params in traits start with `Self=0` |
| 88 | + // and generic argument lists `GenericTrait<i32>` don't have `Self`, |
| 89 | + // we need to subtract 1 from the index. |
| 90 | + && let GenericArg::Type(ty_a) = implied_by_args[index as usize - 1] |
| 91 | + && let GenericArg::Type(ty_b) = implied_args[arg_index - 1] |
| 92 | + { |
| 93 | + hir_ty_to_ty(tcx, ty_a) == hir_ty_to_ty(tcx, ty_b) |
| 94 | + } else { |
| 95 | + false |
| 96 | + } |
| 97 | + }) |
| 98 | +} |
| 99 | + |
| 100 | +fn check(cx: &LateContext<'_>, decl: &FnDecl<'_>) { |
| 101 | + if let FnRetTy::Return(ty) = decl.output |
| 102 | + &&let TyKind::OpaqueDef(item_id, ..) = ty.kind |
| 103 | + && let item = cx.tcx.hir().item(item_id) |
| 104 | + && let ItemKind::OpaqueTy(opaque_ty) = item.kind |
| 105 | + // Very often there is only a single bound, e.g. `impl Deref<..>`, in which case |
| 106 | + // we can avoid doing a bunch of stuff unnecessarily. |
| 107 | + && opaque_ty.bounds.len() > 1 |
| 108 | + { |
| 109 | + // Get all the (implied) trait predicates in the bounds. |
| 110 | + // For `impl Deref + DerefMut` this will contain [`Deref`]. |
| 111 | + // The implied `Deref` comes from `DerefMut` because `trait DerefMut: Deref {}`. |
| 112 | + // N.B. (G)ATs are fine to disregard, because they must be the same for all of its supertraits. |
| 113 | + // Example: |
| 114 | + // `impl Deref<Target = i32> + DerefMut<Target = u32>` is not allowed. |
| 115 | + // `DerefMut::Target` needs to match `Deref::Target`. |
| 116 | + let implied_bounds: Vec<_> = opaque_ty.bounds.iter().filter_map(|bound| { |
| 117 | + if let GenericBound::Trait(poly_trait, TraitBoundModifier::None) = bound |
| 118 | + && let [.., path] = poly_trait.trait_ref.path.segments |
| 119 | + && poly_trait.bound_generic_params.is_empty() |
| 120 | + && let Some(trait_def_id) = path.res.opt_def_id() |
| 121 | + && let predicates = cx.tcx.super_predicates_of(trait_def_id).predicates |
| 122 | + && !predicates.is_empty() // If the trait has no supertrait, there is nothing to add. |
| 123 | + { |
| 124 | + Some((bound.span(), path.args.map_or([].as_slice(), |a| a.args), predicates)) |
| 125 | + } else { |
| 126 | + None |
| 127 | + } |
| 128 | + }).collect(); |
| 129 | + |
| 130 | + // Lint all bounds in the `impl Trait` type that are also in the `implied_bounds` vec. |
| 131 | + // This involves some extra logic when generic arguments are present, since |
| 132 | + // simply comparing trait `DefId`s won't be enough. We also need to compare the generics. |
| 133 | + for (index, bound) in opaque_ty.bounds.iter().enumerate() { |
| 134 | + if let GenericBound::Trait(poly_trait, TraitBoundModifier::None) = bound |
| 135 | + && let [.., path] = poly_trait.trait_ref.path.segments |
| 136 | + && let implied_args = path.args.map_or([].as_slice(), |a| a.args) |
| 137 | + && let Some(def_id) = poly_trait.trait_ref.path.res.opt_def_id() |
| 138 | + && let Some(implied_by_span) = implied_bounds.iter().find_map(|&(span, implied_by_args, preds)| { |
| 139 | + preds.iter().find_map(|(clause, _)| { |
| 140 | + if let ClauseKind::Trait(tr) = clause.kind().skip_binder() |
| 141 | + && tr.def_id() == def_id |
| 142 | + && is_same_generics(cx.tcx, tr.trait_ref.args, implied_by_args, implied_args) |
| 143 | + { |
| 144 | + Some(span) |
| 145 | + } else { |
| 146 | + None |
| 147 | + } |
| 148 | + }) |
| 149 | + }) |
| 150 | + { |
| 151 | + let implied_by = snippet(cx, implied_by_span, ".."); |
| 152 | + span_lint_and_then( |
| 153 | + cx, IMPLIED_BOUNDS_IN_IMPLS, |
| 154 | + poly_trait.span, |
| 155 | + &format!("this bound is already specified as the supertrait of `{implied_by}`"), |
| 156 | + |diag| { |
| 157 | + // If we suggest removing a bound, we may also need extend the span |
| 158 | + // to include the `+` token, so we don't end up with something like `impl + B` |
| 159 | + |
| 160 | + let implied_span_extended = if let Some(next_bound) = opaque_ty.bounds.get(index + 1) { |
| 161 | + poly_trait.span.to(next_bound.span().shrink_to_lo()) |
| 162 | + } else { |
| 163 | + poly_trait.span |
| 164 | + }; |
| 165 | + |
| 166 | + diag.span_suggestion_with_style( |
| 167 | + implied_span_extended, |
| 168 | + "try removing this bound", |
| 169 | + "", |
| 170 | + Applicability::MachineApplicable, |
| 171 | + SuggestionStyle::ShowAlways |
| 172 | + ); |
| 173 | + } |
| 174 | + ); |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +impl LateLintPass<'_> for ImpliedBoundsInImpls { |
| 181 | + fn check_fn( |
| 182 | + &mut self, |
| 183 | + cx: &LateContext<'_>, |
| 184 | + _: FnKind<'_>, |
| 185 | + decl: &FnDecl<'_>, |
| 186 | + _: &Body<'_>, |
| 187 | + _: Span, |
| 188 | + _: LocalDefId, |
| 189 | + ) { |
| 190 | + check(cx, decl); |
| 191 | + } |
| 192 | + fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) { |
| 193 | + if let TraitItemKind::Fn(sig, ..) = &item.kind { |
| 194 | + check(cx, sig.decl); |
| 195 | + } |
| 196 | + } |
| 197 | + fn check_impl_item(&mut self, cx: &LateContext<'_>, item: &ImplItem<'_>) { |
| 198 | + if let ImplItemKind::Fn(sig, ..) = &item.kind { |
| 199 | + check(cx, sig.decl); |
| 200 | + } |
| 201 | + } |
| 202 | +} |
0 commit comments