rust-lang / rust-lang/rust

No warning for open range loop

Open
#150,084 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Code
fn main() {
    for idx in 0u8.. {
        println!("{:02X}", idx);
    }
    // not unreachable!
    func();
}

// no `clippy::infinite_loop` lint!
fn func() {
    for idx in 0u8.. {
        println!("{:02X}", idx);
    }
}
Current output
(loops forever in release, or panics in debug, no warning)
Desired output
Some kind of warning that `for i in (0..)` will loop forever
Rationale and extra context

I was surprised to learn today that iterating over a RangeFrom will wrap (or panic on overflow in debug). RangeFrom's docs (https://doc.rust-lang.org/std/ops/struct.RangeFrom.html#impl-Iterator-for-RangeFrom%3CA%3E) do note this, but it was still surprising to me.

It might be worth linting on this in some form, either in rustc or clippy, neither of which have anything to say about this construct.

Other cases

Rust Version
All versions (I guess since 1.6 where RangeFrom stabilized?)
Anything else?

Edit: This is definitely working as designed/as specified, and I did find some older issues, as well as discussions for "new ranges" that cover this point. I still think it might be worth emitting a diagnostic/lint for this because it may be surprising/unexpected for other people as well.

My code was fixed by switching to for idx in 0u32..=u32::MAX, which is what I really meant, and might be what we point people to in the diagnostic.

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 reading the RangeFrom iterator documentation and the existing clippy::infinite_loop lint entry point. Compare whether rustc or Clippy should diagnose open range loops, then define the supported cases and verify that the warning explains the infinite-loop behavior and an appropriate bounded-range alternative.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.