|
| 1 | +use rustc_errors::Applicability; |
| 2 | +use rustc_hir::def_id::{DefId, DefIdMap}; |
| 3 | +use rustc_hir::{ |
| 4 | + BoundPolarity, GenericBound, Generics, PolyTraitRef, TraitBoundModifiers, WherePredicateKind, |
| 5 | +}; |
| 6 | +use rustc_middle::ty::{ClauseKind, PredicatePolarity}; |
| 7 | +use rustc_session::{declare_lint, declare_lint_pass}; |
| 8 | +use rustc_span::symbol::Ident; |
| 9 | + |
| 10 | +use crate::{LateContext, LateLintPass, LintContext}; |
| 11 | + |
| 12 | +declare_lint! { |
| 13 | + /// The `needless_maybe_sized` lint detects `?Sized` bounds applied to type parameters that cannot be unsized. |
| 14 | + /// |
| 15 | + /// ### Example |
| 16 | + /// |
| 17 | + /// ```rust |
| 18 | + /// // `T` cannot be unsized because `Clone` requires it to be `Sized` |
| 19 | + /// fn f<T: Clone + ?Sized>(t: &T) {} |
| 20 | + /// ``` |
| 21 | + /// |
| 22 | + /// {{produces}} |
| 23 | + /// |
| 24 | + /// ### Explanation |
| 25 | + /// |
| 26 | + /// The `?Sized` bound is misleading because it cannot be satisfied by an |
| 27 | + /// unsized type. This lint notifies the user of said redundant bound. |
| 28 | + pub NEEDLESS_MAYBE_SIZED, |
| 29 | + Warn, |
| 30 | + "a `?Sized` bound that is unusable due to a `Sized` requirement" |
| 31 | +} |
| 32 | +declare_lint_pass!(NeedlessMaybeSized => [NEEDLESS_MAYBE_SIZED]); |
| 33 | + |
| 34 | +struct Bound<'tcx> { |
| 35 | + /// The [`DefId`] of the type parameter the bound refers to |
| 36 | + param: DefId, |
| 37 | + ident: Ident, |
| 38 | + |
| 39 | + trait_bound: &'tcx PolyTraitRef<'tcx>, |
| 40 | + |
| 41 | + predicate_pos: usize, |
| 42 | + bound_pos: usize, |
| 43 | +} |
| 44 | + |
| 45 | +/// Finds all of the [`Bound`]s that refer to a type parameter and are not from a macro expansion |
| 46 | +fn type_param_bounds<'tcx>(generics: &'tcx Generics<'tcx>) -> impl Iterator<Item = Bound<'tcx>> { |
| 47 | + generics |
| 48 | + .predicates |
| 49 | + .iter() |
| 50 | + .enumerate() |
| 51 | + .filter_map(|(predicate_pos, predicate)| { |
| 52 | + let WherePredicateKind::BoundPredicate(bound_predicate) = &predicate.kind else { |
| 53 | + return None; |
| 54 | + }; |
| 55 | + |
| 56 | + let (param, ident) = bound_predicate.bounded_ty.as_generic_param()?; |
| 57 | + |
| 58 | + Some( |
| 59 | + bound_predicate |
| 60 | + .bounds |
| 61 | + .iter() |
| 62 | + .enumerate() |
| 63 | + .filter_map(move |(bound_pos, bound)| match bound { |
| 64 | + GenericBound::Trait(trait_bound) => { |
| 65 | + Some(Bound { param, ident, trait_bound, predicate_pos, bound_pos }) |
| 66 | + } |
| 67 | + GenericBound::Outlives(_) | GenericBound::Use(..) => None, |
| 68 | + }) |
| 69 | + .filter(|bound| !bound.trait_bound.span.from_expansion()), |
| 70 | + ) |
| 71 | + }) |
| 72 | + .flatten() |
| 73 | +} |
| 74 | + |
| 75 | +/// Searches the supertraits of the trait referred to by `trait_bound` recursively, returning the |
| 76 | +/// path taken to find a `Sized` bound if one is found |
| 77 | +fn path_to_sized_bound(cx: &LateContext<'_>, trait_bound: &PolyTraitRef<'_>) -> Option<Vec<DefId>> { |
| 78 | + fn search(cx: &LateContext<'_>, path: &mut Vec<DefId>) -> bool { |
| 79 | + let trait_def_id = *path.last().unwrap(); |
| 80 | + |
| 81 | + if Some(trait_def_id) == cx.tcx.lang_items().sized_trait() { |
| 82 | + return true; |
| 83 | + } |
| 84 | + |
| 85 | + for (predicate, _) in |
| 86 | + cx.tcx.explicit_super_predicates_of(trait_def_id).iter_identity_copied() |
| 87 | + { |
| 88 | + if let ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder() |
| 89 | + && trait_predicate.polarity == PredicatePolarity::Positive |
| 90 | + && !path.contains(&trait_predicate.def_id()) |
| 91 | + { |
| 92 | + path.push(trait_predicate.def_id()); |
| 93 | + if search(cx, path) { |
| 94 | + return true; |
| 95 | + } |
| 96 | + path.pop(); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + false |
| 101 | + } |
| 102 | + |
| 103 | + let mut path = vec![trait_bound.trait_ref.trait_def_id()?]; |
| 104 | + search(cx, &mut path).then_some(path) |
| 105 | +} |
| 106 | + |
| 107 | +impl LateLintPass<'_> for NeedlessMaybeSized { |
| 108 | + fn check_generics(&mut self, cx: &LateContext<'_>, generics: &Generics<'_>) { |
| 109 | + let Some(sized_trait) = cx.tcx.lang_items().sized_trait() else { |
| 110 | + return; |
| 111 | + }; |
| 112 | + |
| 113 | + let maybe_sized_params: DefIdMap<_> = type_param_bounds(generics) |
| 114 | + .filter(|bound| { |
| 115 | + bound.trait_bound.trait_ref.trait_def_id() == Some(sized_trait) |
| 116 | + && matches!(bound.trait_bound.modifiers.polarity, BoundPolarity::Maybe(_)) |
| 117 | + }) |
| 118 | + .map(|bound| (bound.param, bound)) |
| 119 | + .collect(); |
| 120 | + |
| 121 | + for bound in type_param_bounds(generics) { |
| 122 | + if bound.trait_bound.modifiers == TraitBoundModifiers::NONE |
| 123 | + && let Some(sized_bound) = maybe_sized_params.get(&bound.param) |
| 124 | + && let Some(path) = path_to_sized_bound(cx, bound.trait_bound) |
| 125 | + { |
| 126 | + cx.span_lint(NEEDLESS_MAYBE_SIZED, sized_bound.trait_bound.span, |diag| { |
| 127 | + diag.primary_message( |
| 128 | + "`?Sized` bound is ignored because of a `Sized` requirement", |
| 129 | + ); |
| 130 | + let ty_param = sized_bound.ident; |
| 131 | + diag.span_note( |
| 132 | + bound.trait_bound.span, |
| 133 | + format!("`{ty_param}` cannot be unsized because of the bound"), |
| 134 | + ); |
| 135 | + |
| 136 | + for &[current_id, next_id] in path.array_windows() { |
| 137 | + let current = cx.tcx.item_name(current_id); |
| 138 | + let next = cx.tcx.item_name(next_id); |
| 139 | + diag.note(format!("...because `{current}` has the bound `{next}`")); |
| 140 | + } |
| 141 | + |
| 142 | + diag.span_suggestion_verbose( |
| 143 | + generics.span_for_bound_removal( |
| 144 | + sized_bound.predicate_pos, |
| 145 | + sized_bound.bound_pos, |
| 146 | + ), |
| 147 | + "change the bounds that require `Sized`, or remove the `?Sized` bound", |
| 148 | + "", |
| 149 | + Applicability::MaybeIncorrect, |
| 150 | + ); |
| 151 | + }); |
| 152 | + |
| 153 | + return; |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | +} |
0 commit comments