Auto merge of #13412 - GnomedDev:regex-comp-in-loop, r=y21

Implement lint for regex::Regex compilation inside a loop

Closes #598.

Seems like a pretty simple one, I'm not sure if I sorted out all the lint plumbing correctly because I was adding it to the existing regex pass, but seems to work. The name is a bit jank and I'm super open to suggestions for changing it.

changelog: [`regex_creation_in_loops`]: Added lint for Regex compilation inside loops.
This commit is contained in:
bors 2024-10-05 18:41:45 +00:00
commit 753629bb33
5 changed files with 145 additions and 4 deletions

View file

@ -5,7 +5,7 @@
clippy::needless_borrow,
clippy::needless_borrows_for_generic_args
)]
#![warn(clippy::invalid_regex, clippy::trivial_regex)]
#![warn(clippy::invalid_regex, clippy::trivial_regex, clippy::regex_creation_in_loops)]
extern crate regex;
@ -118,7 +118,35 @@ fn trivial_regex() {
let _ = BRegex::new(r"\b{start}word\b{end}");
}
fn regex_creation_in_loops() {
loop {
static STATIC_REGEX: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| Regex::new("a.b").unwrap());
let regex = Regex::new("a.b");
//~^ ERROR: compiling a regex in a loop
let regex = BRegex::new("a.b");
//~^ ERROR: compiling a regex in a loop
#[allow(clippy::regex_creation_in_loops)]
let allowed_regex = Regex::new("a.b");
if true {
let regex = Regex::new("a.b");
//~^ ERROR: compiling a regex in a loop
}
for _ in 0..10 {
let nested_regex = Regex::new("a.b");
//~^ ERROR: compiling a regex in a loop
}
}
for i in 0..10 {
let dependant_regex = Regex::new(&format!("{i}"));
}
}
fn main() {
syntax_error();
trivial_regex();
regex_creation_in_loops();
}

View file

@ -195,5 +195,55 @@ LL | let binary_trivial_empty = BRegex::new("^$");
|
= help: consider using `str::is_empty`
error: aborting due to 24 previous errors
error: compiling a regex in a loop
--> tests/ui/regex.rs:125:21
|
LL | let regex = Regex::new("a.b");
| ^^^^^^^^^^
|
help: move the regex construction outside this loop
--> tests/ui/regex.rs:122:5
|
LL | loop {
| ^^^^
= note: `-D clippy::regex-creation-in-loops` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::regex_creation_in_loops)]`
error: compiling a regex in a loop
--> tests/ui/regex.rs:127:21
|
LL | let regex = BRegex::new("a.b");
| ^^^^^^^^^^^
|
help: move the regex construction outside this loop
--> tests/ui/regex.rs:122:5
|
LL | loop {
| ^^^^
error: compiling a regex in a loop
--> tests/ui/regex.rs:133:25
|
LL | let regex = Regex::new("a.b");
| ^^^^^^^^^^
|
help: move the regex construction outside this loop
--> tests/ui/regex.rs:122:5
|
LL | loop {
| ^^^^
error: compiling a regex in a loop
--> tests/ui/regex.rs:138:32
|
LL | let nested_regex = Regex::new("a.b");
| ^^^^^^^^^^
|
help: move the regex construction outside this loop
--> tests/ui/regex.rs:137:9
|
LL | for _ in 0..10 {
| ^^^^^^^^^^^^^^
error: aborting due to 28 previous errors