Skip to content

Commit 9f5bfe2

Browse files
committed
Implement lint for regex::Regex compilation inside a loop
1 parent 903293b commit 9f5bfe2

File tree

5 files changed

+141
-3
lines changed

5 files changed

+141
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5873,6 +5873,7 @@ Released 2018-09-13
58735873
[`ref_in_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#ref_in_deref
58745874
[`ref_option_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#ref_option_ref
58755875
[`ref_patterns`]: https://rust-lang.github.io/rust-clippy/master/index.html#ref_patterns
5876+
[`regex_creation_in_loops`]: https://rust-lang.github.io/rust-clippy/master/index.html#regex_creation_in_loops
58765877
[`regex_macro`]: https://rust-lang.github.io/rust-clippy/master/index.html#regex_macro
58775878
[`renamed_function_params`]: https://rust-lang.github.io/rust-clippy/master/index.html#renamed_function_params
58785879
[`repeat_once`]: https://rust-lang.github.io/rust-clippy/master/index.html#repeat_once

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
637637
crate::ref_patterns::REF_PATTERNS_INFO,
638638
crate::reference::DEREF_ADDROF_INFO,
639639
crate::regex::INVALID_REGEX_INFO,
640+
crate::regex::REGEX_CREATION_IN_LOOPS_INFO,
640641
crate::regex::TRIVIAL_REGEX_INFO,
641642
crate::repeat_vec_with_capacity::REPEAT_VEC_WITH_CAPACITY_INFO,
642643
crate::reserve_after_initialization::RESERVE_AFTER_INITIALIZATION_INFO,

clippy_lints/src/regex.rs

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,44 @@ declare_clippy_lint! {
5555
"trivial regular expressions"
5656
}
5757

58+
declare_clippy_lint! {
59+
/// ### What it does
60+
///
61+
/// Checks for [regex](https://crates.io/crates/regex) compilation inside a loop with a literal.
62+
///
63+
/// ### Why is this bad?
64+
///
65+
/// Compiling a regex is a much more expensive operation than using one, and a compiled regex can be used multiple times.
66+
/// This is documented as an antipattern [on the regex documentation](https://docs.rs/regex/latest/regex/#avoid-re-compiling-regexes-especially-in-a-loop)
67+
///
68+
/// ### Example
69+
/// ```no_run
70+
/// # let haystacks = [""];
71+
/// # const MY_REGEX: &str = "a.b";
72+
/// for haystack in haystacks {
73+
/// let regex = regex::Regex::new(MY_REGEX).unwrap();
74+
/// if regex.is_match(haystack) {
75+
/// // Perform operation
76+
/// }
77+
/// }
78+
/// ```
79+
/// can be replaced with
80+
/// ```no_run
81+
/// # let haystacks = [""];
82+
/// # const MY_REGEX: &str = "a.b";
83+
/// let regex = regex::Regex::new(MY_REGEX).unwrap();
84+
/// for haystack in haystacks {
85+
/// if regex.is_match(haystack) {
86+
/// // Perform operation
87+
/// }
88+
/// }
89+
/// ```
90+
#[clippy::version = "1.83.0"]
91+
pub REGEX_CREATION_IN_LOOPS,
92+
perf,
93+
"regular expression compilation performed in a loop"
94+
}
95+
5896
#[derive(Copy, Clone)]
5997
enum RegexKind {
6098
Unicode,
@@ -66,9 +104,10 @@ enum RegexKind {
66104
#[derive(Default)]
67105
pub struct Regex {
68106
definitions: DefIdMap<RegexKind>,
107+
loop_stack: Vec<Span>,
69108
}
70109

71-
impl_lint_pass!(Regex => [INVALID_REGEX, TRIVIAL_REGEX]);
110+
impl_lint_pass!(Regex => [INVALID_REGEX, TRIVIAL_REGEX, REGEX_CREATION_IN_LOOPS]);
72111

73112
impl<'tcx> LateLintPass<'tcx> for Regex {
74113
fn check_crate(&mut self, cx: &LateContext<'tcx>) {
@@ -96,12 +135,33 @@ impl<'tcx> LateLintPass<'tcx> for Regex {
96135
&& let Some(def_id) = path_def_id(cx, fun)
97136
&& let Some(regex_kind) = self.definitions.get(&def_id)
98137
{
138+
if let Some(&loop_span) = self.loop_stack.last()
139+
&& (matches!(arg.kind, ExprKind::Lit(_)) || const_str(cx, arg).is_some())
140+
{
141+
span_lint_and_help(
142+
cx,
143+
REGEX_CREATION_IN_LOOPS,
144+
fun.span,
145+
"compiling a regex in a loop",
146+
Some(loop_span),
147+
"move the regex construction outside this loop",
148+
);
149+
}
150+
99151
match regex_kind {
100152
RegexKind::Unicode => check_regex(cx, arg, true),
101153
RegexKind::UnicodeSet => check_set(cx, arg, true),
102154
RegexKind::Bytes => check_regex(cx, arg, false),
103155
RegexKind::BytesSet => check_set(cx, arg, false),
104156
}
157+
} else if let ExprKind::Loop(_, _, _, span) = expr.kind {
158+
self.loop_stack.push(span);
159+
}
160+
}
161+
162+
fn check_expr_post(&mut self, _: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
163+
if matches!(expr.kind, ExprKind::Loop(..)) {
164+
self.loop_stack.pop();
105165
}
106166
}
107167
}

tests/ui/regex.rs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
clippy::needless_borrow,
66
clippy::needless_borrows_for_generic_args
77
)]
8-
#![warn(clippy::invalid_regex, clippy::trivial_regex)]
8+
#![warn(clippy::invalid_regex, clippy::trivial_regex, clippy::regex_creation_in_loops)]
99

1010
extern crate regex;
1111

@@ -118,7 +118,33 @@ fn trivial_regex() {
118118
let _ = BRegex::new(r"\b{start}word\b{end}");
119119
}
120120

121+
fn regex_creation_in_loops() {
122+
loop {
123+
let regex = Regex::new("a.b");
124+
//~^ ERROR: compiling a regex in a loop
125+
let regex = BRegex::new("a.b");
126+
//~^ ERROR: compiling a regex in a loop
127+
#[allow(clippy::regex_creation_in_loops)]
128+
let allowed_regex = Regex::new("a.b");
129+
130+
if true {
131+
let regex = Regex::new("a.b");
132+
//~^ ERROR: compiling a regex in a loop
133+
}
134+
135+
for _ in 0..10 {
136+
let nested_regex = Regex::new("a.b");
137+
//~^ ERROR: compiling a regex in a loop
138+
}
139+
}
140+
141+
for i in 0..10 {
142+
let dependant_regex = Regex::new(&format!("{i}"));
143+
}
144+
}
145+
121146
fn main() {
122147
syntax_error();
123148
trivial_regex();
149+
regex_creation_in_loops();
124150
}

tests/ui/regex.stderr

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,5 +195,55 @@ LL | let binary_trivial_empty = BRegex::new("^$");
195195
|
196196
= help: consider using `str::is_empty`
197197

198-
error: aborting due to 24 previous errors
198+
error: compiling a regex in a loop
199+
--> tests/ui/regex.rs:123:21
200+
|
201+
LL | let regex = Regex::new("a.b");
202+
| ^^^^^^^^^^
203+
|
204+
help: move the regex construction outside this loop
205+
--> tests/ui/regex.rs:122:5
206+
|
207+
LL | loop {
208+
| ^^^^
209+
= note: `-D clippy::regex-creation-in-loops` implied by `-D warnings`
210+
= help: to override `-D warnings` add `#[allow(clippy::regex_creation_in_loops)]`
211+
212+
error: compiling a regex in a loop
213+
--> tests/ui/regex.rs:125:21
214+
|
215+
LL | let regex = BRegex::new("a.b");
216+
| ^^^^^^^^^^^
217+
|
218+
help: move the regex construction outside this loop
219+
--> tests/ui/regex.rs:122:5
220+
|
221+
LL | loop {
222+
| ^^^^
223+
224+
error: compiling a regex in a loop
225+
--> tests/ui/regex.rs:131:25
226+
|
227+
LL | let regex = Regex::new("a.b");
228+
| ^^^^^^^^^^
229+
|
230+
help: move the regex construction outside this loop
231+
--> tests/ui/regex.rs:122:5
232+
|
233+
LL | loop {
234+
| ^^^^
235+
236+
error: compiling a regex in a loop
237+
--> tests/ui/regex.rs:136:32
238+
|
239+
LL | let nested_regex = Regex::new("a.b");
240+
| ^^^^^^^^^^
241+
|
242+
help: move the regex construction outside this loop
243+
--> tests/ui/regex.rs:135:9
244+
|
245+
LL | for _ in 0..10 {
246+
| ^^^^^^^^^^^^^^
247+
248+
error: aborting due to 28 previous errors
199249

0 commit comments

Comments
 (0)