1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::source::{snippet, snippet_with_applicability};
3 use clippy_utils::{in_macro, SpanlessHash};
4 use if_chain::if_chain;
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_errors::Applicability;
7 use rustc_hir::{def::Res, GenericBound, Generics, ParamName, Path, QPath, TyKind, WherePredicate};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 declare_clippy_lint! {
13 /// **What it does:** This lint warns about unnecessary type repetitions in trait bounds
15 /// **Why is this bad?** Repeating the type for every bound makes the code
16 /// less readable than combining the bounds
18 /// **Known problems:** None.
22 /// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
25 /// Could be written as:
28 /// pub fn foo<T>(t: T) where T: Copy + Clone {}
30 pub TYPE_REPETITION_IN_BOUNDS,
32 "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
35 declare_clippy_lint! {
36 /// **What it does:** Checks for cases where generics are being used and multiple
37 /// syntax specifications for trait bounds are used simultaneously.
39 /// **Why is this bad?** Duplicate bounds makes the code
40 /// less readable than specifing them only once.
42 /// **Known problems:** None.
46 /// fn func<T: Clone + Default>(arg: T) where T: Clone + Default {}
49 /// Could be written as:
52 /// fn func<T: Clone + Default>(arg: T) {}
57 /// fn func<T>(arg: T) where T: Clone + Default {}
59 pub TRAIT_DUPLICATION_IN_BOUNDS,
61 "Check if the same trait bounds are specified twice during a function declaration"
64 #[derive(Copy, Clone)]
65 pub struct TraitBounds {
66 max_trait_bounds: u64,
71 pub fn new(max_trait_bounds: u64) -> Self {
72 Self { max_trait_bounds }
76 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
78 impl<'tcx> LateLintPass<'tcx> for TraitBounds {
79 fn check_generics(&mut self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
80 self.check_type_repetition(cx, gen);
81 check_trait_bound_duplication(cx, gen);
85 fn get_trait_res_span_from_bound(bound: &GenericBound<'_>) -> Option<(Res, Span)> {
86 if let GenericBound::Trait(t, _) = bound {
87 Some((t.trait_ref.path.res, t.span))
94 fn check_type_repetition(self, cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
95 if in_macro(gen.span) {
98 let hash = |ty| -> u64 {
99 let mut hasher = SpanlessHash::new(cx);
103 let mut map = FxHashMap::default();
104 let mut applicability = Applicability::MaybeIncorrect;
105 for bound in gen.where_clause.predicates {
107 if let WherePredicate::BoundPredicate(ref p) = bound;
108 if p.bounds.len() as u64 <= self.max_trait_bounds;
109 if !in_macro(p.span);
110 let h = hash(&p.bounded_ty);
111 if let Some(ref v) = map.insert(h, p.bounds.iter().collect::<Vec<_>>());
114 let mut hint_string = format!(
115 "consider combining the bounds: `{}:",
116 snippet(cx, p.bounded_ty.span, "_")
119 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
120 let path = &poly_trait_ref.trait_ref.path;
121 hint_string.push_str(&format!(
123 snippet_with_applicability(cx, path.span, "..", &mut applicability)
127 for b in p.bounds.iter() {
128 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
129 let path = &poly_trait_ref.trait_ref.path;
130 hint_string.push_str(&format!(
132 snippet_with_applicability(cx, path.span, "..", &mut applicability)
136 hint_string.truncate(hint_string.len() - 2);
137 hint_string.push('`');
140 TYPE_REPETITION_IN_BOUNDS,
142 "this type has already been used as a bound predicate",
152 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
153 if in_macro(gen.span) || gen.params.is_empty() || gen.where_clause.predicates.is_empty() {
157 let mut map = FxHashMap::default();
158 for param in gen.params {
159 if let ParamName::Plain(ref ident) = param.name {
163 .filter_map(get_trait_res_span_from_bound)
164 .collect::<Vec<_>>();
165 map.insert(*ident, res);
169 for predicate in gen.where_clause.predicates {
171 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
172 if !in_macro(bound_predicate.span);
173 if let TyKind::Path(QPath::Resolved(_, Path { ref segments, .. })) = bound_predicate.bounded_ty.kind;
174 if let Some(segment) = segments.first();
175 if let Some(trait_resolutions_direct) = map.get(&segment.ident);
177 for (res_where, _) in bound_predicate.bounds.iter().filter_map(get_trait_res_span_from_bound) {
178 if let Some((_, span_direct)) = trait_resolutions_direct
180 .find(|(res_direct, _)| *res_direct == res_where) {
183 TRAIT_DUPLICATION_IN_BOUNDS,
185 "this trait bound is already specified in the where clause",
187 "consider removing this trait bound",