]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/trait_bounds.rs
Rollup merge of #90995 - the8472:hash-portability, r=dtolnay
[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::{in_macro, SpanlessHash};
4 use if_chain::if_chain;
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::unhash::UnhashMap;
7 use rustc_errors::Applicability;
8 use rustc_hir::{def::Res, GenericBound, Generics, ParamName, Path, QPath, TyKind, WherePredicate};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
11 use rustc_span::Span;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// This lint warns about unnecessary type repetitions in trait bounds
16     ///
17     /// ### Why is this bad?
18     /// Repeating the type for every bound makes the code
19     /// less readable than combining the bounds
20     ///
21     /// ### Example
22     /// ```rust
23     /// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
24     /// ```
25     ///
26     /// Could be written as:
27     ///
28     /// ```rust
29     /// pub fn foo<T>(t: T) where T: Copy + Clone {}
30     /// ```
31     pub TYPE_REPETITION_IN_BOUNDS,
32     pedantic,
33     "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
34 }
35
36 declare_clippy_lint! {
37     /// ### What it does
38     /// Checks for cases where generics are being used and multiple
39     /// syntax specifications for trait bounds are used simultaneously.
40     ///
41     /// ### Why is this bad?
42     /// Duplicate bounds makes the code
43     /// less readable than specifing them only once.
44     ///
45     /// ### Example
46     /// ```rust
47     /// fn func<T: Clone + Default>(arg: T) where T: Clone + Default {}
48     /// ```
49     ///
50     /// Could be written as:
51     ///
52     /// ```rust
53     /// fn func<T: Clone + Default>(arg: T) {}
54     /// ```
55     /// or
56     ///
57     /// ```rust
58     /// fn func<T>(arg: T) where T: Clone + Default {}
59     /// ```
60     pub TRAIT_DUPLICATION_IN_BOUNDS,
61     pedantic,
62     "Check if the same trait bounds are specified twice during a function declaration"
63 }
64
65 #[derive(Copy, Clone)]
66 pub struct TraitBounds {
67     max_trait_bounds: u64,
68 }
69
70 impl TraitBounds {
71     #[must_use]
72     pub fn new(max_trait_bounds: u64) -> Self {
73         Self { max_trait_bounds }
74     }
75 }
76
77 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
78
79 impl<'tcx> LateLintPass<'tcx> for TraitBounds {
80     fn check_generics(&mut self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
81         self.check_type_repetition(cx, gen);
82         check_trait_bound_duplication(cx, gen);
83     }
84 }
85
86 fn get_trait_res_span_from_bound(bound: &GenericBound<'_>) -> Option<(Res, Span)> {
87     if let GenericBound::Trait(t, _) = bound {
88         Some((t.trait_ref.path.res, t.span))
89     } else {
90         None
91     }
92 }
93
94 impl TraitBounds {
95     fn check_type_repetition(self, cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
96         if in_macro(gen.span) {
97             return;
98         }
99         let hash = |ty| -> u64 {
100             let mut hasher = SpanlessHash::new(cx);
101             hasher.hash_ty(ty);
102             hasher.finish()
103         };
104         let mut map: UnhashMap<u64, Vec<&GenericBound<'_>>> = UnhashMap::default();
105         let mut applicability = Applicability::MaybeIncorrect;
106         for bound in gen.where_clause.predicates {
107             if_chain! {
108                 if let WherePredicate::BoundPredicate(ref p) = bound;
109                 if p.bounds.len() as u64 <= self.max_trait_bounds;
110                 if !in_macro(p.span);
111                 let h = hash(p.bounded_ty);
112                 if let Some(ref v) = map.insert(h, p.bounds.iter().collect::<Vec<_>>());
113
114                 then {
115                     let mut hint_string = format!(
116                         "consider combining the bounds: `{}:",
117                         snippet(cx, p.bounded_ty.span, "_")
118                     );
119                     for b in v.iter() {
120                         if let GenericBound::Trait(ref poly_trait_ref, _) = b {
121                             let path = &poly_trait_ref.trait_ref.path;
122                             hint_string.push_str(&format!(
123                                 " {} +",
124                                 snippet_with_applicability(cx, path.span, "..", &mut applicability)
125                             ));
126                         }
127                     }
128                     for b in p.bounds.iter() {
129                         if let GenericBound::Trait(ref poly_trait_ref, _) = b {
130                             let path = &poly_trait_ref.trait_ref.path;
131                             hint_string.push_str(&format!(
132                                 " {} +",
133                                 snippet_with_applicability(cx, path.span, "..", &mut applicability)
134                             ));
135                         }
136                     }
137                     hint_string.truncate(hint_string.len() - 2);
138                     hint_string.push('`');
139                     span_lint_and_help(
140                         cx,
141                         TYPE_REPETITION_IN_BOUNDS,
142                         p.span,
143                         "this type has already been used as a bound predicate",
144                         None,
145                         &hint_string,
146                     );
147                 }
148             }
149         }
150     }
151 }
152
153 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
154     if in_macro(gen.span) || gen.params.is_empty() || gen.where_clause.predicates.is_empty() {
155         return;
156     }
157
158     let mut map = FxHashMap::default();
159     for param in gen.params {
160         if let ParamName::Plain(ref ident) = param.name {
161             let res = param
162                 .bounds
163                 .iter()
164                 .filter_map(get_trait_res_span_from_bound)
165                 .collect::<Vec<_>>();
166             map.insert(*ident, res);
167         }
168     }
169
170     for predicate in gen.where_clause.predicates {
171         if_chain! {
172             if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
173             if !in_macro(bound_predicate.span);
174             if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
175             if let Some(segment) = segments.first();
176             if let Some(trait_resolutions_direct) = map.get(&segment.ident);
177             then {
178                 for (res_where, _) in bound_predicate.bounds.iter().filter_map(get_trait_res_span_from_bound) {
179                     if let Some((_, span_direct)) = trait_resolutions_direct
180                                                 .iter()
181                                                 .find(|(res_direct, _)| *res_direct == res_where) {
182                         span_lint_and_help(
183                             cx,
184                             TRAIT_DUPLICATION_IN_BOUNDS,
185                             *span_direct,
186                             "this trait bound is already specified in the where clause",
187                             None,
188                             "consider removing this trait bound",
189                         );
190                     }
191                 }
192             }
193         }
194     }
195 }