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;
7 use rustc_data_structures::unhash::UnhashMap;
8 use rustc_errors::Applicability;
9 use rustc_hir::def::Res;
11 GenericBound, Generics, Item, ItemKind, Node, Path, PathSegment, PredicateOrigin, QPath, TraitItem, Ty, TyKind,
14 use rustc_lint::{LateContext, LateLintPass};
15 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use std::fmt::Write as _;
19 declare_clippy_lint! {
21 /// This lint warns about unnecessary type repetitions in trait bounds
23 /// ### Why is this bad?
24 /// Repeating the type for every bound makes the code
25 /// less readable than combining the bounds
29 /// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
32 /// Could be written as:
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 {}
57 /// Could be written as:
60 /// fn func<T: Clone + Default>(arg: T) {}
65 /// fn func<T>(arg: T) where T: Clone + Default {}
67 #[clippy::version = "1.47.0"]
68 pub TRAIT_DUPLICATION_IN_BOUNDS,
70 "Check if the same trait bounds are specified twice during a function declaration"
73 #[derive(Copy, Clone)]
74 pub struct TraitBounds {
75 max_trait_bounds: u64,
80 pub fn new(max_trait_bounds: u64) -> Self {
81 Self { max_trait_bounds }
85 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
87 impl<'tcx> LateLintPass<'tcx> for TraitBounds {
88 fn check_generics(&mut self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
89 self.check_type_repetition(cx, gen);
90 check_trait_bound_duplication(cx, gen);
93 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'tcx>) {
94 let mut self_bounds_map = FxHashMap::default();
96 for predicate in item.generics.predicates {
98 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
99 if bound_predicate.origin != PredicateOrigin::ImplTrait;
100 if !bound_predicate.span.from_expansion();
101 if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
102 if let Some(PathSegment {
103 res: Some(Res::SelfTy{ trait_: Some(def_id), alias_to: _ }), ..
104 }) = segments.first();
108 kind: ItemKind::Trait(_, _, _, self_bounds, _),
111 ) = cx.tcx.hir().get_if_local(*def_id);
113 if self_bounds_map.is_empty() {
114 for bound in self_bounds.iter() {
115 let Some((self_res, self_segments, _)) = get_trait_info_from_bound(bound) else { continue };
116 self_bounds_map.insert(self_res, self_segments);
123 .filter_map(get_trait_info_from_bound)
124 .for_each(|(trait_item_res, trait_item_segments, span)| {
125 if let Some(self_segments) = self_bounds_map.get(&trait_item_res) {
126 if SpanlessEq::new(cx).eq_path_segments(self_segments, trait_item_segments) {
129 TRAIT_DUPLICATION_IN_BOUNDS,
131 "this trait bound is already specified in trait declaration",
133 "consider removing this trait bound",
145 fn check_type_repetition<'tcx>(self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
146 struct SpanlessTy<'cx, 'tcx> {
148 cx: &'cx LateContext<'tcx>,
150 impl PartialEq for SpanlessTy<'_, '_> {
151 fn eq(&self, other: &Self) -> bool {
152 let mut eq = SpanlessEq::new(self.cx);
153 eq.inter_expr().eq_ty(self.ty, other.ty)
156 impl Hash for SpanlessTy<'_, '_> {
157 fn hash<H: Hasher>(&self, h: &mut H) {
158 let mut t = SpanlessHash::new(self.cx);
160 h.write_u64(t.finish());
163 impl Eq for SpanlessTy<'_, '_> {}
165 if gen.span.from_expansion() {
168 let mut map: UnhashMap<SpanlessTy<'_, '_>, Vec<&GenericBound<'_>>> = UnhashMap::default();
169 let mut applicability = Applicability::MaybeIncorrect;
170 for bound in gen.predicates {
172 if let WherePredicate::BoundPredicate(ref p) = bound;
173 if p.origin != PredicateOrigin::ImplTrait;
174 if p.bounds.len() as u64 <= self.max_trait_bounds;
175 if !p.span.from_expansion();
176 if let Some(ref v) = map.insert(
177 SpanlessTy { ty: p.bounded_ty, cx },
178 p.bounds.iter().collect::<Vec<_>>()
182 let mut hint_string = format!(
183 "consider combining the bounds: `{}:",
184 snippet(cx, p.bounded_ty.span, "_")
187 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
188 let path = &poly_trait_ref.trait_ref.path;
189 let _ = write!(hint_string,
191 snippet_with_applicability(cx, path.span, "..", &mut applicability)
195 for b in p.bounds.iter() {
196 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
197 let path = &poly_trait_ref.trait_ref.path;
198 let _ = write!(hint_string,
200 snippet_with_applicability(cx, path.span, "..", &mut applicability)
204 hint_string.truncate(hint_string.len() - 2);
205 hint_string.push('`');
208 TYPE_REPETITION_IN_BOUNDS,
210 "this type has already been used as a bound predicate",
220 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
221 if gen.span.from_expansion() || gen.params.is_empty() || gen.predicates.is_empty() {
225 let mut map = FxHashMap::<_, Vec<_>>::default();
226 for predicate in gen.predicates {
228 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
229 if bound_predicate.origin != PredicateOrigin::ImplTrait;
230 if !bound_predicate.span.from_expansion();
231 if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
232 if let Some(segment) = segments.first();
234 for (res_where, _, span_where) in bound_predicate.bounds.iter().filter_map(get_trait_info_from_bound) {
235 let trait_resolutions_direct = map.entry(segment.ident).or_default();
236 if let Some((_, span_direct)) = trait_resolutions_direct
238 .find(|(res_direct, _)| *res_direct == res_where) {
241 TRAIT_DUPLICATION_IN_BOUNDS,
243 "this trait bound is already specified in the where clause",
245 "consider removing this trait bound",
249 trait_resolutions_direct.push((res_where, span_where));
257 fn get_trait_info_from_bound<'a>(bound: &'a GenericBound<'_>) -> Option<(Res, &'a [PathSegment<'a>], Span)> {
258 if let GenericBound::Trait(t, _) = bound {
259 Some((t.trait_ref.path.res, t.trait_ref.path.segments, t.span))