1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
2 use clippy_utils::source::{snippet, snippet_opt, snippet_with_applicability};
3 use clippy_utils::{SpanlessEq, SpanlessHash};
4 use core::hash::{Hash, Hasher};
5 use if_chain::if_chain;
6 use itertools::Itertools;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_data_structures::unhash::UnhashMap;
9 use rustc_errors::Applicability;
10 use rustc_hir::def::Res;
12 GenericArg, GenericBound, Generics, Item, ItemKind, Node, Path, PathSegment, PredicateOrigin, QPath,
13 TraitBoundModifier, TraitItem, TraitRef, Ty, TyKind, WherePredicate,
15 use rustc_lint::{LateContext, LateLintPass};
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::{BytePos, Span};
18 use std::collections::hash_map::Entry;
20 declare_clippy_lint! {
22 /// This lint warns about unnecessary type repetitions in trait bounds
24 /// ### Why is this bad?
25 /// Repeating the type for every bound makes the code
26 /// less readable than combining the bounds
30 /// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
35 /// pub fn foo<T>(t: T) where T: Copy + Clone {}
37 #[clippy::version = "1.38.0"]
38 pub TYPE_REPETITION_IN_BOUNDS,
40 "types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
43 declare_clippy_lint! {
45 /// Checks for cases where generics are being used and multiple
46 /// syntax specifications for trait bounds are used simultaneously.
48 /// ### Why is this bad?
49 /// Duplicate bounds makes the code
50 /// less readable than specifying them only once.
54 /// fn func<T: Clone + Default>(arg: T) where T: Clone + Default {}
60 /// fn func<T: Clone + Default>(arg: T) {}
65 /// fn func<T>(arg: T) where T: Clone + Default {}
69 /// fn foo<T: Default + Default>(bar: T) {}
73 /// fn foo<T: Default>(bar: T) {}
77 /// fn foo<T>(bar: T) where T: Default + Default {}
81 /// fn foo<T>(bar: T) where T: Default {}
83 #[clippy::version = "1.47.0"]
84 pub TRAIT_DUPLICATION_IN_BOUNDS,
86 "check if the same trait bounds are specified more than once during a generic declaration"
89 #[derive(Copy, Clone)]
90 pub struct TraitBounds {
91 max_trait_bounds: u64,
96 pub fn new(max_trait_bounds: u64) -> Self {
97 Self { max_trait_bounds }
101 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
103 impl<'tcx> LateLintPass<'tcx> for TraitBounds {
104 fn check_generics(&mut self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
105 self.check_type_repetition(cx, gen);
106 check_trait_bound_duplication(cx, gen);
109 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
110 // special handling for self trait bounds as these are not considered generics
111 // ie. trait Foo: Display {}
113 kind: ItemKind::Trait(_, _, _, bounds, ..),
117 rollup_traits(cx, bounds, "these bounds contain repeated elements");
121 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'tcx>) {
122 let mut self_bounds_map = FxHashMap::default();
124 for predicate in item.generics.predicates {
126 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
127 if bound_predicate.origin != PredicateOrigin::ImplTrait;
128 if !bound_predicate.span.from_expansion();
129 if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
130 if let Some(PathSegment {
131 res: Res::SelfTy{ trait_: Some(def_id), alias_to: _ }, ..
132 }) = segments.first();
136 kind: ItemKind::Trait(_, _, _, self_bounds, _),
139 ) = cx.tcx.hir().get_if_local(*def_id);
141 if self_bounds_map.is_empty() {
142 for bound in self_bounds.iter() {
143 let Some((self_res, self_segments, _)) = get_trait_info_from_bound(bound) else { continue };
144 self_bounds_map.insert(self_res, self_segments);
151 .filter_map(get_trait_info_from_bound)
152 .for_each(|(trait_item_res, trait_item_segments, span)| {
153 if let Some(self_segments) = self_bounds_map.get(&trait_item_res) {
154 if SpanlessEq::new(cx).eq_path_segments(self_segments, trait_item_segments) {
157 TRAIT_DUPLICATION_IN_BOUNDS,
159 "this trait bound is already specified in trait declaration",
161 "consider removing this trait bound",
173 fn check_type_repetition<'tcx>(self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
174 struct SpanlessTy<'cx, 'tcx> {
176 cx: &'cx LateContext<'tcx>,
178 impl PartialEq for SpanlessTy<'_, '_> {
179 fn eq(&self, other: &Self) -> bool {
180 let mut eq = SpanlessEq::new(self.cx);
181 eq.inter_expr().eq_ty(self.ty, other.ty)
184 impl Hash for SpanlessTy<'_, '_> {
185 fn hash<H: Hasher>(&self, h: &mut H) {
186 let mut t = SpanlessHash::new(self.cx);
188 h.write_u64(t.finish());
191 impl Eq for SpanlessTy<'_, '_> {}
193 if gen.span.from_expansion() {
196 let mut map: UnhashMap<SpanlessTy<'_, '_>, Vec<&GenericBound<'_>>> = UnhashMap::default();
197 let mut applicability = Applicability::MaybeIncorrect;
198 for bound in gen.predicates {
200 if let WherePredicate::BoundPredicate(ref p) = bound;
201 if p.origin != PredicateOrigin::ImplTrait;
202 if p.bounds.len() as u64 <= self.max_trait_bounds;
203 if !p.span.from_expansion();
204 if let Some(ref v) = map.insert(
205 SpanlessTy { ty: p.bounded_ty, cx },
206 p.bounds.iter().collect::<Vec<_>>()
213 .chain(p.bounds.iter())
214 .filter_map(get_trait_info_from_bound)
215 .map(|(_, _, span)| snippet_with_applicability(cx, span, "..", &mut applicability))
217 let hint_string = format!(
218 "consider combining the bounds: `{}: {}`",
219 snippet(cx, p.bounded_ty.span, "_"),
224 TYPE_REPETITION_IN_BOUNDS,
226 "this type has already been used as a bound predicate",
236 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
237 if gen.span.from_expansion() {
242 // fn bad_foo<T: Clone + Default, Z: Copy>(arg0: T, arg1: Z)
243 // where T: Clone + Default, { unimplemented!(); }
244 // ^^^^^^^^^^^^^^^^^^
246 // collects each of these where clauses into a set keyed by generic name and comparable trait
248 let where_predicates = gen
253 if pred.in_where_clause();
254 if let WherePredicate::BoundPredicate(bound_predicate) = pred;
255 if let TyKind::Path(QPath::Resolved(_, path)) = bound_predicate.bounded_ty.kind;
258 rollup_traits(cx, bound_predicate.bounds, "these where clauses contain repeated elements")
259 .into_iter().map(|(trait_ref, _)| (path.res, trait_ref)))
265 .collect::<FxHashSet<_>>();
268 // fn bad_foo<T: Clone + Default, Z: Copy>(arg0: T, arg1: Z) ...
269 // ^^^^^^^^^^^^^^^^^^ ^^^^^^^
271 // compare trait bounds keyed by generic name and comparable trait to collected where
272 // predicates eg. (T, Clone)
273 for predicate in gen.predicates.iter().filter(|pred| !pred.in_where_clause()) {
275 if let WherePredicate::BoundPredicate(bound_predicate) = predicate;
276 if bound_predicate.origin != PredicateOrigin::ImplTrait;
277 if !bound_predicate.span.from_expansion();
278 if let TyKind::Path(QPath::Resolved(_, path)) = bound_predicate.bounded_ty.kind;
280 let traits = rollup_traits(cx, bound_predicate.bounds, "these bounds contain repeated elements");
281 for (trait_ref, span) in traits {
282 let key = (path.res, trait_ref);
283 if where_predicates.contains(&key) {
286 TRAIT_DUPLICATION_IN_BOUNDS,
288 "this trait bound is already specified in the where clause",
290 "consider removing this trait bound",
299 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
300 struct ComparableTraitRef(Res, Vec<Res>);
301 impl Default for ComparableTraitRef {
302 fn default() -> Self {
303 Self(Res::Err, Vec::new())
307 fn get_trait_info_from_bound<'a>(bound: &'a GenericBound<'_>) -> Option<(Res, &'a [PathSegment<'a>], Span)> {
308 if let GenericBound::Trait(t, tbm) = bound {
309 let trait_path = t.trait_ref.path;
311 let path_span = trait_path.span;
312 if let TraitBoundModifier::Maybe = tbm {
313 path_span.with_lo(path_span.lo() - BytePos(1)) // include the `?`
318 Some((trait_path.res, trait_path.segments, trait_span))
324 // FIXME: ComparableTraitRef does not support nested bounds needed for associated_type_bounds
325 fn into_comparable_trait_ref(trait_ref: &TraitRef<'_>) -> ComparableTraitRef {
332 .filter_map(|segment| {
333 // get trait bound type arguments
334 Some(segment.args?.args.iter().filter_map(|arg| {
336 if let GenericArg::Type(ty) = arg;
337 if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind;
338 then { return Some(path.res) }
348 fn rollup_traits(cx: &LateContext<'_>, bounds: &[GenericBound<'_>], msg: &str) -> Vec<(ComparableTraitRef, Span)> {
349 let mut map = FxHashMap::default();
350 let mut repeated_res = false;
352 let only_comparable_trait_refs = |bound: &GenericBound<'_>| {
353 if let GenericBound::Trait(t, _) = bound {
354 Some((into_comparable_trait_ref(&t.trait_ref), t.span))
361 for bound in bounds.iter().filter_map(only_comparable_trait_refs) {
362 let (comparable_bound, span_direct) = bound;
363 match map.entry(comparable_bound) {
364 Entry::Occupied(_) => repeated_res = true,
365 Entry::Vacant(e) => {
366 e.insert((span_direct, i));
372 // Put bounds in source order
373 let mut comparable_bounds = vec![Default::default(); map.len()];
374 for (k, (v, i)) in map {
375 comparable_bounds[i] = (k, v);
380 if let [first_trait, .., last_trait] = bounds;
382 let all_trait_span = first_trait.span().to(last_trait.span());
384 let traits = comparable_bounds.iter()
385 .filter_map(|&(_, span)| snippet_opt(cx, span))
386 .collect::<Vec<_>>();
387 let traits = traits.join(" + ");
391 TRAIT_DUPLICATION_IN_BOUNDS,
396 Applicability::MachineApplicable