Skip to content

Uplift clippy::for_loops_over_fallibles lint into rustc#99696

Merged
bors merged 19 commits intorust-lang:masterfrom
WaffleLapkin:uplift
Oct 10, 2022
Merged

Uplift clippy::for_loops_over_fallibles lint into rustc#99696
bors merged 19 commits intorust-lang:masterfrom
WaffleLapkin:uplift

Conversation

@WaffleLapkin
Copy link
Member

This PR, as the title suggests, uplifts clippy::for_loops_over_fallibles lint into rustc. This lint warns for code like this:

for _ in Some(1) {}
for _ in Ok::<_, ()>(1) {}

i.e. directly iterating over Option and Result using for loop.

There are a number of suggestions that this PR adds (on top of what clippy suggested):

  1. If the argument (? is there a better name for that expression) of a for loop is a .next() call, then we can suggest removing it (or rather replacing with .by_ref() to allow iterator being used later)
     for _ in iter.next() {}
     // turns into
     for _ in iter.by_ref() {}
  2. (otherwise) We can suggest using while let, this is useful for non-iterator, iterator-like things like [async] channels
    for _ in rx.recv() {}
    // turns into
    while let Some(_) = rx.recv() {}
  3. If the argument type is Result<impl IntoIterator, _> and the body has a Result<_, _> type, we can suggest using ?
    for _ in f() {}
    // turns into
    for _ in f()? {}
  4. To preserve the original behavior and clear intent, we can suggest using if let
    for _ in f() {}
    // turns into
    if let Some(_) = f() {}

(P.S. Some and Ok are interchangeable depending on the type)

I still feel that the lint wording/look is somewhat off, so I'll be happy to hear suggestions (on how to improve suggestions :D)!

Resolves #99272

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Uplift clippy::for_loops_over_fallibles to rustc