Skip to content

Commit fff8e72

Browse files
committed
Auto merge of #5761 - ThibsG:TypeRepetitionThreshold, r=flip1995
Improvements for `type_repetition_in_bounds` lint Some improvements for `type_repetition_in_bounds`: - add a configurable threshold to trigger the lint (#4380). The lint won't trigger anymore if there are more bounds (strictly) than `conf.max_trait_bounds` on this type. - take generic args into account over bounded type (#4323) - don't lint for predicates generated in macros (#4326) Fixes #4380, Fixes #4323, Fixes #4326, Closes #3764 changelog: Fix multiple FPs in `type_repetition_in_bounds` and add a configuration option Note: the #3764 has already been fixed but not closed
2 parents c493090 + 2d5930a commit fff8e72

File tree

7 files changed

+107
-21
lines changed

7 files changed

+107
-21
lines changed

clippy_lints/src/lib.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -996,7 +996,8 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
996996
store.register_late_pass(|| box checked_conversions::CheckedConversions);
997997
store.register_late_pass(|| box integer_division::IntegerDivision);
998998
store.register_late_pass(|| box inherent_to_string::InherentToString);
999-
store.register_late_pass(|| box trait_bounds::TraitBounds);
999+
let max_trait_bounds = conf.max_trait_bounds;
1000+
store.register_late_pass(move || box trait_bounds::TraitBounds::new(max_trait_bounds));
10001001
store.register_late_pass(|| box comparison_chain::ComparisonChain);
10011002
store.register_late_pass(|| box mut_key::MutableKeyType);
10021003
store.register_late_pass(|| box modulo_arithmetic::ModuloArithmetic);
@@ -1033,7 +1034,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10331034
let array_size_threshold = conf.array_size_threshold;
10341035
store.register_late_pass(move || box large_stack_arrays::LargeStackArrays::new(array_size_threshold));
10351036
store.register_late_pass(move || box large_const_arrays::LargeConstArrays::new(array_size_threshold));
1036-
store.register_late_pass(move || box floating_point_arithmetic::FloatingPointArithmetic);
1037+
store.register_late_pass(|| box floating_point_arithmetic::FloatingPointArithmetic);
10371038
store.register_early_pass(|| box as_conversions::AsConversions);
10381039
store.register_early_pass(|| box utils::internal_lints::ProduceIce);
10391040
store.register_late_pass(|| box let_underscore::LetUnderscore);

clippy_lints/src/trait_bounds.rs

+22-5
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
11
use crate::utils::{in_macro, snippet, snippet_with_applicability, span_lint_and_help, SpanlessHash};
2+
use if_chain::if_chain;
23
use rustc_data_structures::fx::FxHashMap;
34
use rustc_errors::Applicability;
45
use rustc_hir::{GenericBound, Generics, WherePredicate};
56
use rustc_lint::{LateContext, LateLintPass};
67
use rustc_session::{declare_tool_lint, impl_lint_pass};
78

8-
#[derive(Copy, Clone)]
9-
pub struct TraitBounds;
10-
119
declare_clippy_lint! {
1210
/// **What it does:** This lint warns about unnecessary type repetitions in trait bounds
1311
///
1412
/// **Why is this bad?** Repeating the type for every bound makes the code
1513
/// less readable than combining the bounds
1614
///
15+
/// **Known problems:** None.
16+
///
1717
/// **Example:**
1818
/// ```rust
1919
/// pub fn foo<T>(t: T) where T: Copy, T: Clone {}
@@ -29,6 +29,18 @@ declare_clippy_lint! {
2929
"Types are repeated unnecessary in trait bounds use `+` instead of using `T: _, T: _`"
3030
}
3131

32+
#[derive(Copy, Clone)]
33+
pub struct TraitBounds {
34+
max_trait_bounds: u64,
35+
}
36+
37+
impl TraitBounds {
38+
#[must_use]
39+
pub fn new(max_trait_bounds: u64) -> Self {
40+
Self { max_trait_bounds }
41+
}
42+
}
43+
3244
impl_lint_pass!(TraitBounds => [TYPE_REPETITION_IN_BOUNDS]);
3345

3446
impl<'tcx> LateLintPass<'tcx> for TraitBounds {
@@ -44,9 +56,14 @@ impl<'tcx> LateLintPass<'tcx> for TraitBounds {
4456
let mut map = FxHashMap::default();
4557
let mut applicability = Applicability::MaybeIncorrect;
4658
for bound in gen.where_clause.predicates {
47-
if let WherePredicate::BoundPredicate(ref p) = bound {
59+
if_chain! {
60+
if let WherePredicate::BoundPredicate(ref p) = bound;
61+
if p.bounds.len() as u64 <= self.max_trait_bounds;
62+
if !in_macro(p.span);
4863
let h = hash(&p.bounded_ty);
49-
if let Some(ref v) = map.insert(h, p.bounds.iter().collect::<Vec<_>>()) {
64+
if let Some(ref v) = map.insert(h, p.bounds.iter().collect::<Vec<_>>());
65+
66+
then {
5067
let mut hint_string = format!(
5168
"consider combining the bounds: `{}:",
5269
snippet(cx, p.bounded_ty.span, "_")

clippy_lints/src/utils/conf.rs

+2
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,8 @@ define_Conf! {
156156
(array_size_threshold, "array_size_threshold": u64, 512_000),
157157
/// Lint: VEC_BOX. The size of the boxed type in bytes, where boxing in a `Vec` is allowed
158158
(vec_box_size_threshold, "vec_box_size_threshold": u64, 4096),
159+
/// Lint: TYPE_REPETITION_IN_BOUNDS. The maximum number of bounds a trait can have to be linted
160+
(max_trait_bounds, "max_trait_bounds": u64, 3),
159161
/// Lint: STRUCT_EXCESSIVE_BOOLS. The maximum number of bools a struct can have
160162
(max_struct_bools, "max_struct_bools": u64, 3),
161163
/// Lint: FN_PARAMS_EXCESSIVE_BOOLS. The maximum number of bools function parameters can have

clippy_lints/src/utils/hir_utils.rs

+12-7
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
703703
}
704704
for segment in path.segments {
705705
segment.ident.name.hash(&mut self.s);
706+
self.hash_generic_args(segment.generic_args().args);
706707
}
707708
},
708709
QPath::TypeRelative(ref ty, ref segment) => {
@@ -711,13 +712,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
711712
},
712713
},
713714
TyKind::OpaqueDef(_, arg_list) => {
714-
for arg in *arg_list {
715-
match arg {
716-
GenericArg::Lifetime(ref l) => self.hash_lifetime(l),
717-
GenericArg::Type(ref ty) => self.hash_ty(&ty),
718-
GenericArg::Const(ref ca) => self.hash_body(ca.value.body),
719-
}
720-
}
715+
self.hash_generic_args(arg_list);
721716
},
722717
TyKind::TraitObject(_, lifetime) => {
723718
self.hash_lifetime(lifetime);
@@ -735,4 +730,14 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
735730
self.hash_expr(&self.cx.tcx.hir().body(body_id).value);
736731
self.maybe_typeck_tables = old_maybe_typeck_tables;
737732
}
733+
734+
fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
735+
for arg in arg_list {
736+
match arg {
737+
GenericArg::Lifetime(ref l) => self.hash_lifetime(l),
738+
GenericArg::Type(ref ty) => self.hash_ty(&ty),
739+
GenericArg::Const(ref ca) => self.hash_body(ca.value.body),
740+
}
741+
}
742+
}
738743
}
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
error: error reading Clippy's configuration file `$DIR/clippy.toml`: unknown field `foobar`, expected one of `blacklisted-names`, `cognitive-complexity-threshold`, `cyclomatic-complexity-threshold`, `doc-valid-idents`, `too-many-arguments-threshold`, `type-complexity-threshold`, `single-char-binding-names-threshold`, `too-large-for-stack`, `enum-variant-name-threshold`, `enum-variant-size-threshold`, `verbose-bit-mask-threshold`, `literal-representation-threshold`, `trivial-copy-size-limit`, `too-many-lines-threshold`, `array-size-threshold`, `vec-box-size-threshold`, `max-struct-bools`, `max-fn-params-bools`, `warn-on-all-wildcard-imports`, `third-party` at line 5 column 1
1+
error: error reading Clippy's configuration file `$DIR/clippy.toml`: unknown field `foobar`, expected one of `blacklisted-names`, `cognitive-complexity-threshold`, `cyclomatic-complexity-threshold`, `doc-valid-idents`, `too-many-arguments-threshold`, `type-complexity-threshold`, `single-char-binding-names-threshold`, `too-large-for-stack`, `enum-variant-name-threshold`, `enum-variant-size-threshold`, `verbose-bit-mask-threshold`, `literal-representation-threshold`, `trivial-copy-size-limit`, `too-many-lines-threshold`, `array-size-threshold`, `vec-box-size-threshold`, `max-trait-bounds`, `max-struct-bools`, `max-fn-params-bools`, `warn-on-all-wildcard-imports`, `third-party` at line 5 column 1
22

33
error: aborting due to previous error
44

tests/ui/type_repetition_in_bounds.rs

+54-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
#[deny(clippy::type_repetition_in_bounds)]
1+
#![deny(clippy::type_repetition_in_bounds)]
2+
3+
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
24

35
pub fn foo<T>(_t: T)
46
where
@@ -16,4 +18,55 @@ where
1618
unimplemented!();
1719
}
1820

21+
// Threshold test (see #4380)
22+
trait LintBounds
23+
where
24+
Self: Clone,
25+
Self: Copy + Default + Ord,
26+
Self: Add<Output = Self> + AddAssign + Sub<Output = Self> + SubAssign,
27+
Self: Mul<Output = Self> + MulAssign + Div<Output = Self> + DivAssign,
28+
{
29+
}
30+
31+
trait LotsOfBounds
32+
where
33+
Self: Clone + Copy + Default + Ord,
34+
Self: Add<Output = Self> + AddAssign + Sub<Output = Self> + SubAssign,
35+
Self: Mul<Output = Self> + MulAssign + Div<Output = Self> + DivAssign,
36+
{
37+
}
38+
39+
// Generic distinction (see #4323)
40+
mod issue4323 {
41+
pub struct Foo<A>(A);
42+
pub struct Bar<A, B> {
43+
a: Foo<A>,
44+
b: Foo<B>,
45+
}
46+
47+
impl<A, B> Unpin for Bar<A, B>
48+
where
49+
Foo<A>: Unpin,
50+
Foo<B>: Unpin,
51+
{
52+
}
53+
}
54+
55+
// Extern macros shouldn't lint (see #4326)
56+
extern crate serde;
57+
mod issue4326 {
58+
use serde::{Deserialize, Serialize};
59+
60+
trait Foo {}
61+
impl Foo for String {}
62+
63+
#[derive(Debug, Serialize, Deserialize)]
64+
struct Bar<S>
65+
where
66+
S: Foo,
67+
{
68+
foo: S,
69+
}
70+
}
71+
1972
fn main() {}
+13-5
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,23 @@
11
error: this type has already been used as a bound predicate
2-
--> $DIR/type_repetition_in_bounds.rs:6:5
2+
--> $DIR/type_repetition_in_bounds.rs:8:5
33
|
44
LL | T: Clone,
55
| ^^^^^^^^
66
|
77
note: the lint level is defined here
8-
--> $DIR/type_repetition_in_bounds.rs:1:8
8+
--> $DIR/type_repetition_in_bounds.rs:1:9
99
|
10-
LL | #[deny(clippy::type_repetition_in_bounds)]
11-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
10+
LL | #![deny(clippy::type_repetition_in_bounds)]
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1212
= help: consider combining the bounds: `T: Copy + Clone`
1313

14-
error: aborting due to previous error
14+
error: this type has already been used as a bound predicate
15+
--> $DIR/type_repetition_in_bounds.rs:25:5
16+
|
17+
LL | Self: Copy + Default + Ord,
18+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
19+
|
20+
= help: consider combining the bounds: `Self: Clone + Copy + Default + Ord`
21+
22+
error: aborting due to 2 previous errors
1523

0 commit comments

Comments
 (0)