Skip to content

Commit 5b81677

Browse files
committed
Add needless_maybe_sized lint
1 parent b5bfd11 commit 5b81677

File tree

9 files changed

+789
-4
lines changed

9 files changed

+789
-4
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5089,6 +5089,7 @@ Released 2018-09-13
50895089
[`needless_late_init`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_late_init
50905090
[`needless_lifetimes`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes
50915091
[`needless_match`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_match
5092+
[`needless_maybe_sized`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_maybe_sized
50925093
[`needless_option_as_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_option_as_deref
50935094
[`needless_option_take`]: https://rust-lang.github.io/rust-clippy/master/index.html#needless_option_take
50945095
[`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
@@ -482,6 +482,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
482482
crate::needless_for_each::NEEDLESS_FOR_EACH_INFO,
483483
crate::needless_if::NEEDLESS_IF_INFO,
484484
crate::needless_late_init::NEEDLESS_LATE_INIT_INFO,
485+
crate::needless_maybe_sized::NEEDLESS_MAYBE_SIZED_INFO,
485486
crate::needless_parens_on_range_literals::NEEDLESS_PARENS_ON_RANGE_LITERALS_INFO,
486487
crate::needless_pass_by_ref_mut::NEEDLESS_PASS_BY_REF_MUT_INFO,
487488
crate::needless_pass_by_value::NEEDLESS_PASS_BY_VALUE_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,7 @@ mod needless_else;
232232
mod needless_for_each;
233233
mod needless_if;
234234
mod needless_late_init;
235+
mod needless_maybe_sized;
235236
mod needless_parens_on_range_literals;
236237
mod needless_pass_by_ref_mut;
237238
mod needless_pass_by_value;
@@ -1018,6 +1019,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10181019
store.register_late_pass(|_| Box::new(no_mangle_with_rust_abi::NoMangleWithRustAbi));
10191020
store.register_late_pass(|_| Box::new(collection_is_never_read::CollectionIsNeverRead));
10201021
store.register_late_pass(|_| Box::new(missing_assert_message::MissingAssertMessage));
1022+
store.register_late_pass(|_| Box::new(needless_maybe_sized::NeedlessMaybeSized));
10211023
store.register_late_pass(|_| Box::new(redundant_async_block::RedundantAsyncBlock));
10221024
store.register_late_pass(|_| Box::new(let_with_type_underscore::UnderscoreTyped));
10231025
store.register_late_pass(|_| Box::new(allow_attributes::AllowAttribute));
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
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::{ClauseKind, ImplPolarity};
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 ClauseKind::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 {
117+
return;
118+
};
119+
120+
let maybe_sized_params: DefIdMap<_> = type_param_bounds(generics)
121+
.filter(|bound| {
122+
bound.trait_bound.trait_ref.trait_def_id() == Some(sized_trait)
123+
&& bound.modifier == TraitBoundModifier::Maybe
124+
})
125+
.map(|bound| (bound.param, bound))
126+
.collect();
127+
128+
for bound in type_param_bounds(generics) {
129+
if bound.modifier == TraitBoundModifier::None
130+
&& let Some(sized_bound) = maybe_sized_params.get(&bound.param)
131+
&& let Some(path) = path_to_sized_bound(cx, bound.trait_bound)
132+
{
133+
span_lint_and_then(
134+
cx,
135+
NEEDLESS_MAYBE_SIZED,
136+
sized_bound.trait_bound.span,
137+
"`?Sized` bound is ignored because of a `Sized` requirement",
138+
|diag| {
139+
let Some(&(span, _)) = path.first() else { return };
140+
141+
let ty_param = sized_bound.ident;
142+
diag.span_note(span, format!("`{ty_param}` cannot be unsized because of the bound"));
143+
144+
for &[(_, current_id), (span, next_id)] in path.array_windows() {
145+
let current = cx.tcx.item_name(current_id);
146+
let next = cx.tcx.item_name(next_id);
147+
diag.span_note(span, format!("...because `{current}` has the bound `{next}`"));
148+
}
149+
150+
diag.span_suggestion_verbose(
151+
generics.span_for_bound_removal(sized_bound.predicate_pos, sized_bound.bound_pos),
152+
"change the bounds that require `Sized`, or remove the `?Sized` bound",
153+
"",
154+
Applicability::MaybeIncorrect,
155+
);
156+
},
157+
);
158+
}
159+
}
160+
}
161+
}

tests/ui/auxiliary/proc_macros.rs

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

5959
/// Takes a single token followed by a sequence of tokens. Returns the sequence of tokens with their
60-
/// span set to that of the first token. Tokens may be escaped with either `#ident` or `#(tokens)`.
60+
/// span set to that of the first token. Tokens may be escaped with either `$ident` or `$(tokens)`.
6161
#[proc_macro]
6262
pub fn with_span(input: TokenStream) -> TokenStream {
6363
let mut iter = input.into_iter();
@@ -71,7 +71,7 @@ pub fn with_span(input: TokenStream) -> TokenStream {
7171
}
7272

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

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

tests/ui/needless_maybe_sized.fixed

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

0 commit comments

Comments
 (0)