1 use crate::utils::{in_macro, snippet, snippet_with_applicability, span_lint_and_help, SpanlessHash};
2 use rustc_data_structures::fx::FxHashMap;
3 use rustc_errors::Applicability;
4 use rustc_hir::{GenericBound, Generics, WherePredicate};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
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 let mut applicability = Applicability::MaybeIncorrect;
46 for bound in gen.where_clause.predicates {
47 if let WherePredicate::BoundPredicate(ref p) = bound {
48 let h = hash(&p.bounded_ty);
49 if let Some(ref v) = map.insert(h, p.bounds.iter().collect::<Vec<_>>()) {
50 let mut hint_string = format!(
51 "consider combining the bounds: `{}:",
52 snippet(cx, p.bounded_ty.span, "_")
55 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
56 let path = &poly_trait_ref.trait_ref.path;
57 hint_string.push_str(&format!(
59 snippet_with_applicability(cx, path.span, "..", &mut applicability)
63 for b in p.bounds.iter() {
64 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
65 let path = &poly_trait_ref.trait_ref.path;
66 hint_string.push_str(&format!(
68 snippet_with_applicability(cx, path.span, "..", &mut applicability)
72 hint_string.truncate(hint_string.len() - 2);
73 hint_string.push('`');
76 TYPE_REPETITION_IN_BOUNDS,
78 "this type has already been used as a bound predicate",