Skip to content

Commit df68b71

Browse files
committed
Auto merge of rust-lang#11362 - y21:superfluous_impl, r=xFrednet
new lint: `implied_bounds_in_impls` Closes rust-lang#10849 A new lint that looks for explicitly specified bounds that are already implied by other bounds in `impl Trait` return position types. One example, as shown in the linked example, would be ```rs fn foo<T>(x: T) -> impl Deref<Target = T> + DerefMut<Target = T> { Box::new(x) } ``` `DerefMut<Target = T>` requires `Deref<Target = T>` to be wellformed, so specifying `Deref` there is unnecessary. This currently "ignores" (i.e., does not lint at all) transitive supertrait bounds (e.g. `trait A {} trait B: A {} trait C: B {}`, then having an `impl A + C` type), because that seems a bit more difficult and I think this isn't technically a blocker. It leads to FNs, but shouldn't bring any FPs changelog: new lint [`implied_bounds_in_impls`]
2 parents 4932d05 + 1227571 commit df68b71

File tree

7 files changed

+465
-0
lines changed

7 files changed

+465
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4985,6 +4985,7 @@ Released 2018-09-13
49854985
[`implicit_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_return
49864986
[`implicit_saturating_add`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_saturating_add
49874987
[`implicit_saturating_sub`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_saturating_sub
4988+
[`implied_bounds_in_impls`]: https://rust-lang.github.io/rust-clippy/master/index.html#implied_bounds_in_impls
49884989
[`impossible_comparisons`]: https://rust-lang.github.io/rust-clippy/master/index.html#impossible_comparisons
49894990
[`imprecise_flops`]: https://rust-lang.github.io/rust-clippy/master/index.html#imprecise_flops
49904991
[`inconsistent_digit_grouping`]: https://rust-lang.github.io/rust-clippy/master/index.html#inconsistent_digit_grouping

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
209209
crate::implicit_return::IMPLICIT_RETURN_INFO,
210210
crate::implicit_saturating_add::IMPLICIT_SATURATING_ADD_INFO,
211211
crate::implicit_saturating_sub::IMPLICIT_SATURATING_SUB_INFO,
212+
crate::implied_bounds_in_impls::IMPLIED_BOUNDS_IN_IMPLS_INFO,
212213
crate::inconsistent_struct_constructor::INCONSISTENT_STRUCT_CONSTRUCTOR_INFO,
213214
crate::incorrect_impls::INCORRECT_CLONE_IMPL_ON_COPY_TYPE_INFO,
214215
crate::incorrect_impls::INCORRECT_PARTIAL_ORD_IMPL_ON_ORD_TYPE_INFO,
Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
use clippy_utils::diagnostics::span_lint_and_then;
2+
use clippy_utils::source::snippet;
3+
use rustc_errors::{Applicability, SuggestionStyle};
4+
use rustc_hir::def_id::LocalDefId;
5+
use rustc_hir::intravisit::FnKind;
6+
use rustc_hir::{
7+
Body, FnDecl, FnRetTy, GenericArg, GenericBound, ImplItem, ImplItemKind, ItemKind, TraitBoundModifier, TraitItem,
8+
TraitItemKind, TyKind,
9+
};
10+
use rustc_hir_analysis::hir_ty_to_ty;
11+
use rustc_lint::{LateContext, LateLintPass};
12+
use rustc_middle::ty::{self, ClauseKind, TyCtxt};
13+
use rustc_session::{declare_lint_pass, declare_tool_lint};
14+
use rustc_span::Span;
15+
16+
declare_clippy_lint! {
17+
/// ### What it does
18+
/// Looks for bounds in `impl Trait` in return position that are implied by other bounds.
19+
/// This can happen when a trait is specified that another trait already has as a supertrait
20+
/// (e.g. `fn() -> impl Deref + DerefMut<Target = i32>` has an unnecessary `Deref` bound,
21+
/// because `Deref` is a supertrait of `DerefMut`)
22+
///
23+
/// ### Why is this bad?
24+
/// Specifying more bounds than necessary adds needless complexity for the reader.
25+
///
26+
/// ### Limitations
27+
/// This lint does not check for implied bounds transitively. Meaning that
28+
/// it does't check for implied bounds from supertraits of supertraits
29+
/// (e.g. `trait A {} trait B: A {} trait C: B {}`, then having an `fn() -> impl A + C`)
30+
///
31+
/// ### Example
32+
/// ```rust
33+
/// # use std::ops::{Deref,DerefMut};
34+
/// fn f() -> impl Deref<Target = i32> + DerefMut<Target = i32> {
35+
/// // ^^^^^^^^^^^^^^^^^^^ unnecessary bound, already implied by the `DerefMut` trait bound
36+
/// Box::new(123)
37+
/// }
38+
/// ```
39+
/// Use instead:
40+
/// ```rust
41+
/// # use std::ops::{Deref,DerefMut};
42+
/// fn f() -> impl DerefMut<Target = i32> {
43+
/// Box::new(123)
44+
/// }
45+
/// ```
46+
#[clippy::version = "1.73.0"]
47+
pub IMPLIED_BOUNDS_IN_IMPLS,
48+
complexity,
49+
"specifying bounds that are implied by other bounds in `impl Trait` type"
50+
}
51+
declare_lint_pass!(ImpliedBoundsInImpls => [IMPLIED_BOUNDS_IN_IMPLS]);
52+
53+
/// This function tries to, for all type parameters in a supertype predicate `GenericTrait<U>`,
54+
/// check if the substituted type in the implied-by bound matches with what's subtituted in the
55+
/// implied type.
56+
///
57+
/// Consider this example.
58+
/// ```rust,ignore
59+
/// trait GenericTrait<T> {}
60+
/// trait GenericSubTrait<T, U, V>: GenericTrait<U> {}
61+
/// ^ trait_predicate_args: [Self#0, U#2]
62+
/// impl GenericTrait<i32> for () {}
63+
/// impl GenericSubTrait<(), i32, ()> for () {}
64+
/// impl GenericSubTrait<(), [u8; 8], ()> for () {}
65+
///
66+
/// fn f() -> impl GenericTrait<i32> + GenericSubTrait<(), [u8; 8], ()> {
67+
/// ^^^ implied_args ^^^^^^^^^^^^^^^ implied_by_args
68+
/// (we are interested in `[u8; 8]` specifically, as that
69+
/// is what `U` in `GenericTrait<U>` is substituted with)
70+
/// ()
71+
/// }
72+
/// ```
73+
/// Here i32 != [u8; 8], so this will return false.
74+
fn is_same_generics(
75+
tcx: TyCtxt<'_>,
76+
trait_predicate_args: &[ty::GenericArg<'_>],
77+
implied_by_args: &[GenericArg<'_>],
78+
implied_args: &[GenericArg<'_>],
79+
) -> bool {
80+
trait_predicate_args
81+
.iter()
82+
.enumerate()
83+
.skip(1) // skip `Self` implicit arg
84+
.all(|(arg_index, arg)| {
85+
if let Some(ty) = arg.as_type()
86+
&& let &ty::Param(ty::ParamTy{ index, .. }) = ty.kind()
87+
// Since `trait_predicate_args` and type params in traits start with `Self=0`
88+
// and generic argument lists `GenericTrait<i32>` don't have `Self`,
89+
// we need to subtract 1 from the index.
90+
&& let GenericArg::Type(ty_a) = implied_by_args[index as usize - 1]
91+
&& let GenericArg::Type(ty_b) = implied_args[arg_index - 1]
92+
{
93+
hir_ty_to_ty(tcx, ty_a) == hir_ty_to_ty(tcx, ty_b)
94+
} else {
95+
false
96+
}
97+
})
98+
}
99+
100+
fn check(cx: &LateContext<'_>, decl: &FnDecl<'_>) {
101+
if let FnRetTy::Return(ty) = decl.output
102+
&&let TyKind::OpaqueDef(item_id, ..) = ty.kind
103+
&& let item = cx.tcx.hir().item(item_id)
104+
&& let ItemKind::OpaqueTy(opaque_ty) = item.kind
105+
// Very often there is only a single bound, e.g. `impl Deref<..>`, in which case
106+
// we can avoid doing a bunch of stuff unnecessarily.
107+
&& opaque_ty.bounds.len() > 1
108+
{
109+
// Get all the (implied) trait predicates in the bounds.
110+
// For `impl Deref + DerefMut` this will contain [`Deref`].
111+
// The implied `Deref` comes from `DerefMut` because `trait DerefMut: Deref {}`.
112+
// N.B. (G)ATs are fine to disregard, because they must be the same for all of its supertraits.
113+
// Example:
114+
// `impl Deref<Target = i32> + DerefMut<Target = u32>` is not allowed.
115+
// `DerefMut::Target` needs to match `Deref::Target`.
116+
let implied_bounds: Vec<_> = opaque_ty.bounds.iter().filter_map(|bound| {
117+
if let GenericBound::Trait(poly_trait, TraitBoundModifier::None) = bound
118+
&& let [.., path] = poly_trait.trait_ref.path.segments
119+
&& poly_trait.bound_generic_params.is_empty()
120+
&& let Some(trait_def_id) = path.res.opt_def_id()
121+
&& let predicates = cx.tcx.super_predicates_of(trait_def_id).predicates
122+
&& !predicates.is_empty() // If the trait has no supertrait, there is nothing to add.
123+
{
124+
Some((bound.span(), path.args.map_or([].as_slice(), |a| a.args), predicates))
125+
} else {
126+
None
127+
}
128+
}).collect();
129+
130+
// Lint all bounds in the `impl Trait` type that are also in the `implied_bounds` vec.
131+
// This involves some extra logic when generic arguments are present, since
132+
// simply comparing trait `DefId`s won't be enough. We also need to compare the generics.
133+
for (index, bound) in opaque_ty.bounds.iter().enumerate() {
134+
if let GenericBound::Trait(poly_trait, TraitBoundModifier::None) = bound
135+
&& let [.., path] = poly_trait.trait_ref.path.segments
136+
&& let implied_args = path.args.map_or([].as_slice(), |a| a.args)
137+
&& let Some(def_id) = poly_trait.trait_ref.path.res.opt_def_id()
138+
&& let Some(implied_by_span) = implied_bounds.iter().find_map(|&(span, implied_by_args, preds)| {
139+
preds.iter().find_map(|(clause, _)| {
140+
if let ClauseKind::Trait(tr) = clause.kind().skip_binder()
141+
&& tr.def_id() == def_id
142+
&& is_same_generics(cx.tcx, tr.trait_ref.args, implied_by_args, implied_args)
143+
{
144+
Some(span)
145+
} else {
146+
None
147+
}
148+
})
149+
})
150+
{
151+
let implied_by = snippet(cx, implied_by_span, "..");
152+
span_lint_and_then(
153+
cx, IMPLIED_BOUNDS_IN_IMPLS,
154+
poly_trait.span,
155+
&format!("this bound is already specified as the supertrait of `{implied_by}`"),
156+
|diag| {
157+
// If we suggest removing a bound, we may also need extend the span
158+
// to include the `+` token, so we don't end up with something like `impl + B`
159+
160+
let implied_span_extended = if let Some(next_bound) = opaque_ty.bounds.get(index + 1) {
161+
poly_trait.span.to(next_bound.span().shrink_to_lo())
162+
} else {
163+
poly_trait.span
164+
};
165+
166+
diag.span_suggestion_with_style(
167+
implied_span_extended,
168+
"try removing this bound",
169+
"",
170+
Applicability::MachineApplicable,
171+
SuggestionStyle::ShowAlways
172+
);
173+
}
174+
);
175+
}
176+
}
177+
}
178+
}
179+
180+
impl LateLintPass<'_> for ImpliedBoundsInImpls {
181+
fn check_fn(
182+
&mut self,
183+
cx: &LateContext<'_>,
184+
_: FnKind<'_>,
185+
decl: &FnDecl<'_>,
186+
_: &Body<'_>,
187+
_: Span,
188+
_: LocalDefId,
189+
) {
190+
check(cx, decl);
191+
}
192+
fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) {
193+
if let TraitItemKind::Fn(sig, ..) = &item.kind {
194+
check(cx, sig.decl);
195+
}
196+
}
197+
fn check_impl_item(&mut self, cx: &LateContext<'_>, item: &ImplItem<'_>) {
198+
if let ImplItemKind::Fn(sig, ..) = &item.kind {
199+
check(cx, sig.decl);
200+
}
201+
}
202+
}

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ mod implicit_hasher;
152152
mod implicit_return;
153153
mod implicit_saturating_add;
154154
mod implicit_saturating_sub;
155+
mod implied_bounds_in_impls;
155156
mod inconsistent_struct_constructor;
156157
mod incorrect_impls;
157158
mod index_refutable_slice;
@@ -1097,6 +1098,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10971098
store.register_late_pass(|_| Box::new(redundant_locals::RedundantLocals));
10981099
store.register_late_pass(|_| Box::new(ignored_unit_patterns::IgnoredUnitPatterns));
10991100
store.register_late_pass(|_| Box::<reserve_after_initialization::ReserveAfterInitialization>::default());
1101+
store.register_late_pass(|_| Box::new(implied_bounds_in_impls::ImpliedBoundsInImpls));
11001102
// add lints here, do not remove this comment, it's used in `new_lint`
11011103
}
11021104

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#![warn(clippy::implied_bounds_in_impls)]
2+
#![allow(dead_code)]
3+
#![feature(return_position_impl_trait_in_trait)]
4+
5+
use std::ops::{Deref, DerefMut};
6+
7+
// Only one bound, nothing to lint.
8+
fn normal_deref<T>(x: T) -> impl Deref<Target = T> {
9+
Box::new(x)
10+
}
11+
12+
// Deref implied by DerefMut
13+
fn deref_derefmut<T>(x: T) -> impl DerefMut<Target = T> {
14+
Box::new(x)
15+
}
16+
17+
trait GenericTrait<T> {}
18+
trait GenericTrait2<V> {}
19+
// U is intentionally at a different "index" in GenericSubtrait than `T` is in GenericTrait,
20+
// so this can be a good test to make sure that the calculations are right (no off-by-one errors,
21+
// ...)
22+
trait GenericSubtrait<T, U, V>: GenericTrait<U> + GenericTrait2<V> {}
23+
24+
impl GenericTrait<i32> for () {}
25+
impl GenericTrait<i64> for () {}
26+
impl<V> GenericTrait2<V> for () {}
27+
impl<V> GenericSubtrait<(), i32, V> for () {}
28+
impl<V> GenericSubtrait<(), i64, V> for () {}
29+
30+
fn generics_implied<U, W>() -> impl GenericSubtrait<U, W, U>
31+
where
32+
(): GenericSubtrait<U, W, U>,
33+
{
34+
}
35+
36+
fn generics_implied_multi<V>() -> impl GenericSubtrait<(), i32, V> {}
37+
38+
fn generics_implied_multi2<T, V>() -> impl GenericSubtrait<(), T, V>
39+
where
40+
(): GenericSubtrait<(), T, V> + GenericTrait<T>,
41+
{
42+
}
43+
44+
// i32 != i64, GenericSubtrait<_, i64, _> does not imply GenericTrait<i32>, don't lint
45+
fn generics_different() -> impl GenericTrait<i32> + GenericSubtrait<(), i64, ()> {}
46+
47+
// i32 == i32, GenericSubtrait<_, i32, _> does imply GenericTrait<i32>, lint
48+
fn generics_same() -> impl GenericSubtrait<(), i32, ()> {}
49+
50+
trait SomeTrait {
51+
// Check that it works in trait declarations.
52+
fn f() -> impl DerefMut<Target = u8>;
53+
}
54+
struct SomeStruct;
55+
impl SomeStruct {
56+
// Check that it works in inherent impl blocks.
57+
fn f() -> impl DerefMut<Target = u8> {
58+
Box::new(123)
59+
}
60+
}
61+
impl SomeTrait for SomeStruct {
62+
// Check that it works in trait impls.
63+
fn f() -> impl DerefMut<Target = u8> {
64+
Box::new(42)
65+
}
66+
}
67+
68+
fn main() {}

tests/ui/implied_bounds_in_impls.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#![warn(clippy::implied_bounds_in_impls)]
2+
#![allow(dead_code)]
3+
#![feature(return_position_impl_trait_in_trait)]
4+
5+
use std::ops::{Deref, DerefMut};
6+
7+
// Only one bound, nothing to lint.
8+
fn normal_deref<T>(x: T) -> impl Deref<Target = T> {
9+
Box::new(x)
10+
}
11+
12+
// Deref implied by DerefMut
13+
fn deref_derefmut<T>(x: T) -> impl Deref<Target = T> + DerefMut<Target = T> {
14+
Box::new(x)
15+
}
16+
17+
trait GenericTrait<T> {}
18+
trait GenericTrait2<V> {}
19+
// U is intentionally at a different "index" in GenericSubtrait than `T` is in GenericTrait,
20+
// so this can be a good test to make sure that the calculations are right (no off-by-one errors,
21+
// ...)
22+
trait GenericSubtrait<T, U, V>: GenericTrait<U> + GenericTrait2<V> {}
23+
24+
impl GenericTrait<i32> for () {}
25+
impl GenericTrait<i64> for () {}
26+
impl<V> GenericTrait2<V> for () {}
27+
impl<V> GenericSubtrait<(), i32, V> for () {}
28+
impl<V> GenericSubtrait<(), i64, V> for () {}
29+
30+
fn generics_implied<U, W>() -> impl GenericTrait<W> + GenericSubtrait<U, W, U>
31+
where
32+
(): GenericSubtrait<U, W, U>,
33+
{
34+
}
35+
36+
fn generics_implied_multi<V>() -> impl GenericTrait<i32> + GenericTrait2<V> + GenericSubtrait<(), i32, V> {}
37+
38+
fn generics_implied_multi2<T, V>() -> impl GenericTrait<T> + GenericTrait2<V> + GenericSubtrait<(), T, V>
39+
where
40+
(): GenericSubtrait<(), T, V> + GenericTrait<T>,
41+
{
42+
}
43+
44+
// i32 != i64, GenericSubtrait<_, i64, _> does not imply GenericTrait<i32>, don't lint
45+
fn generics_different() -> impl GenericTrait<i32> + GenericSubtrait<(), i64, ()> {}
46+
47+
// i32 == i32, GenericSubtrait<_, i32, _> does imply GenericTrait<i32>, lint
48+
fn generics_same() -> impl GenericTrait<i32> + GenericSubtrait<(), i32, ()> {}
49+
50+
trait SomeTrait {
51+
// Check that it works in trait declarations.
52+
fn f() -> impl Deref + DerefMut<Target = u8>;
53+
}
54+
struct SomeStruct;
55+
impl SomeStruct {
56+
// Check that it works in inherent impl blocks.
57+
fn f() -> impl Deref + DerefMut<Target = u8> {
58+
Box::new(123)
59+
}
60+
}
61+
impl SomeTrait for SomeStruct {
62+
// Check that it works in trait impls.
63+
fn f() -> impl Deref + DerefMut<Target = u8> {
64+
Box::new(42)
65+
}
66+
}
67+
68+
fn main() {}

0 commit comments

Comments
 (0)