Skip to content

Warn on useless ?Sized anti-bound #10600

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
rileyshahar opened this issue Apr 6, 2023 · 0 comments · Fixed by #10632
Closed

Warn on useless ?Sized anti-bound #10600

rileyshahar opened this issue Apr 6, 2023 · 0 comments · Fixed by #10632
Assignees
Labels
A-lint Area: New lints

Comments

@rileyshahar
Copy link

rileyshahar commented Apr 6, 2023

What it does

Consider the following (admittedly silly) code:

fn id<T: Copy + ?Sized>(t: &T) -> &T {
    t
}

The author clearly meant for this method to work on unsized T, but the Copy bound implicitly implies Clone, which implies Sized, so the compiler will deduce that T is Sized. Right now, it compiles and passes clippy silently. Instead, clippy should warn that the ?Sized anti-bound is useless, and suggest removing one of the two bounds.

Here's a silly-but-slightly-less-so example:

unsafe fn deref<T: Copy + ?Sized>(ptr: *const T) -> T {
    *ptr
}

Here, someone might have this function without the ?Sized anti-bound (Copy is required to move out of the pointer), realize they want to call it with an unsized type, and modify it like so. (In my case, I was trying to construct an example of ?Sized and pointer dereferencing, and ended up surprised for a few minutes that this compiled.)

A similar case is #1463, i.e. bounds where one implies the other, for example T: Copy + Clone. That seems potentially less bad, because there's no issue with the code's intent; it's just an unnecessarily complex bound.

Lint Name

useless_anti_bound

Category

suspicious

Advantage

  • Clearer intent
  • Removes useless code

Drawbacks

None I can think of.

Example

fn id<T: Copy + ?Sized>(t: &T) -> &T {
    t
}

Could be written as:

fn id<T: Copy>(t: &T) -> &T {
    t
}
@rileyshahar rileyshahar added the A-lint Area: New lints label Apr 6, 2023
@Alexendoo Alexendoo self-assigned this Apr 9, 2023
bors added a commit that referenced this issue Apr 12, 2024
Add `needless_maybe_sized` lint

changelog: new lint: [`needless_maybe_sized`]

Closes #10600
@bors bors closed this as completed in 6cfd4ac Jun 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants