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_data_structures::unhash::UnhashMap;
7 use rustc_errors::Applicability;
8 use rustc_hir::{def::Res, GenericBound, Generics, ParamName, Path, QPath, TyKind, WherePredicate};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 declare_clippy_lint! {
15 /// This lint warns about unnecessary type repetitions in trait bounds
17 /// ### Why is this bad?
18 /// Repeating the type for every bound makes the code
19 /// less readable than combining the bounds
23 /// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
26 /// Could be written as:
29 /// pub fn foo<T>(t: T) where T: Copy + Clone {}
31 pub TYPE_REPETITION_IN_BOUNDS,
33 "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
36 declare_clippy_lint! {
38 /// Checks for cases where generics are being used and multiple
39 /// syntax specifications for trait bounds are used simultaneously.
41 /// ### Why is this bad?
42 /// Duplicate bounds makes the code
43 /// less readable than specifing them only once.
47 /// fn func<T: Clone + Default>(arg: T) where T: Clone + Default {}
50 /// Could be written as:
53 /// fn func<T: Clone + Default>(arg: T) {}
58 /// fn func<T>(arg: T) where T: Clone + Default {}
60 pub TRAIT_DUPLICATION_IN_BOUNDS,
62 "Check if the same trait bounds are specified twice during a function declaration"
65 #[derive(Copy, Clone)]
66 pub struct TraitBounds {
67 max_trait_bounds: u64,
72 pub fn new(max_trait_bounds: u64) -> Self {
73 Self { max_trait_bounds }
77 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
79 impl<'tcx> LateLintPass<'tcx> for TraitBounds {
80 fn check_generics(&mut self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
81 self.check_type_repetition(cx, gen);
82 check_trait_bound_duplication(cx, gen);
86 fn get_trait_res_span_from_bound(bound: &GenericBound<'_>) -> Option<(Res, Span)> {
87 if let GenericBound::Trait(t, _) = bound {
88 Some((t.trait_ref.path.res, t.span))
95 fn check_type_repetition(self, cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
96 if in_macro(gen.span) {
99 let hash = |ty| -> u64 {
100 let mut hasher = SpanlessHash::new(cx);
104 let mut map: UnhashMap<u64, Vec<&GenericBound<'_>>> = UnhashMap::default();
105 let mut applicability = Applicability::MaybeIncorrect;
106 for bound in gen.where_clause.predicates {
108 if let WherePredicate::BoundPredicate(ref p) = bound;
109 if p.bounds.len() as u64 <= self.max_trait_bounds;
110 if !in_macro(p.span);
111 let h = hash(p.bounded_ty);
112 if let Some(ref v) = map.insert(h, p.bounds.iter().collect::<Vec<_>>());
115 let mut hint_string = format!(
116 "consider combining the bounds: `{}:",
117 snippet(cx, p.bounded_ty.span, "_")
120 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
121 let path = &poly_trait_ref.trait_ref.path;
122 hint_string.push_str(&format!(
124 snippet_with_applicability(cx, path.span, "..", &mut applicability)
128 for b in p.bounds.iter() {
129 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
130 let path = &poly_trait_ref.trait_ref.path;
131 hint_string.push_str(&format!(
133 snippet_with_applicability(cx, path.span, "..", &mut applicability)
137 hint_string.truncate(hint_string.len() - 2);
138 hint_string.push('`');
141 TYPE_REPETITION_IN_BOUNDS,
143 "this type has already been used as a bound predicate",
153 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
154 if in_macro(gen.span) || gen.params.is_empty() || gen.where_clause.predicates.is_empty() {
158 let mut map = FxHashMap::default();
159 for param in gen.params {
160 if let ParamName::Plain(ref ident) = param.name {
164 .filter_map(get_trait_res_span_from_bound)
165 .collect::<Vec<_>>();
166 map.insert(*ident, res);
170 for predicate in gen.where_clause.predicates {
172 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
173 if !in_macro(bound_predicate.span);
174 if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
175 if let Some(segment) = segments.first();
176 if let Some(trait_resolutions_direct) = map.get(&segment.ident);
178 for (res_where, _) in bound_predicate.bounds.iter().filter_map(get_trait_res_span_from_bound) {
179 if let Some((_, span_direct)) = trait_resolutions_direct
181 .find(|(res_direct, _)| *res_direct == res_where) {
184 TRAIT_DUPLICATION_IN_BOUNDS,
186 "this trait bound is already specified in the where clause",
188 "consider removing this trait bound",