]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/trait_bounds.rs
Merge commit 'd7b5cbf065b88830ca519adcb73fad4c0d24b1c7' into clippyup
[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     /// Use instead:
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 specifying them only once.
50     ///
51     /// ### Example
52     /// ```rust
53     /// fn func<T: Clone + Default>(arg: T) where T: Clone + Default {}
54     /// ```
55     ///
56     /// Use instead:
57     /// ```rust
58     /// # mod hidden {
59     /// fn func<T: Clone + Default>(arg: T) {}
60     /// # }
61     ///
62     /// // or
63     ///
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 mut self_bounds_map = FxHashMap::default();
94
95         for predicate in item.generics.predicates {
96             if_chain! {
97                 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
98                 if bound_predicate.origin != PredicateOrigin::ImplTrait;
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 {
102                     res: Some(Res::SelfTy{ trait_: Some(def_id), alias_to: _ }), ..
103                 }) = segments.first();
104                 if let Some(
105                     Node::Item(
106                         Item {
107                             kind: ItemKind::Trait(_, _, _, self_bounds, _),
108                             .. }
109                         )
110                     ) = cx.tcx.hir().get_if_local(*def_id);
111                 then {
112                     if self_bounds_map.is_empty() {
113                         for bound in self_bounds.iter() {
114                             let Some((self_res, self_segments, _)) = get_trait_info_from_bound(bound) else { continue };
115                             self_bounds_map.insert(self_res, self_segments);
116                         }
117                     }
118
119                     bound_predicate
120                         .bounds
121                         .iter()
122                         .filter_map(get_trait_info_from_bound)
123                         .for_each(|(trait_item_res, trait_item_segments, span)| {
124                             if let Some(self_segments) = self_bounds_map.get(&trait_item_res) {
125                                 if SpanlessEq::new(cx).eq_path_segments(self_segments, trait_item_segments) {
126                                     span_lint_and_help(
127                                         cx,
128                                         TRAIT_DUPLICATION_IN_BOUNDS,
129                                         span,
130                                         "this trait bound is already specified in trait declaration",
131                                         None,
132                                         "consider removing this trait bound",
133                                     );
134                                 }
135                             }
136                         });
137                 }
138             }
139         }
140     }
141 }
142
143 impl TraitBounds {
144     fn check_type_repetition<'tcx>(self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
145         struct SpanlessTy<'cx, 'tcx> {
146             ty: &'tcx Ty<'tcx>,
147             cx: &'cx LateContext<'tcx>,
148         }
149         impl PartialEq for SpanlessTy<'_, '_> {
150             fn eq(&self, other: &Self) -> bool {
151                 let mut eq = SpanlessEq::new(self.cx);
152                 eq.inter_expr().eq_ty(self.ty, other.ty)
153             }
154         }
155         impl Hash for SpanlessTy<'_, '_> {
156             fn hash<H: Hasher>(&self, h: &mut H) {
157                 let mut t = SpanlessHash::new(self.cx);
158                 t.hash_ty(self.ty);
159                 h.write_u64(t.finish());
160             }
161         }
162         impl Eq for SpanlessTy<'_, '_> {}
163
164         if gen.span.from_expansion() {
165             return;
166         }
167         let mut map: UnhashMap<SpanlessTy<'_, '_>, Vec<&GenericBound<'_>>> = UnhashMap::default();
168         let mut applicability = Applicability::MaybeIncorrect;
169         for bound in gen.predicates {
170             if_chain! {
171                 if let WherePredicate::BoundPredicate(ref p) = bound;
172                 if p.origin != PredicateOrigin::ImplTrait;
173                 if p.bounds.len() as u64 <= self.max_trait_bounds;
174                 if !p.span.from_expansion();
175                 if let Some(ref v) = map.insert(
176                     SpanlessTy { ty: p.bounded_ty, cx },
177                     p.bounds.iter().collect::<Vec<_>>()
178                 );
179
180                 then {
181                     let mut hint_string = format!(
182                         "consider combining the bounds: `{}:",
183                         snippet(cx, p.bounded_ty.span, "_")
184                     );
185                     for b in v.iter() {
186                         if let GenericBound::Trait(ref poly_trait_ref, _) = b {
187                             let path = &poly_trait_ref.trait_ref.path;
188                             let _ = write!(hint_string,
189                                 " {} +",
190                                 snippet_with_applicability(cx, path.span, "..", &mut applicability)
191                             );
192                         }
193                     }
194                     for b in p.bounds.iter() {
195                         if let GenericBound::Trait(ref poly_trait_ref, _) = b {
196                             let path = &poly_trait_ref.trait_ref.path;
197                             let _ = write!(hint_string,
198                                 " {} +",
199                                 snippet_with_applicability(cx, path.span, "..", &mut applicability)
200                             );
201                         }
202                     }
203                     hint_string.truncate(hint_string.len() - 2);
204                     hint_string.push('`');
205                     span_lint_and_help(
206                         cx,
207                         TYPE_REPETITION_IN_BOUNDS,
208                         p.span,
209                         "this type has already been used as a bound predicate",
210                         None,
211                         &hint_string,
212                     );
213                 }
214             }
215         }
216     }
217 }
218
219 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
220     if gen.span.from_expansion() || gen.params.is_empty() || gen.predicates.is_empty() {
221         return;
222     }
223
224     let mut map = FxHashMap::<_, Vec<_>>::default();
225     for predicate in gen.predicates {
226         if_chain! {
227             if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
228             if bound_predicate.origin != PredicateOrigin::ImplTrait;
229             if !bound_predicate.span.from_expansion();
230             if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
231             if let Some(segment) = segments.first();
232             then {
233                 for (res_where, _, span_where) in bound_predicate.bounds.iter().filter_map(get_trait_info_from_bound) {
234                     let trait_resolutions_direct = map.entry(segment.ident).or_default();
235                     if let Some((_, span_direct)) = trait_resolutions_direct
236                                                 .iter()
237                                                 .find(|(res_direct, _)| *res_direct == res_where) {
238                         span_lint_and_help(
239                             cx,
240                             TRAIT_DUPLICATION_IN_BOUNDS,
241                             *span_direct,
242                             "this trait bound is already specified in the where clause",
243                             None,
244                             "consider removing this trait bound",
245                         );
246                     }
247                     else {
248                         trait_resolutions_direct.push((res_where, span_where));
249                     }
250                 }
251             }
252         }
253     }
254 }
255
256 fn get_trait_info_from_bound<'a>(bound: &'a GenericBound<'_>) -> Option<(Res, &'a [PathSegment<'a>], Span)> {
257     if let GenericBound::Trait(t, _) = bound {
258         Some((t.trait_ref.path.res, t.trait_ref.path.segments, t.span))
259     } else {
260         None
261     }
262 }