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