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