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