rust-lang / rust-lang/rust-analyzer

`convert_for_loop_with_for_each` does not take control flow in account

Open
#11,111 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-assists C-bug S-actionable
Dominant language
Rust
Stars
16.9k
Forks
2.2k
Avg merge
1d 12h
Merged PRs (30d)
72

Description

This assist apparently does not notice when it's being invoked on a for loop with control flow, given:

fn main() {
    for i in 0..10 {
        if i % 2 == 0 {
            continue;
        } else if i % 3 == 0 {
            break;
        } else {
            return;
        }
    }
}

Triggering the assist generates:

fn main() {
    (0..10).for_each(|i| {
        if i % 2 == 0 {
            continue;
        } else if i % 3 == 0 {
            break;
        } else {
            return;
        }
    });
}

Which is rather non-functional.

As first resolution, the assist should probably not trigger / show up if there's any control flow going through the loop (possibly any control flow at all for simplicity? e.g. nested loops would make the analysis more difficult).

A second pass could be an ancillary version of the assist which replaces the loop by try_for_each instead, though that only works if the loop is being manipulated by continue or break. If there's a return inside the loop it should probably not be convertible at all, as (AFAIK) Rust doesn't have non-local returns.
rust-analyzer version: (eg. output of "Rust Analyzer: Show RA Version" command)

> rust-analyzer --version
rust-analyzer 0add6e95e 2021-12-23 dev

rustc version: (eg. output of rustc -V)

> rustc --version
rustc 1.57.0 (f1edd0429 2021-11-29)

/cc @mattyhall @Veykril

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 at the convert_for_loop_with_for_each assist entry point and reproduce the Rust example from the report. Done means the assist does not trigger for loops containing the shown control flow; the optional try_for_each follow-up is a separate task.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.