1 use crate::utils::{in_macro, snippet, span_help_and_lint, SpanlessHash};
3 use rustc::impl_lint_pass;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_session::declare_tool_lint;
9 pub struct TraitBounds;
11 declare_clippy_lint! {
12 /// **What it does:** This lint warns about unnecessary type repetitions in trait bounds
14 /// **Why is this bad?** Repeating the type for every bound makes the code
15 /// less readable than combining the bounds
19 /// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
22 /// Could be written as:
25 /// pub fn foo<T>(t: T) where T: Copy + Clone {}
27 pub TYPE_REPETITION_IN_BOUNDS,
29 "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
32 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS]);
34 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TraitBounds {
35 fn check_generics(&mut self, cx: &LateContext<'a, 'tcx>, gen: &'tcx Generics) {
36 if in_macro(gen.span) {
39 let hash = |ty| -> u64 {
40 let mut hasher = SpanlessHash::new(cx, cx.tables);
44 let mut map = FxHashMap::default();
45 for bound in &gen.where_clause.predicates {
46 if let WherePredicate::BoundPredicate(ref p) = bound {
47 let h = hash(&p.bounded_ty);
48 if let Some(ref v) = map.insert(h, p.bounds.iter().collect::<Vec<_>>()) {
49 let mut hint_string = format!(
50 "consider combining the bounds: `{}:",
51 snippet(cx, p.bounded_ty.span, "_")
54 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
55 let path = &poly_trait_ref.trait_ref.path;
56 hint_string.push_str(&format!(" {} +", path));
59 for b in p.bounds.iter() {
60 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
61 let path = &poly_trait_ref.trait_ref.path;
62 hint_string.push_str(&format!(" {} +", path));
65 hint_string.truncate(hint_string.len() - 2);
66 hint_string.push('`');
69 TYPE_REPETITION_IN_BOUNDS,
71 "this type has already been used as a bound predicate",