Skip to content

No warning for open range loop #150084

@jamesmunns

Description

@jamesmunns

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions