]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/trait_bounds.rs
Rollup merge of #92021 - woodenarrow:br_single_fp_element, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / 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, ParamName, Path, PathSegment, 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
18 declare_clippy_lint! {
19     /// ### What it does
20     /// This lint warns about unnecessary type repetitions in trait bounds
21     ///
22     /// ### Why is this bad?
23     /// Repeating the type for every bound makes the code
24     /// less readable than combining the bounds
25     ///
26     /// ### Example
27     /// ```rust
28     /// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
29     /// ```
30     ///
31     /// Could be written as:
32     ///
33     /// ```rust
34     /// pub fn foo<T>(t: T) where T: Copy + Clone {}
35     /// ```
36     #[clippy::version = "1.38.0"]
37     pub TYPE_REPETITION_IN_BOUNDS,
38     pedantic,
39     "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
40 }
41
42 declare_clippy_lint! {
43     /// ### What it does
44     /// Checks for cases where generics are being used and multiple
45     /// syntax specifications for trait bounds are used simultaneously.
46     ///
47     /// ### Why is this bad?
48     /// Duplicate bounds makes the code
49     /// less readable than specifing them only once.
50     ///
51     /// ### Example
52     /// ```rust
53     /// fn func<T: Clone + Default>(arg: T) where T: Clone + Default {}
54     /// ```
55     ///
56     /// Could be written as:
57     ///
58     /// ```rust
59     /// fn func<T: Clone + Default>(arg: T) {}
60     /// ```
61     /// or
62     ///
63     /// ```rust
64     /// fn func<T>(arg: T) where T: Clone + Default {}
65     /// ```
66     #[clippy::version = "1.47.0"]
67     pub TRAIT_DUPLICATION_IN_BOUNDS,
68     pedantic,
69     "Check if the same trait bounds are specified twice during a function declaration"
70 }
71
72 #[derive(Copy, Clone)]
73 pub struct TraitBounds {
74     max_trait_bounds: u64,
75 }
76
77 impl TraitBounds {
78     #[must_use]
79     pub fn new(max_trait_bounds: u64) -> Self {
80         Self { max_trait_bounds }
81     }
82 }
83
84 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
85
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);
90     }
91
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_map = FxHashMap::default();
95
96         for predicate in where_clause.predicates {
97             if_chain! {
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();
102
103                 if let Some(
104                     Node::Item(
105                         Item {
106                             kind: ItemKind::Trait(_, _, _, self_bounds, _),
107                             .. }
108                         )
109                     ) = cx.tcx.hir().get_if_local(*def_id);
110                 then {
111                     if self_bounds_map.is_empty() {
112                         for bound in self_bounds.iter() {
113                             let Some((self_res, self_segments, _)) = get_trait_info_from_bound(bound) else { continue };
114                             self_bounds_map.insert(self_res, self_segments);
115                         }
116                     }
117
118                     bound_predicate
119                         .bounds
120                         .iter()
121                         .filter_map(get_trait_info_from_bound)
122                         .for_each(|(trait_item_res, trait_item_segments, span)| {
123                             if let Some(self_segments) = self_bounds_map.get(&trait_item_res) {
124                                 if SpanlessEq::new(cx).eq_path_segments(self_segments, trait_item_segments) {
125                                     span_lint_and_help(
126                                         cx,
127                                         TRAIT_DUPLICATION_IN_BOUNDS,
128                                         span,
129                                         "this trait bound is already specified in trait declaration",
130                                         None,
131                                         "consider removing this trait bound",
132                                     );
133                                 }
134                             }
135                         });
136                 }
137             }
138         }
139     }
140 }
141
142 impl TraitBounds {
143     fn check_type_repetition<'tcx>(self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
144         struct SpanlessTy<'cx, 'tcx> {
145             ty: &'tcx Ty<'tcx>,
146             cx: &'cx LateContext<'tcx>,
147         }
148         impl PartialEq for SpanlessTy<'_, '_> {
149             fn eq(&self, other: &Self) -> bool {
150                 let mut eq = SpanlessEq::new(self.cx);
151                 eq.inter_expr().eq_ty(self.ty, other.ty)
152             }
153         }
154         impl Hash for SpanlessTy<'_, '_> {
155             fn hash<H: Hasher>(&self, h: &mut H) {
156                 let mut t = SpanlessHash::new(self.cx);
157                 t.hash_ty(self.ty);
158                 h.write_u64(t.finish());
159             }
160         }
161         impl Eq for SpanlessTy<'_, '_> {}
162
163         if gen.span.from_expansion() {
164             return;
165         }
166         let mut map: UnhashMap<SpanlessTy<'_, '_>, Vec<&GenericBound<'_>>> = UnhashMap::default();
167         let mut applicability = Applicability::MaybeIncorrect;
168         for bound in gen.where_clause.predicates {
169             if_chain! {
170                 if let WherePredicate::BoundPredicate(ref p) = bound;
171                 if p.bounds.len() as u64 <= self.max_trait_bounds;
172                 if !p.span.from_expansion();
173                 if let Some(ref v) = map.insert(
174                     SpanlessTy { ty: p.bounded_ty, cx },
175                     p.bounds.iter().collect::<Vec<_>>()
176                 );
177
178                 then {
179                     let mut hint_string = format!(
180                         "consider combining the bounds: `{}:",
181                         snippet(cx, p.bounded_ty.span, "_")
182                     );
183                     for b in v.iter() {
184                         if let GenericBound::Trait(ref poly_trait_ref, _) = b {
185                             let path = &poly_trait_ref.trait_ref.path;
186                             hint_string.push_str(&format!(
187                                 " {} +",
188                                 snippet_with_applicability(cx, path.span, "..", &mut applicability)
189                             ));
190                         }
191                     }
192                     for b in p.bounds.iter() {
193                         if let GenericBound::Trait(ref poly_trait_ref, _) = b {
194                             let path = &poly_trait_ref.trait_ref.path;
195                             hint_string.push_str(&format!(
196                                 " {} +",
197                                 snippet_with_applicability(cx, path.span, "..", &mut applicability)
198                             ));
199                         }
200                     }
201                     hint_string.truncate(hint_string.len() - 2);
202                     hint_string.push('`');
203                     span_lint_and_help(
204                         cx,
205                         TYPE_REPETITION_IN_BOUNDS,
206                         p.span,
207                         "this type has already been used as a bound predicate",
208                         None,
209                         &hint_string,
210                     );
211                 }
212             }
213         }
214     }
215 }
216
217 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
218     if gen.span.from_expansion() || gen.params.is_empty() || gen.where_clause.predicates.is_empty() {
219         return;
220     }
221
222     let mut map = FxHashMap::default();
223     for param in gen.params {
224         if let ParamName::Plain(ref ident) = param.name {
225             let res = param
226                 .bounds
227                 .iter()
228                 .filter_map(get_trait_info_from_bound)
229                 .collect::<Vec<_>>();
230             map.insert(*ident, res);
231         }
232     }
233
234     for predicate in gen.where_clause.predicates {
235         if_chain! {
236             if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
237             if !bound_predicate.span.from_expansion();
238             if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
239             if let Some(segment) = segments.first();
240             if let Some(trait_resolutions_direct) = map.get(&segment.ident);
241             then {
242                 for (res_where, _,  _) in bound_predicate.bounds.iter().filter_map(get_trait_info_from_bound) {
243                     if let Some((_, _, span_direct)) = trait_resolutions_direct
244                                                 .iter()
245                                                 .find(|(res_direct, _, _)| *res_direct == res_where) {
246                         span_lint_and_help(
247                             cx,
248                             TRAIT_DUPLICATION_IN_BOUNDS,
249                             *span_direct,
250                             "this trait bound is already specified in the where clause",
251                             None,
252                             "consider removing this trait bound",
253                         );
254                     }
255                 }
256             }
257         }
258     }
259 }
260
261 fn get_trait_info_from_bound<'a>(bound: &'a GenericBound<'_>) -> Option<(Res, &'a [PathSegment<'a>], Span)> {
262     if let GenericBound::Trait(t, _) = bound {
263         Some((t.trait_ref.path.res, t.trait_ref.path.segments, t.span))
264     } else {
265         None
266     }
267 }