Skip to content

regex in loop triggers on OnceLock::<Regex>::get_or_init in loop #15237

Open
@hkBst

Description

@hkBst

Summary

Due to the nature of OnceLock, initialization happens only once, so I think this is a false positive:

Lint Name

regex_creation_in_loops

Reproducer

I tried this code:

macro_rules! static_regex {
    ($re:literal) => {{
        static RE: ::std::sync::OnceLock<::regex::Regex> = ::std::sync::OnceLock::new();
        RE.get_or_init(|| ::regex::Regex::new($re).unwrap())
    }};
}

fn main() {
    while false {
        if static_regex!(r"^\s*//").is_match("") {
            break;
        }
    }
}

I saw this happen:

warning: compiling a regex in a loop
  --> src/main.rs:4:27
   |
4  |         RE.get_or_init(|| ::regex::Regex::new($re).unwrap())
   |                           ^^^^^^^^^^^^^^^^^^^
...
10 |         if static_regex!(r"^\s*//").is_match("") {
   |            ------------------------ in this macro invocation
   |
help: move the regex construction outside this loop
  --> src/main.rs:9:5
   |
9  |     while false {
   |     ^^^^^^^^^^^
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#regex_creation_in_loops
   = note: `#[warn(clippy::regex_creation_in_loops)]` on by default
   = note: this warning originates in the macro `static_regex` (in Nightly builds, run with -Z macro-backtrace for more info)

I expected to see this happen:
no warning

Version

current nightly

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions