Skip to content

Add iter::successors and iter::repeat_with to the list of possibly infinite iterators #17719

Description

@voodookiidoo

What it does

A clippy check, that will try to guess if iter::successor or iter::repeat_with is a finite iterator or not.

Advantage

Another check in the list of possible infinite iterators, like (0..), repeat(1), .cycle().

Drawbacks

Analysis won't operate with CFG, only on heuristics, and thus can give false negative /positive results

Example

use std::iter::{repeat_with, successors};

fn infinity() {
    // this will be infinite, and might hang in runtime (or even panic, if we invoke count method!)
    //      v
    let _ = successors(Some(1i8), |&x| Some(x)).collect::<Vec<_>>();

    // this may be infinite, since some returned values are Some
    //      v
    let _ = successors(Some(1), |&x| if x != 12 { Some(x + 1) } else { None }).collect::<Vec<_>>();
    // this will be finite (empty actually), since the initial value is None
    //      v
    let _ = successors(None, |&x: &i32| Some(x)).count();
    // we consider this as maybe infinite, since we don't operate with cfg
    // even though the generator will return None
    //      v
    let _ = successors(Some(1), dummy_func).count();

    // we consider this as always finite
    // although this makes no sense tbh
    //      v
    let _ = successors(Some(1), |_| None).count();

    // same rules apply to repeat_with
    // this will panic!
    //      v
    let _ = repeat_with(|| 1).count();

    // and the rest is similar to iter::repeat(x) function
}

fn dummy_func(val: &i32) -> Option<i32> {
    None
}

Comparison with existing lints

No response

Additional Context

I am happy to be assigned on this task, it could be my first contribution in the rust-lang community! Also - i am not sure if i need to make it an additional linter rule, i think adding it to the existing infinite_iter.rs would do just fine.

Activity

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

Metadata

Metadata

Assignees

Labels

A-lintArea: New lints

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions