1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::source::{snippet, snippet_with_applicability};
3 use clippy_utils::{SpanlessEq, SpanlessHash};
4 use core::hash::{Hash, Hasher};
5 use if_chain::if_chain;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_data_structures::unhash::UnhashMap;
8 use rustc_errors::Applicability;
9 use rustc_hir::def::Res;
11 GenericBound, Generics, Item, ItemKind, Node, ParamName, Path, PathSegment, QPath, TraitItem, Ty, TyKind,
14 use rustc_lint::{LateContext, LateLintPass};
15 use rustc_session::{declare_tool_lint, impl_lint_pass};
18 declare_clippy_lint! {
20 /// This lint warns about unnecessary type repetitions in trait bounds
22 /// ### Why is this bad?
23 /// Repeating the type for every bound makes the code
24 /// less readable than combining the bounds
28 /// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
31 /// Could be written as:
34 /// pub fn foo<T>(t: T) where T: Copy + Clone {}
36 #[clippy::version = "1.38.0"]
37 pub TYPE_REPETITION_IN_BOUNDS,
39 "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
42 declare_clippy_lint! {
44 /// Checks for cases where generics are being used and multiple
45 /// syntax specifications for trait bounds are used simultaneously.
47 /// ### Why is this bad?
48 /// Duplicate bounds makes the code
49 /// less readable than specifing them only once.
53 /// fn func<T: Clone + Default>(arg: T) where T: Clone + Default {}
56 /// Could be written as:
59 /// fn func<T: Clone + Default>(arg: T) {}
64 /// fn func<T>(arg: T) where T: Clone + Default {}
66 #[clippy::version = "1.47.0"]
67 pub TRAIT_DUPLICATION_IN_BOUNDS,
69 "Check if the same trait bounds are specified twice during a function declaration"
72 #[derive(Copy, Clone)]
73 pub struct TraitBounds {
74 max_trait_bounds: u64,
79 pub fn new(max_trait_bounds: u64) -> Self {
80 Self { max_trait_bounds }
84 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
86 impl<'tcx> LateLintPass<'tcx> for TraitBounds {
87 fn check_generics(&mut self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
88 self.check_type_repetition(cx, gen);
89 check_trait_bound_duplication(cx, gen);
92 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'tcx>) {
93 let Generics { where_clause, .. } = &item.generics;
94 let mut self_bounds_set = FxHashSet::default();
96 for predicate in where_clause.predicates {
98 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
99 if !bound_predicate.span.from_expansion();
100 if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
101 if let Some(PathSegment { res: Some(Res::SelfTy(Some(def_id), _)), .. }) = segments.first();
106 kind: ItemKind::Trait(_, _, _, self_bounds, _),
109 ) = cx.tcx.hir().get_if_local(*def_id);
111 if self_bounds_set.is_empty() {
112 for bound in self_bounds.iter() {
113 let Some((self_res, _)) = get_trait_res_span_from_bound(bound) else { continue };
114 self_bounds_set.insert(self_res);
121 .filter_map(get_trait_res_span_from_bound)
122 .for_each(|(trait_item_res, span)| {
123 if self_bounds_set.get(&trait_item_res).is_some() {
126 TRAIT_DUPLICATION_IN_BOUNDS,
128 "this trait bound is already specified in trait declaration",
130 "consider removing this trait bound",
140 fn get_trait_res_span_from_bound(bound: &GenericBound<'_>) -> Option<(Res, Span)> {
141 if let GenericBound::Trait(t, _) = bound {
142 Some((t.trait_ref.path.res, t.span))
149 fn check_type_repetition<'tcx>(self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
150 struct SpanlessTy<'cx, 'tcx> {
152 cx: &'cx LateContext<'tcx>,
154 impl PartialEq for SpanlessTy<'_, '_> {
155 fn eq(&self, other: &Self) -> bool {
156 let mut eq = SpanlessEq::new(self.cx);
157 eq.inter_expr().eq_ty(self.ty, other.ty)
160 impl Hash for SpanlessTy<'_, '_> {
161 fn hash<H: Hasher>(&self, h: &mut H) {
162 let mut t = SpanlessHash::new(self.cx);
164 h.write_u64(t.finish());
167 impl Eq for SpanlessTy<'_, '_> {}
169 if gen.span.from_expansion() {
172 let mut map: UnhashMap<SpanlessTy<'_, '_>, Vec<&GenericBound<'_>>> = UnhashMap::default();
173 let mut applicability = Applicability::MaybeIncorrect;
174 for bound in gen.where_clause.predicates {
176 if let WherePredicate::BoundPredicate(ref p) = bound;
177 if p.bounds.len() as u64 <= self.max_trait_bounds;
178 if !p.span.from_expansion();
179 if let Some(ref v) = map.insert(
180 SpanlessTy { ty: p.bounded_ty, cx },
181 p.bounds.iter().collect::<Vec<_>>()
185 let mut hint_string = format!(
186 "consider combining the bounds: `{}:",
187 snippet(cx, p.bounded_ty.span, "_")
190 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
191 let path = &poly_trait_ref.trait_ref.path;
192 hint_string.push_str(&format!(
194 snippet_with_applicability(cx, path.span, "..", &mut applicability)
198 for b in p.bounds.iter() {
199 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
200 let path = &poly_trait_ref.trait_ref.path;
201 hint_string.push_str(&format!(
203 snippet_with_applicability(cx, path.span, "..", &mut applicability)
207 hint_string.truncate(hint_string.len() - 2);
208 hint_string.push('`');
211 TYPE_REPETITION_IN_BOUNDS,
213 "this type has already been used as a bound predicate",
223 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
224 if gen.span.from_expansion() || gen.params.is_empty() || gen.where_clause.predicates.is_empty() {
228 let mut map = FxHashMap::default();
229 for param in gen.params {
230 if let ParamName::Plain(ref ident) = param.name {
234 .filter_map(get_trait_res_span_from_bound)
235 .collect::<Vec<_>>();
236 map.insert(*ident, res);
240 for predicate in gen.where_clause.predicates {
242 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
243 if !bound_predicate.span.from_expansion();
244 if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
245 if let Some(segment) = segments.first();
246 if let Some(trait_resolutions_direct) = map.get(&segment.ident);
248 for (res_where, _) in bound_predicate.bounds.iter().filter_map(get_trait_res_span_from_bound) {
249 if let Some((_, span_direct)) = trait_resolutions_direct
251 .find(|(res_direct, _)| *res_direct == res_where) {
254 TRAIT_DUPLICATION_IN_BOUNDS,
256 "this trait bound is already specified in the where clause",
258 "consider removing this trait bound",