Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 42bd6d7

Browse files
committed
new lint: implied_bounds_in_impl
1 parent 4932d05 commit 42bd6d7

File tree

6 files changed

+161
-0
lines changed

6 files changed

+161
-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_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#implied_bounds_in_impl
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_impl::IMPLIED_BOUNDS_IN_IMPL_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: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
use clippy_utils::diagnostics::span_lint;
2+
use rustc_hir::def_id::LocalDefId;
3+
use rustc_hir::intravisit::FnKind;
4+
use rustc_hir::{Body, FnDecl, FnRetTy, GenericArgs, GenericBound, ItemKind, TraitBoundModifier, TyKind};
5+
use rustc_lint::{LateContext, LateLintPass};
6+
use rustc_middle::ty::ClauseKind;
7+
use rustc_session::{declare_lint_pass, declare_tool_lint};
8+
use rustc_span::Span;
9+
10+
declare_clippy_lint! {
11+
/// ### What it does
12+
/// Looks for bounds in `impl Trait` in return position that are implied by other bounds.
13+
/// This is usually the case when a supertrait is explicitly specified, when it is already implied
14+
/// by a subtrait (e.g. `DerefMut: Deref`, so specifying `Deref` is unnecessary when `DerefMut` is specified).
15+
///
16+
/// ### Why is this bad?
17+
/// Unnecessary complexity.
18+
///
19+
/// ### Known problems
20+
/// This lint currently does not work with generic traits (i.e. will not lint even if redundant).
21+
///
22+
/// ### Example
23+
/// ```rust
24+
/// fn f() -> impl Deref<Target = i32> + DerefMut<Target = i32> {
25+
/// // ^^^^^^^^^^^^^^^^^^^ unnecessary bound, already implied by the `DerefMut` trait bound
26+
/// Box::new(123)
27+
/// }
28+
/// ```
29+
/// Use instead:
30+
/// ```rust
31+
/// fn f() -> impl DerefMut<Target = i32> {
32+
/// Box::new(123)
33+
/// }
34+
/// ```
35+
#[clippy::version = "1.73.0"]
36+
pub IMPLIED_BOUNDS_IN_IMPL,
37+
complexity,
38+
"specifying bounds that are implied by other bounds in `impl Trait` type"
39+
}
40+
declare_lint_pass!(ImpliedBoundsInImpl => [IMPLIED_BOUNDS_IN_IMPL]);
41+
42+
impl LateLintPass<'_> for ImpliedBoundsInImpl {
43+
fn check_fn(
44+
&mut self,
45+
cx: &LateContext<'_>,
46+
_: FnKind<'_>,
47+
decl: &FnDecl<'_>,
48+
_: &Body<'_>,
49+
_: Span,
50+
_: LocalDefId,
51+
) {
52+
if let FnRetTy::Return(ty) = decl.output {
53+
if let TyKind::OpaqueDef(item_id, ..) = ty.kind
54+
&& let item = cx.tcx.hir().item(item_id)
55+
&& let ItemKind::OpaqueTy(opaque_ty) = item.kind
56+
{
57+
// Get all `DefId`s of (implied) trait predicates in all the bounds.
58+
// For `impl Deref + DerefMut` this will contain [`Deref`].
59+
// The implied `Deref` comes from `DerefMut` because `trait DerefMut: Deref {}`.
60+
61+
// N.B. Generic args on trait bounds are currently ignored and (G)ATs are fine to disregard,
62+
// because they must be the same for all of its supertraits. Example:
63+
// `impl Deref<Target = i32> + DerefMut<Target = u32>` is not allowed.
64+
// `DerefMut::Target` needs to match `Deref::Target`
65+
let implied_bounds = opaque_ty.bounds.iter().flat_map(|bound| {
66+
if let GenericBound::Trait(poly_trait, TraitBoundModifier::None) = bound
67+
&& let [.., path] = poly_trait.trait_ref.path.segments
68+
&& poly_trait.bound_generic_params.is_empty()
69+
&& path.args.map_or(true, GenericArgs::is_empty)
70+
&& let Some(trait_def_id) = path.res.opt_def_id()
71+
{
72+
cx.tcx.implied_predicates_of(trait_def_id).predicates
73+
} else {
74+
&[]
75+
}
76+
}).collect::<Vec<_>>();
77+
78+
// Lint all bounds in the `impl Trait` type that are also in the `implied_bounds` vec.
79+
for bound in opaque_ty.bounds {
80+
if let GenericBound::Trait(poly_trait, TraitBoundModifier::None) = bound
81+
&& let Some(def_id) = poly_trait.trait_ref.path.res.opt_def_id()
82+
&& implied_bounds.iter().any(|(clause, _)| {
83+
if let ClauseKind::Trait(tr) = clause.kind().skip_binder() {
84+
tr.def_id() == def_id
85+
} else {
86+
false
87+
}
88+
})
89+
{
90+
span_lint(cx, IMPLIED_BOUNDS_IN_IMPL, poly_trait.span, "this bound is implied by another bound and can be removed");
91+
}
92+
}
93+
}
94+
}
95+
}
96+
}

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_impl;
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_impl::ImpliedBoundsInImpl));
11001102
// add lints here, do not remove this comment, it's used in `new_lint`
11011103
}
11021104

tests/ui/implied_bounds_in_impl.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#![warn(clippy::implied_bounds_in_impl)]
2+
#![allow(dead_code)]
3+
4+
use std::ops::{Deref, DerefMut};
5+
6+
trait Trait1<T> {}
7+
// T is intentionally at a different position in Trait2 than in Trait1,
8+
// since that also needs to be taken into account when making this lint work with generics
9+
trait Trait2<U, T>: Trait1<T> {}
10+
impl Trait1<i32> for () {}
11+
impl Trait1<String> for () {}
12+
impl Trait2<u32, i32> for () {}
13+
impl Trait2<u32, String> for () {}
14+
15+
// Deref implied by DerefMut
16+
fn deref_derefmut<T>(x: T) -> impl Deref<Target = T> + DerefMut<Target = T> {
17+
Box::new(x)
18+
}
19+
20+
// Note: no test for different associated types needed since that isn't allowed in the first place.
21+
// E.g. `-> impl Deref<Target = T> + DerefMut<Target = U>` is a compile error.
22+
23+
// DefIds of the traits match, but the generics do not, so it's *not* redundant.
24+
// `Trait2: Trait` holds, but not `Trait2<_, String>: Trait1<i32>`.
25+
// (Generic traits are currently not linted anyway but once/if ever implemented this should not
26+
// warn.)
27+
fn different_generics() -> impl Trait1<i32> + Trait2<u32, String> {
28+
/* () */
29+
}
30+
31+
trait NonGenericTrait1 {}
32+
trait NonGenericTrait2: NonGenericTrait1 {}
33+
impl NonGenericTrait1 for i32 {}
34+
impl NonGenericTrait2 for i32 {}
35+
36+
// Only one bound. Nothing to lint.
37+
fn normal1() -> impl NonGenericTrait1 {
38+
1
39+
}
40+
41+
fn normal2() -> impl NonGenericTrait1 + NonGenericTrait2 {
42+
1
43+
}
44+
45+
fn main() {}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error: this bound is implied by another bound and can be removed
2+
--> $DIR/implied_bounds_in_impl.rs:16:36
3+
|
4+
LL | fn deref_derefmut<T>(x: T) -> impl Deref<Target = T> + DerefMut<Target = T> {
5+
| ^^^^^^^^^^^^^^^^^
6+
|
7+
= note: `-D clippy::implied-bounds-in-impl` implied by `-D warnings`
8+
9+
error: this bound is implied by another bound and can be removed
10+
--> $DIR/implied_bounds_in_impl.rs:41:22
11+
|
12+
LL | fn normal2() -> impl NonGenericTrait1 + NonGenericTrait2 {
13+
| ^^^^^^^^^^^^^^^^
14+
15+
error: aborting due to 2 previous errors
16+

0 commit comments

Comments
 (0)