]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/trait_bounds.rs
Lint for type repetition in trait bounds.
[rust.git] / clippy_lints / src / trait_bounds.rs
1 use crate::utils::{in_macro, span_help_and_lint, SpanlessHash};
2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc::hir::*;
6
7 declare_clippy_lint! {
8     pub TYPE_REPETITION_IN_BOUNDS,
9     complexity,
10     "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
11 }
12
13 #[derive(Copy, Clone)]
14 pub struct TraitBounds;
15
16 impl LintPass for TraitBounds {
17     fn get_lints(&self) -> LintArray {
18         lint_array!(TYPE_REPETITION_IN_BOUNDS)
19     }
20
21     fn name(&self) -> &'static str {
22         "TypeRepetitionInBounds"
23     }
24 }
25
26
27
28 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TraitBounds {
29     fn check_generics(&mut self, cx: &LateContext<'a, 'tcx>, gen: &'tcx Generics) {
30         if in_macro(gen.span) {
31             return;
32         }
33         let hash = | ty | -> u64 {
34             let mut hasher = SpanlessHash::new(cx, cx.tables);
35             hasher.hash_ty(ty);
36             hasher.finish()
37         };
38         let mut map = FxHashMap::default();
39         for bound in &gen.where_clause.predicates {
40             if let WherePredicate::BoundPredicate(ref p) = bound {
41                 let h = hash(&p.bounded_ty);
42                 if let Some(ref v) = map.insert(h, p.bounds) {
43                     let mut hint_string = format!("consider combining the bounds: `{:?}: ", p.bounded_ty);
44                     for &b in v.iter() {
45                         hint_string.push_str(&format!("{:?}, ", b));
46                     }
47                     for &b in p.bounds.iter() {
48                         hint_string.push_str(&format!("{:?}, ", b));
49                     }
50                     hint_string.truncate(hint_string.len() - 2);
51                     hint_string.push('`');
52                     span_help_and_lint(
53                         cx,
54                         TYPE_REPETITION_IN_BOUNDS,
55                         p.span,
56                         "this type has already been used as a bound predicate",
57                         &hint_string,
58                     );
59                 }
60             }
61         }
62     }
63 }