Skip to content

Commit 0220b55

Browse files
committed
Add needless_maybe_sized lint
1 parent 3b5b2ed commit 0220b55

9 files changed

+789
-4
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4757,6 +4757,7 @@ Released 2018-09-13
47574757
[`needless_late_init`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_late_init
47584758
[`needless_lifetimes`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes
47594759
[`needless_match`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_match
4760+
[`needless_maybe_sized`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_maybe_sized
47604761
[`needless_option_as_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_option_as_deref
47614762
[`needless_option_take`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_option_take
47624763
[`needless_parens_on_range_literals`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_parens_on_range_literals

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -449,6 +449,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
449449
crate::needless_continue::NEEDLESS_CONTINUE_INFO,
450450
crate::needless_for_each::NEEDLESS_FOR_EACH_INFO,
451451
crate::needless_late_init::NEEDLESS_LATE_INIT_INFO,
452+
crate::needless_maybe_sized::NEEDLESS_MAYBE_SIZED_INFO,
452453
crate::needless_parens_on_range_literals::NEEDLESS_PARENS_ON_RANGE_LITERALS_INFO,
453454
crate::needless_pass_by_value::NEEDLESS_PASS_BY_VALUE_INFO,
454455
crate::needless_question_mark::NEEDLESS_QUESTION_MARK_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ mod needless_borrowed_ref;
218218
mod needless_continue;
219219
mod needless_for_each;
220220
mod needless_late_init;
221+
mod needless_maybe_sized;
221222
mod needless_parens_on_range_literals;
222223
mod needless_pass_by_value;
223224
mod needless_question_mark;
@@ -945,6 +946,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
945946
store.register_late_pass(|_| Box::new(no_mangle_with_rust_abi::NoMangleWithRustAbi));
946947
store.register_late_pass(|_| Box::new(collection_is_never_read::CollectionIsNeverRead));
947948
store.register_late_pass(|_| Box::new(missing_assert_message::MissingAssertMessage));
949+
store.register_late_pass(|_| Box::new(needless_maybe_sized::NeedlessMaybeSized));
948950
store.register_late_pass(|_| Box::new(redundant_async_block::RedundantAsyncBlock));
949951
store.register_late_pass(|_| Box::new(let_with_type_underscore::UnderscoreTyped));
950952
store.register_late_pass(|_| Box::new(allow_attributes::AllowAttribute));
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
use clippy_utils::diagnostics::span_lint_and_then;
2+
use rustc_errors::Applicability;
3+
use rustc_hir::def_id::{DefId, DefIdMap};
4+
use rustc_hir::{GenericBound, Generics, PolyTraitRef, TraitBoundModifier, WherePredicate};
5+
use rustc_lint::{LateContext, LateLintPass};
6+
use rustc_middle::ty::{Clause, ImplPolarity, PredicateKind};
7+
use rustc_session::{declare_lint_pass, declare_tool_lint};
8+
use rustc_span::symbol::Ident;
9+
use rustc_span::Span;
10+
11+
declare_clippy_lint! {
12+
/// ### What it does
13+
/// Lints `?Sized` bounds applied to type parameters that cannot be unsized
14+
///
15+
/// ### Why is this bad?
16+
/// The `?Sized` bound is misleading because it cannot be satisfied by an
17+
/// unsized type
18+
///
19+
/// ### Example
20+
/// ```rust
21+
/// // `T` cannot be unsized because `Clone` requires it to be `Sized`
22+
/// fn f<T: Clone + ?Sized>(t: &T) {}
23+
/// ```
24+
/// Use instead:
25+
/// ```rust
26+
/// fn f<T: Clone>(t: &T) {}
27+
///
28+
/// // or choose alternative bounds for `T` so that it can be unsized
29+
/// ```
30+
#[clippy::version = "1.70.0"]
31+
pub NEEDLESS_MAYBE_SIZED,
32+
suspicious,
33+
"a `?Sized` bound that is unusable due to a `Sized` requirement"
34+
}
35+
declare_lint_pass!(NeedlessMaybeSized => [NEEDLESS_MAYBE_SIZED]);
36+
37+
struct Bound<'tcx> {
38+
/// The [`DefId`] of the type parameter the bound refers to
39+
param: DefId,
40+
ident: Ident,
41+
42+
trait_bound: &'tcx PolyTraitRef<'tcx>,
43+
modifier: TraitBoundModifier,
44+
45+
predicate_pos: usize,
46+
bound_pos: usize,
47+
}
48+
49+
/// Finds all of the [`Bound`]s that refer to a type parameter and are not from a macro expansion
50+
fn type_param_bounds<'tcx>(generics: &'tcx Generics<'tcx>) -> impl Iterator<Item = Bound<'tcx>> {
51+
generics
52+
.predicates
53+
.iter()
54+
.enumerate()
55+
.filter_map(|(predicate_pos, predicate)| {
56+
let WherePredicate::BoundPredicate(bound_predicate) = predicate else {
57+
return None
58+
};
59+
60+
let (param, ident) = bound_predicate.bounded_ty.as_generic_param()?;
61+
62+
Some(
63+
bound_predicate
64+
.bounds
65+
.iter()
66+
.enumerate()
67+
.filter_map(move |(bound_pos, bound)| match bound {
68+
&GenericBound::Trait(ref trait_bound, modifier) => Some(Bound {
69+
param,
70+
ident,
71+
trait_bound,
72+
modifier,
73+
predicate_pos,
74+
bound_pos,
75+
}),
76+
_ => None,
77+
})
78+
.filter(|bound| !bound.trait_bound.span.from_expansion()),
79+
)
80+
})
81+
.flatten()
82+
}
83+
84+
/// Searches the supertraits of the trait referred to by `trait_bound` recursively, returning the
85+
/// path taken to find a `Sized` bound if one is found
86+
fn path_to_sized_bound(cx: &LateContext<'_>, trait_bound: &PolyTraitRef<'_>) -> Option<Vec<(Span, DefId)>> {
87+
fn search(cx: &LateContext<'_>, path: &mut Vec<(Span, DefId)>) -> bool {
88+
let &(_, trait_def_id) = path.last().unwrap();
89+
90+
if Some(trait_def_id) == cx.tcx.lang_items().sized_trait() {
91+
return true;
92+
}
93+
94+
for &(predicate, span) in cx.tcx.super_predicates_of(trait_def_id).predicates {
95+
if let PredicateKind::Clause(Clause::Trait(trait_predicate)) = predicate.kind().skip_binder()
96+
&& trait_predicate.polarity == ImplPolarity::Positive
97+
&& !path.contains(&(span, trait_predicate.def_id()))
98+
{
99+
path.push((span, trait_predicate.def_id()));
100+
if search(cx, path) {
101+
return true;
102+
}
103+
path.pop();
104+
}
105+
}
106+
107+
false
108+
}
109+
110+
let mut path = vec![(trait_bound.span, trait_bound.trait_ref.trait_def_id()?)];
111+
search(cx, &mut path).then_some(path)
112+
}
113+
114+
impl LateLintPass<'_> for NeedlessMaybeSized {
115+
fn check_generics(&mut self, cx: &LateContext<'_>, generics: &Generics<'_>) {
116+
let Some(sized_trait) = cx.tcx.lang_items().sized_trait() else { return };
117+
118+
let maybe_sized_params: DefIdMap<_> = type_param_bounds(generics)
119+
.filter(|bound| {
120+
bound.trait_bound.trait_ref.trait_def_id() == Some(sized_trait)
121+
&& bound.modifier == TraitBoundModifier::Maybe
122+
})
123+
.map(|bound| (bound.param, bound))
124+
.collect();
125+
126+
for bound in type_param_bounds(generics) {
127+
if bound.modifier == TraitBoundModifier::None
128+
&& let Some(sized_bound) = maybe_sized_params.get(&bound.param)
129+
&& let Some(path) = path_to_sized_bound(cx, bound.trait_bound)
130+
{
131+
span_lint_and_then(
132+
cx,
133+
NEEDLESS_MAYBE_SIZED,
134+
sized_bound.trait_bound.span,
135+
"`?Sized` bound is ignored because of a `Sized` requirement",
136+
|diag| {
137+
let Some(&(span, _)) = path.first() else { return };
138+
139+
let ty_param = sized_bound.ident;
140+
diag.span_note(span, format!("`{ty_param}` cannot be unsized because of the bound"));
141+
142+
for &[(_, current_id), (span, next_id)] in path.array_windows() {
143+
let current = cx.tcx.item_name(current_id);
144+
let next = cx.tcx.item_name(next_id);
145+
diag.span_note(span, format!("...because `{current}` has the bound `{next}`"));
146+
}
147+
148+
diag.span_suggestion_verbose(
149+
generics.span_for_bound_removal(sized_bound.predicate_pos, sized_bound.bound_pos),
150+
"change the bounds that require `Sized`, or remove the `?Sized` bound",
151+
"",
152+
Applicability::MaybeIncorrect,
153+
);
154+
},
155+
);
156+
}
157+
}
158+
}
159+
}

tests/ui/auxiliary/proc_macros.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ fn group_with_span(delimiter: Delimiter, stream: TokenStream, span: Span) -> Gro
6464
const ESCAPE_CHAR: char = '$';
6565

6666
/// Takes a single token followed by a sequence of tokens. Returns the sequence of tokens with their
67-
/// span set to that of the first token. Tokens may be escaped with either `#ident` or `#(tokens)`.
67+
/// span set to that of the first token. Tokens may be escaped with either `$ident` or `$(tokens)`.
6868
#[proc_macro]
6969
pub fn with_span(input: TokenStream) -> TokenStream {
7070
let mut iter = input.into_iter();
@@ -78,7 +78,7 @@ pub fn with_span(input: TokenStream) -> TokenStream {
7878
}
7979

8080
/// Takes a sequence of tokens and return the tokens with the span set such that they appear to be
81-
/// from an external macro. Tokens may be escaped with either `#ident` or `#(tokens)`.
81+
/// from an external macro. Tokens may be escaped with either `$ident` or `$(tokens)`.
8282
#[proc_macro]
8383
pub fn external(input: TokenStream) -> TokenStream {
8484
let mut res = TokenStream::new();
@@ -90,7 +90,7 @@ pub fn external(input: TokenStream) -> TokenStream {
9090
}
9191

9292
/// Copies all the tokens, replacing all their spans with the given span. Tokens can be escaped
93-
/// either by `#ident` or `#(tokens)`.
93+
/// either by `$ident` or `$(tokens)`.
9494
fn write_with_span(s: Span, mut input: IntoIter, out: &mut TokenStream) -> Result<()> {
9595
while let Some(tt) = input.next() {
9696
match tt {

tests/ui/needless_maybe_sized.fixed

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
// run-rustfix
2+
// aux-build:proc_macros.rs
3+
4+
#![allow(unused)]
5+
#![warn(clippy::needless_maybe_sized)]
6+
7+
extern crate proc_macros;
8+
use proc_macros::external;
9+
10+
fn directly<T: Sized>(t: &T) {}
11+
12+
trait A: Sized {}
13+
trait B: A {}
14+
15+
fn depth_1<T: A>(t: &T) {}
16+
fn depth_2<T: B>(t: &T) {}
17+
18+
// We only need to show one
19+
fn multiple_paths<T: A + B>(t: &T) {}
20+
21+
fn in_where<T>(t: &T)
22+
where
23+
T: Sized,
24+
{
25+
}
26+
27+
fn mixed_1<T: Sized>(t: &T)
28+
29+
{
30+
}
31+
32+
fn mixed_2<T>(t: &T)
33+
where
34+
T: Sized,
35+
{
36+
}
37+
38+
fn mixed_3<T>(t: &T)
39+
where
40+
T: Sized,
41+
{
42+
}
43+
44+
struct Struct<T: Sized>(T);
45+
46+
impl<T: Sized> Struct<T> {
47+
fn method<U: Sized>(&self) {}
48+
}
49+
50+
enum Enum<T: Sized + 'static> {
51+
Variant(&'static T),
52+
}
53+
54+
union Union<'a, T: Sized> {
55+
a: &'a T,
56+
}
57+
58+
trait Trait<T: Sized> {
59+
fn trait_method<U: Sized>() {}
60+
61+
type GAT<U: Sized>;
62+
63+
type Assoc: Sized + ?Sized; // False negative
64+
}
65+
66+
trait SecondInTrait: Send + Sized {}
67+
fn second_in_trait<T: SecondInTrait>() {}
68+
69+
fn impl_trait(_: &(impl Sized)) {}
70+
71+
trait GenericTrait<T>: Sized {}
72+
fn in_generic_trait<T: GenericTrait<U>, U>() {}
73+
74+
mod larger_graph {
75+
// C1 C2 Sized
76+
// \ /\ /
77+
// B1 B2
78+
// \ /
79+
// A1
80+
81+
trait C1 {}
82+
trait C2 {}
83+
trait B1: C1 + C2 {}
84+
trait B2: C2 + Sized {}
85+
trait A1: B1 + B2 {}
86+
87+
fn larger_graph<T: A1>() {}
88+
}
89+
90+
// Should not lint
91+
92+
fn sized<T: Sized>() {}
93+
fn maybe_sized<T: ?Sized>() {}
94+
95+
struct SeparateBounds<T: ?Sized>(T);
96+
impl<T: Sized> SeparateBounds<T> {}
97+
98+
trait P {}
99+
trait Q: P {}
100+
101+
fn ok_depth_1<T: P + ?Sized>() {}
102+
fn ok_depth_2<T: Q + ?Sized>() {}
103+
104+
external! {
105+
fn in_macro<T: Clone + ?Sized>(t: &T) {}
106+
107+
fn with_local_clone<T: $Clone + ?Sized>(t: &T) {}
108+
}
109+
110+
#[derive(Clone)]
111+
struct InDerive<T: ?Sized> {
112+
t: T,
113+
}
114+
115+
struct Refined<T: ?Sized>(T);
116+
impl<T: Sized> Refined<T> {}
117+
118+
fn main() {}

0 commit comments

Comments
 (0)