rust-lang / rust-lang/rust-clippy

while_let_on_iterator should not trigger on borrowed iterators if the iterator is subsequently used.

Open
#7,659 12 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Lint name: while_let_on_iterator

I tried this code:

fn parse_value<V>(tokens: TokenStream) -> parse::Result<(ValueExpr<V>, TokenStream)>
where
    ValueExpr<V>: Parse,
{
    let mut it = tokens.into_iter();
    let mut value = TokenStream::new();
    while let Some(tt) = it.next() {
        if let TokenTree::Punct(p) = &tt {
            if p.as_char() == ',' {
                break;
            }
        }
        value.append(tt);
    }
    Ok((ValueExpr::parse.parse2(value)?, it.collect()))
}

I expected to see this happen:

This should not trigger the lint because the iterator is used again after the loop. The purpose of explicitly calling next() is to make it clear that the iterator may not be fully consumed in the loop and the remaining items can be processed elsewhere.

Instead, this happened: The lint triggers and tells me to use a for loop.

Meta

Rust version (rustc -Vv):

rustc 1.55.0 (c8dfcfe04 2021-09-06)
binary: rustc
commit-hash: c8dfcfe046a7680554bf4eb612bad840e7631c4b
commit-date: 2021-09-06
host: x86_64-apple-darwin
release: 1.55.0
LLVM version: 12.0.1

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the while_let_on_iterator lint and its tests, then reproduce the reported parse_value example with a borrowed iterator that is used after the loop. The fix is done when this case no longer triggers while ordinary fully consumed iterator cases retain the intended lint behavior, with regression coverage added.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools, tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.