1 use crate::utils::{in_macro, span_lint_and_help, SpanlessHash};
2 use clippy_utils::source::{snippet, snippet_with_applicability};
3 use if_chain::if_chain;
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_errors::Applicability;
6 use rustc_hir::{def::Res, GenericBound, Generics, ParamName, Path, QPath, TyKind, WherePredicate};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
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
17 /// **Known problems:** None.
21 /// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
24 /// Could be written as:
27 /// pub fn foo<T>(t: T) where T: Copy + Clone {}
29 pub TYPE_REPETITION_IN_BOUNDS,
31 "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
34 declare_clippy_lint! {
35 /// **What it does:** Checks for cases where generics are being used and multiple
36 /// syntax specifications for trait bounds are used simultaneously.
38 /// **Why is this bad?** Duplicate bounds makes the code
39 /// less readable than specifing them only once.
41 /// **Known problems:** None.
45 /// fn func<T: Clone + Default>(arg: T) where T: Clone + Default {}
48 /// Could be written as:
51 /// fn func<T: Clone + Default>(arg: T) {}
56 /// fn func<T>(arg: T) where T: Clone + Default {}
58 pub TRAIT_DUPLICATION_IN_BOUNDS,
60 "Check if the same trait bounds are specified twice during a function declaration"
63 #[derive(Copy, Clone)]
64 pub struct TraitBounds {
65 max_trait_bounds: u64,
70 pub fn new(max_trait_bounds: u64) -> Self {
71 Self { max_trait_bounds }
75 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
77 impl<'tcx> LateLintPass<'tcx> for TraitBounds {
78 fn check_generics(&mut self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
79 self.check_type_repetition(cx, gen);
80 check_trait_bound_duplication(cx, gen);
84 fn get_trait_res_span_from_bound(bound: &GenericBound<'_>) -> Option<(Res, Span)> {
85 if let GenericBound::Trait(t, _) = bound {
86 Some((t.trait_ref.path.res, t.span))
93 fn check_type_repetition(self, cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
94 if in_macro(gen.span) {
97 let hash = |ty| -> u64 {
98 let mut hasher = SpanlessHash::new(cx);
102 let mut map = FxHashMap::default();
103 let mut applicability = Applicability::MaybeIncorrect;
104 for bound in gen.where_clause.predicates {
106 if let WherePredicate::BoundPredicate(ref p) = bound;
107 if p.bounds.len() as u64 <= self.max_trait_bounds;
108 if !in_macro(p.span);
109 let h = hash(&p.bounded_ty);
110 if let Some(ref v) = map.insert(h, p.bounds.iter().collect::<Vec<_>>());
113 let mut hint_string = format!(
114 "consider combining the bounds: `{}:",
115 snippet(cx, p.bounded_ty.span, "_")
118 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
119 let path = &poly_trait_ref.trait_ref.path;
120 hint_string.push_str(&format!(
122 snippet_with_applicability(cx, path.span, "..", &mut applicability)
126 for b in p.bounds.iter() {
127 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
128 let path = &poly_trait_ref.trait_ref.path;
129 hint_string.push_str(&format!(
131 snippet_with_applicability(cx, path.span, "..", &mut applicability)
135 hint_string.truncate(hint_string.len() - 2);
136 hint_string.push('`');
139 TYPE_REPETITION_IN_BOUNDS,
141 "this type has already been used as a bound predicate",
151 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
152 if in_macro(gen.span) || gen.params.is_empty() || gen.where_clause.predicates.is_empty() {
156 let mut map = FxHashMap::default();
157 for param in gen.params {
158 if let ParamName::Plain(ref ident) = param.name {
162 .filter_map(get_trait_res_span_from_bound)
163 .collect::<Vec<_>>();
164 map.insert(*ident, res);
168 for predicate in gen.where_clause.predicates {
170 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
171 if !in_macro(bound_predicate.span);
172 if let TyKind::Path(QPath::Resolved(_, Path { ref segments, .. })) = bound_predicate.bounded_ty.kind;
173 if let Some(segment) = segments.first();
174 if let Some(trait_resolutions_direct) = map.get(&segment.ident);
176 for (res_where, _) in bound_predicate.bounds.iter().filter_map(get_trait_res_span_from_bound) {
177 if let Some((_, span_direct)) = trait_resolutions_direct
179 .find(|(res_direct, _)| *res_direct == res_where) {
182 TRAIT_DUPLICATION_IN_BOUNDS,
184 "this trait bound is already specified in the where clause",
186 "consider removing this trait bound",