1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::source::{snippet, snippet_with_applicability};
3 use clippy_utils::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 #[clippy::version = "1.38.0"]
32 pub TYPE_REPETITION_IN_BOUNDS,
34 "Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
37 declare_clippy_lint! {
39 /// Checks for cases where generics are being used and multiple
40 /// syntax specifications for trait bounds are used simultaneously.
42 /// ### Why is this bad?
43 /// Duplicate bounds makes the code
44 /// less readable than specifing them only once.
48 /// fn func<T: Clone + Default>(arg: T) where T: Clone + Default {}
51 /// Could be written as:
54 /// fn func<T: Clone + Default>(arg: T) {}
59 /// fn func<T>(arg: T) where T: Clone + Default {}
61 #[clippy::version = "1.47.0"]
62 pub TRAIT_DUPLICATION_IN_BOUNDS,
64 "Check if the same trait bounds are specified twice during a function declaration"
67 #[derive(Copy, Clone)]
68 pub struct TraitBounds {
69 max_trait_bounds: u64,
74 pub fn new(max_trait_bounds: u64) -> Self {
75 Self { max_trait_bounds }
79 impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS, TRAIT_DUPLICATION_IN_BOUNDS]);
81 impl<'tcx> LateLintPass<'tcx> for TraitBounds {
82 fn check_generics(&mut self, cx: &LateContext<'tcx>, gen: &'tcx Generics<'_>) {
83 self.check_type_repetition(cx, gen);
84 check_trait_bound_duplication(cx, gen);
88 fn get_trait_res_span_from_bound(bound: &GenericBound<'_>) -> Option<(Res, Span)> {
89 if let GenericBound::Trait(t, _) = bound {
90 Some((t.trait_ref.path.res, t.span))
97 fn check_type_repetition(self, cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
98 if gen.span.from_expansion() {
101 let hash = |ty| -> u64 {
102 let mut hasher = SpanlessHash::new(cx);
106 let mut map: UnhashMap<u64, Vec<&GenericBound<'_>>> = UnhashMap::default();
107 let mut applicability = Applicability::MaybeIncorrect;
108 for bound in gen.where_clause.predicates {
110 if let WherePredicate::BoundPredicate(ref p) = bound;
111 if p.bounds.len() as u64 <= self.max_trait_bounds;
112 if !p.span.from_expansion();
113 let h = hash(p.bounded_ty);
114 if let Some(ref v) = map.insert(h, p.bounds.iter().collect::<Vec<_>>());
117 let mut hint_string = format!(
118 "consider combining the bounds: `{}:",
119 snippet(cx, p.bounded_ty.span, "_")
122 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
123 let path = &poly_trait_ref.trait_ref.path;
124 hint_string.push_str(&format!(
126 snippet_with_applicability(cx, path.span, "..", &mut applicability)
130 for b in p.bounds.iter() {
131 if let GenericBound::Trait(ref poly_trait_ref, _) = b {
132 let path = &poly_trait_ref.trait_ref.path;
133 hint_string.push_str(&format!(
135 snippet_with_applicability(cx, path.span, "..", &mut applicability)
139 hint_string.truncate(hint_string.len() - 2);
140 hint_string.push('`');
143 TYPE_REPETITION_IN_BOUNDS,
145 "this type has already been used as a bound predicate",
155 fn check_trait_bound_duplication(cx: &LateContext<'_>, gen: &'_ Generics<'_>) {
156 if gen.span.from_expansion() || gen.params.is_empty() || gen.where_clause.predicates.is_empty() {
160 let mut map = FxHashMap::default();
161 for param in gen.params {
162 if let ParamName::Plain(ref ident) = param.name {
166 .filter_map(get_trait_res_span_from_bound)
167 .collect::<Vec<_>>();
168 map.insert(*ident, res);
172 for predicate in gen.where_clause.predicates {
174 if let WherePredicate::BoundPredicate(ref bound_predicate) = predicate;
175 if !bound_predicate.span.from_expansion();
176 if let TyKind::Path(QPath::Resolved(_, Path { segments, .. })) = bound_predicate.bounded_ty.kind;
177 if let Some(segment) = segments.first();
178 if let Some(trait_resolutions_direct) = map.get(&segment.ident);
180 for (res_where, _) in bound_predicate.bounds.iter().filter_map(get_trait_res_span_from_bound) {
181 if let Some((_, span_direct)) = trait_resolutions_direct
183 .find(|(res_direct, _)| *res_direct == res_where) {
186 TRAIT_DUPLICATION_IN_BOUNDS,
188 "this trait bound is already specified in the where clause",
190 "consider removing this trait bound",