]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/trait_bounds.rs
Rollup merge of #97415 - cjgillot:is-late-bound-solo, r=estebank
[rust.git] / clippy_lints / src / trait_bounds.rs
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;
10 use rustc_hir::{
11     GenericBound, Generics, Item, ItemKind, Node, Path, PathSegment, PredicateOrigin, QPath, TraitItem, Ty, TyKind,
12     WherePredicate,
13 };
14 use rustc_lint::{LateContext, LateLintPass};
15 use rustc_session::{declare_tool_lint, impl_lint_pass};
16 use rustc_span::Span;
17 use std::fmt::Write as _;
18
19 declare_clippy_lint! {
20     /// ### What it does
21     /// This lint warns about unnecessary type repetitions in trait bounds
22     ///
23     /// ### Why is this bad?
24     /// Repeating the type for every bound makes the code
25     /// less readable than combining the bounds
26     ///
27     /// ### Example
28     /// ```rust
29     /// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
30     /// ```
31     ///
32     /// Could be written as:
33     ///
34     /// ```rust
35     /// pub fn foo<T>(t: T) where T: Copy + Clone {}
36     /// ```
37     #[clippy::version = "1.38.0"]
38     pub TYPE_REPETITION_IN_BOUNDS,
39     pedantic,
40     "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
41 }
42
43 declare_clippy_lint! {
44     /// ### What it does
45     /// Checks for cases where generics are being used and multiple
46     /// syntax specifications for trait bounds are used simultaneously.
47     ///
48     /// ### Why is this bad?
49     /// Duplicate bounds makes the code
50     /// less readable than specifying them only once.
51     ///
52     /// ### Example
53     /// ```rust
54     /// fn func<T: Clone + Default>(arg: T) where T: Clone + Default {}
55     /// ```
56     ///
57     /// Could be written as:
58     ///
59     /// ```rust
60     /// fn func<T: Clone + Default>(arg: T) {}
61     /// ```
62     /// or
63     ///
64     /// ```rust
65     /// fn func<T>(arg: T) where T: Clone + Default {}
66     /// ```
67     #[clippy::version = "1.47.0"]
68     pub TRAIT_DUPLICATION_IN_BOUNDS,
69     pedantic,
70     "Check if the same trait bounds are specified twice during a function declaration"
71 }
72
73 #[derive(Copy, Clone)]
74 pub struct TraitBounds {
75     max_trait_bounds: u64,
76 }
77
78 impl TraitBounds {
79     #[must_use]
80     pub fn new(max_trait_bounds: u64) -> Self {
81         Self { max_trait_bounds }
82     }
83 }
84
85 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
86
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);
91     }
92
93     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'tcx>) {
94         let mut self_bounds_map = FxHashMap::default();
95
96         for predicate in item.generics.predicates {
97             if_chain! {
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();
105                 if let Some(
106                     Node::Item(
107                         Item {
108                             kind: ItemKind::Trait(_, _, _, self_bounds, _),
109                             .. }
110                         )
111                     ) = cx.tcx.hir().get_if_local(*def_id);
112                 then {
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);
117                         }
118                     }
119
120                     bound_predicate
121                         .bounds
122                         .iter()
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) {
127                                     span_lint_and_help(
128                                         cx,
129                                         TRAIT_DUPLICATION_IN_BOUNDS,
130                                         span,
131                                         "this trait bound is already specified in trait declaration",
132                                         None,
133                                         "consider removing this trait bound",
134                                     );
135                                 }
136                             }
137                         });
138                 }
139             }
140         }
141     }
142 }
143
144 impl TraitBounds {
145     fn check_type_repetition<'tcx>(self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
146         struct SpanlessTy<'cx, 'tcx> {
147             ty: &'tcx Ty<'tcx>,
148             cx: &'cx LateContext<'tcx>,
149         }
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)
154             }
155         }
156         impl Hash for SpanlessTy<'_, '_> {
157             fn hash<H: Hasher>(&self, h: &mut H) {
158                 let mut t = SpanlessHash::new(self.cx);
159                 t.hash_ty(self.ty);
160                 h.write_u64(t.finish());
161             }
162         }
163         impl Eq for SpanlessTy<'_, '_> {}
164
165         if gen.span.from_expansion() {
166             return;
167         }
168         let mut map: UnhashMap<SpanlessTy<'_, '_>, Vec<&GenericBound<'_>>> = UnhashMap::default();
169         let mut applicability = Applicability::MaybeIncorrect;
170         for bound in gen.predicates {
171             if_chain! {
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<_>>()
179                 );
180
181                 then {
182                     let mut hint_string = format!(
183                         "consider combining the bounds: `{}:",
184                         snippet(cx, p.bounded_ty.span, "_")
185                     );
186                     for b in v.iter() {
187                         if let GenericBound::Trait(ref poly_trait_ref, _) = b {
188                             let path = &poly_trait_ref.trait_ref.path;
189                             let _ = write!(hint_string,
190                                 " {} +",
191                                 snippet_with_applicability(cx, path.span, "..", &mut applicability)
192                             );
193                         }
194                     }
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,
199                                 " {} +",
200                                 snippet_with_applicability(cx, path.span, "..", &mut applicability)
201                             );
202                         }
203                     }
204                     hint_string.truncate(hint_string.len() - 2);
205                     hint_string.push('`');
206                     span_lint_and_help(
207                         cx,
208                         TYPE_REPETITION_IN_BOUNDS,
209                         p.span,
210                         "this type has already been used as a bound predicate",
211                         None,
212                         &hint_string,
213                     );
214                 }
215             }
216         }
217     }
218 }
219
220 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
221     if gen.span.from_expansion() || gen.params.is_empty() || gen.predicates.is_empty() {
222         return;
223     }
224
225     let mut map = FxHashMap::<_, Vec<_>>::default();
226     for predicate in gen.predicates {
227         if_chain! {
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();
233             then {
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
237                                                 .iter()
238                                                 .find(|(res_direct, _)| *res_direct == res_where) {
239                         span_lint_and_help(
240                             cx,
241                             TRAIT_DUPLICATION_IN_BOUNDS,
242                             *span_direct,
243                             "this trait bound is already specified in the where clause",
244                             None,
245                             "consider removing this trait bound",
246                         );
247                     }
248                     else {
249                         trait_resolutions_direct.push((res_where, span_where));
250                     }
251                 }
252             }
253         }
254     }
255 }
256
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))
260     } else {
261         None
262     }
263 }