]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/trait_bounds.rs
Merge commit 'fdb84cbfd25908df5683f8f62388f663d9260e39' into clippyup
[rust.git] / clippy_lints / src / trait_bounds.rs
1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
2 use clippy_utils::source::{snippet, snippet_opt, snippet_with_applicability};
3 use clippy_utils::{SpanlessEq, SpanlessHash};
4 use core::hash::{Hash, Hasher};
5 use if_chain::if_chain;
6 use itertools::Itertools;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_data_structures::unhash::UnhashMap;
9 use rustc_errors::Applicability;
10 use rustc_hir::def::Res;
11 use rustc_hir::{
12     GenericArg, GenericBound, Generics, Item, ItemKind, Node, Path, PathSegment, PredicateOrigin, QPath,
13     TraitBoundModifier, TraitItem, TraitRef, Ty, TyKind, WherePredicate,
14 };
15 use rustc_lint::{LateContext, LateLintPass};
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::{BytePos, Span};
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     nursery,
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     ///
67     /// ```rust
68     /// fn foo<T: Default + Default>(bar: T) {}
69     /// ```
70     /// Use instead:
71     /// ```rust
72     /// fn foo<T: Default>(bar: T) {}
73     /// ```
74     ///
75     /// ```rust
76     /// fn foo<T>(bar: T) where T: Default + Default {}
77     /// ```
78     /// Use instead:
79     /// ```rust
80     /// fn foo<T>(bar: T) where T: Default {}
81     /// ```
82     #[clippy::version = "1.47.0"]
83     pub TRAIT_DUPLICATION_IN_BOUNDS,
84     nursery,
85     "check if the same trait bounds are specified more than once during a generic declaration"
86 }
87
88 #[derive(Copy, Clone)]
89 pub struct TraitBounds {
90     max_trait_bounds: u64,
91 }
92
93 impl TraitBounds {
94     #[must_use]
95     pub fn new(max_trait_bounds: u64) -> Self {
96         Self { max_trait_bounds }
97     }
98 }
99
100 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
101
102 impl<'tcx> LateLintPass<'tcx> for TraitBounds {
103     fn check_generics(&mut self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
104         self.check_type_repetition(cx, gen);
105         check_trait_bound_duplication(cx, gen);
106         check_bounds_or_where_duplication(cx, gen);
107     }
108
109     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
110         // special handling for self trait bounds as these are not considered generics
111         // ie. trait Foo: Display {}
112         if let Item {
113             kind: ItemKind::Trait(_, _, _, bounds, ..),
114             ..
115         } = item
116         {
117             rollup_traits(cx, bounds, "these bounds contain repeated elements");
118         }
119     }
120
121     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'tcx>) {
122         let mut self_bounds_map = FxHashMap::default();
123
124         for predicate in item.generics.predicates {
125             if_chain! {
126                 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
127                 if bound_predicate.origin != PredicateOrigin::ImplTrait;
128                 if !bound_predicate.span.from_expansion();
129                 if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
130                 if let Some(PathSegment {
131                     res: Some(Res::SelfTy{ trait_: Some(def_id), alias_to: _ }), ..
132                 }) = segments.first();
133                 if let Some(
134                     Node::Item(
135                         Item {
136                             kind: ItemKind::Trait(_, _, _, self_bounds, _),
137                             .. }
138                         )
139                     ) = cx.tcx.hir().get_if_local(*def_id);
140                 then {
141                     if self_bounds_map.is_empty() {
142                         for bound in self_bounds.iter() {
143                             let Some((self_res, self_segments, _)) = get_trait_info_from_bound(bound) else { continue };
144                             self_bounds_map.insert(self_res, self_segments);
145                         }
146                     }
147
148                     bound_predicate
149                         .bounds
150                         .iter()
151                         .filter_map(get_trait_info_from_bound)
152                         .for_each(|(trait_item_res, trait_item_segments, span)| {
153                             if let Some(self_segments) = self_bounds_map.get(&trait_item_res) {
154                                 if SpanlessEq::new(cx).eq_path_segments(self_segments, trait_item_segments) {
155                                     span_lint_and_help(
156                                         cx,
157                                         TRAIT_DUPLICATION_IN_BOUNDS,
158                                         span,
159                                         "this trait bound is already specified in trait declaration",
160                                         None,
161                                         "consider removing this trait bound",
162                                     );
163                                 }
164                             }
165                         });
166                 }
167             }
168         }
169     }
170 }
171
172 impl TraitBounds {
173     fn check_type_repetition<'tcx>(self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
174         struct SpanlessTy<'cx, 'tcx> {
175             ty: &'tcx Ty<'tcx>,
176             cx: &'cx LateContext<'tcx>,
177         }
178         impl PartialEq for SpanlessTy<'_, '_> {
179             fn eq(&self, other: &Self) -> bool {
180                 let mut eq = SpanlessEq::new(self.cx);
181                 eq.inter_expr().eq_ty(self.ty, other.ty)
182             }
183         }
184         impl Hash for SpanlessTy<'_, '_> {
185             fn hash<H: Hasher>(&self, h: &mut H) {
186                 let mut t = SpanlessHash::new(self.cx);
187                 t.hash_ty(self.ty);
188                 h.write_u64(t.finish());
189             }
190         }
191         impl Eq for SpanlessTy<'_, '_> {}
192
193         if gen.span.from_expansion() {
194             return;
195         }
196         let mut map: UnhashMap<SpanlessTy<'_, '_>, Vec<&GenericBound<'_>>> = UnhashMap::default();
197         let mut applicability = Applicability::MaybeIncorrect;
198         for bound in gen.predicates {
199             if_chain! {
200                 if let WherePredicate::BoundPredicate(ref p) = bound;
201                 if p.origin != PredicateOrigin::ImplTrait;
202                 if p.bounds.len() as u64 <= self.max_trait_bounds;
203                 if !p.span.from_expansion();
204                 if let Some(ref v) = map.insert(
205                     SpanlessTy { ty: p.bounded_ty, cx },
206                     p.bounds.iter().collect::<Vec<_>>()
207                 );
208
209                 then {
210                     let trait_bounds = v
211                         .iter()
212                         .copied()
213                         .chain(p.bounds.iter())
214                         .filter_map(get_trait_info_from_bound)
215                         .map(|(_, _, span)| snippet_with_applicability(cx, span, "..", &mut applicability))
216                         .join(" + ");
217                     let hint_string = format!(
218                         "consider combining the bounds: `{}: {}`",
219                         snippet(cx, p.bounded_ty.span, "_"),
220                         trait_bounds,
221                     );
222                     span_lint_and_help(
223                         cx,
224                         TYPE_REPETITION_IN_BOUNDS,
225                         p.span,
226                         "this type has already been used as a bound predicate",
227                         None,
228                         &hint_string,
229                     );
230                 }
231             }
232         }
233     }
234 }
235
236 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
237     if gen.span.from_expansion() || gen.params.is_empty() || gen.predicates.is_empty() {
238         return;
239     }
240
241     let mut map = FxHashMap::<_, Vec<_>>::default();
242     for predicate in gen.predicates {
243         if_chain! {
244             if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
245             if bound_predicate.origin != PredicateOrigin::ImplTrait;
246             if !bound_predicate.span.from_expansion();
247             if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
248             if let Some(segment) = segments.first();
249             then {
250                 for (res_where, _, span_where) in bound_predicate.bounds.iter().filter_map(get_trait_info_from_bound) {
251                     let trait_resolutions_direct = map.entry(segment.ident).or_default();
252                     if let Some((_, span_direct)) = trait_resolutions_direct
253                                                 .iter()
254                                                 .find(|(res_direct, _)| *res_direct == res_where) {
255                         span_lint_and_help(
256                             cx,
257                             TRAIT_DUPLICATION_IN_BOUNDS,
258                             *span_direct,
259                             "this trait bound is already specified in the where clause",
260                             None,
261                             "consider removing this trait bound",
262                         );
263                     }
264                     else {
265                         trait_resolutions_direct.push((res_where, span_where));
266                     }
267                 }
268             }
269         }
270     }
271 }
272
273 #[derive(PartialEq, Eq, Hash, Debug)]
274 struct ComparableTraitRef(Res, Vec<Res>);
275
276 fn check_bounds_or_where_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
277     if gen.span.from_expansion() {
278         return;
279     }
280
281     for predicate in gen.predicates {
282         if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate {
283             let msg = if predicate.in_where_clause() {
284                 "these where clauses contain repeated elements"
285             } else {
286                 "these bounds contain repeated elements"
287             };
288             rollup_traits(cx, bound_predicate.bounds, msg);
289         }
290     }
291 }
292
293 fn get_trait_info_from_bound<'a>(bound: &'a GenericBound<'_>) -> Option<(Res, &'a [PathSegment<'a>], Span)> {
294     if let GenericBound::Trait(t, tbm) = bound {
295         let trait_path = t.trait_ref.path;
296         let trait_span = {
297             let path_span = trait_path.span;
298             if let TraitBoundModifier::Maybe = tbm {
299                 path_span.with_lo(path_span.lo() - BytePos(1)) // include the `?`
300             } else {
301                 path_span
302             }
303         };
304         Some((trait_path.res, trait_path.segments, trait_span))
305     } else {
306         None
307     }
308 }
309
310 // FIXME: ComparableTraitRef does not support nested bounds needed for associated_type_bounds
311 fn into_comparable_trait_ref(trait_ref: &TraitRef<'_>) -> ComparableTraitRef {
312     ComparableTraitRef(
313         trait_ref.path.res,
314         trait_ref
315             .path
316             .segments
317             .iter()
318             .filter_map(|segment| {
319                 // get trait bound type arguments
320                 Some(segment.args?.args.iter().filter_map(|arg| {
321                     if_chain! {
322                         if let GenericArg::Type(ty) = arg;
323                         if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind;
324                         then { return Some(path.res) }
325                     }
326                     None
327                 }))
328             })
329             .flatten()
330             .collect(),
331     )
332 }
333
334 fn rollup_traits(cx: &LateContext<'_>, bounds: &[GenericBound<'_>], msg: &str) {
335     let mut map = FxHashMap::default();
336     let mut repeated_res = false;
337
338     let only_comparable_trait_refs = |bound: &GenericBound<'_>| {
339         if let GenericBound::Trait(t, _) = bound {
340             Some((into_comparable_trait_ref(&t.trait_ref), t.span))
341         } else {
342             None
343         }
344     };
345
346     for bound in bounds.iter().filter_map(only_comparable_trait_refs) {
347         let (comparable_bound, span_direct) = bound;
348         if map.insert(comparable_bound, span_direct).is_some() {
349             repeated_res = true;
350         }
351     }
352
353     if_chain! {
354         if repeated_res;
355         if let [first_trait, .., last_trait] = bounds;
356         then {
357             let all_trait_span = first_trait.span().to(last_trait.span());
358
359             let mut traits = map.values()
360                 .filter_map(|span| snippet_opt(cx, *span))
361                 .collect::<Vec<_>>();
362             traits.sort_unstable();
363             let traits = traits.join(" + ");
364
365             span_lint_and_sugg(
366                 cx,
367                 TRAIT_DUPLICATION_IN_BOUNDS,
368                 all_trait_span,
369                 msg,
370                 "try",
371                 traits,
372                 Applicability::MachineApplicable
373             );
374         }
375     }
376 }