Skip to content
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

New lint: redundant_sort_by_key. #8212

Closed
pmnoxx opened this issue Jan 2, 2022 · 1 comment
Closed

New lint: redundant_sort_by_key. #8212

pmnoxx opened this issue Jan 2, 2022 · 1 comment
Labels
A-lint Area: New lints L-correctness Lint: Belongs in the correctness lint group

Comments

@pmnoxx
Copy link
Contributor

pmnoxx commented Jan 2, 2022

What it does

I saw an interesting bug today. Apparently the following code is valid.

[3,1,2].sort_by_key(|x|{x;}|);

The extra semicolon makes this function return (), which is valid, but this makes the sorting pointless.

Lint Name

useless_sort_by_key

Category

correctness

Advantage

  • This is likely a bug, and should be fixed. I had it happen to my code, once.
  • Or it can be just called redundant sort_by_key.

Drawbacks

  • I don't see any

Example

[3,1,2].sort_by_key(|x|{x;}|);

Could be written as:

That codes does nothing can be removed.
Or can be fixed, but it may be impossible to figure out what the user intended

[3,1,2].sort_by_key(|x|{x}|);

I think this should be marked as an potential error.

@pmnoxx pmnoxx added the A-lint Area: New lints label Jan 2, 2022
@pmnoxx pmnoxx changed the title sort_by_key with void lambda Likely a bug, when using sort_by_key with void lambda. Jan 2, 2022
@5225225
Copy link
Contributor

5225225 commented Jan 7, 2022

IMO this should apply to most/all _by_key methods.

So you'd be looking for all calls of a specific method with a signature like

fn max_by_key<B, F>(self, f: F) -> Option<Self::Item> where
    B: Ord,
    F: FnMut(&Self::Item) -> B, 

where B is ().

Though I suppose there may be legitimate use cases for a unit _by_key for some methods, so it might be a good idea to restrict it to just some types / be a bit smarter and let people explicitly return unit.

@pmnoxx pmnoxx changed the title Likely a bug, when using sort_by_key with void lambda. New link: redundant_sort_by_key. Jan 7, 2022
@pmnoxx pmnoxx changed the title New link: redundant_sort_by_key. New lint: redundant_sort_by_key. Jan 7, 2022
@camsteffen camsteffen added the L-correctness Lint: Belongs in the correctness lint group label Jan 12, 2022
@pmnoxx pmnoxx closed this as completed Mar 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints L-correctness Lint: Belongs in the correctness lint group
Projects
None yet
Development

No branches or pull requests

3 participants