Skip to content

Commit 711fd7f

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

File tree

5 files changed

+174
-7
lines changed

5 files changed

+174
-7
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_compile_in_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#regex_compile_in_loop
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_COMPILE_IN_LOOP_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: 96 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use clippy_utils::source::SpanRangeExt;
66
use clippy_utils::{def_path_def_ids, path_def_id, paths};
77
use rustc_ast::ast::{LitKind, StrStyle};
88
use rustc_hir::def_id::DefIdMap;
9+
use rustc_hir::intravisit::{self, Visitor};
910
use rustc_hir::{BorrowKind, Expr, ExprKind};
1011
use rustc_lint::{LateContext, LateLintPass};
1112
use rustc_session::impl_lint_pass;
@@ -55,6 +56,44 @@ declare_clippy_lint! {
5556
"trivial regular expressions"
5657
}
5758

59+
declare_clippy_lint! {
60+
/// ### What it does
61+
///
62+
/// Checks for [regex](https://crates.io/crates/regex) compilation inside a loop with a literal.
63+
///
64+
/// ### Why is this bad?
65+
///
66+
/// Compiling a regex is a much more expensive operation than using one, and a compiled regex can be used multiple times.
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+
/// should 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+
///
91+
#[clippy::version = "1.83.0"]
92+
pub REGEX_COMPILE_IN_LOOP,
93+
perf,
94+
"regular expression compilation performed in a loop"
95+
}
96+
5897
#[derive(Copy, Clone)]
5998
enum RegexKind {
6099
Unicode,
@@ -68,7 +107,7 @@ pub struct Regex {
68107
definitions: DefIdMap<RegexKind>,
69108
}
70109

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

73112
impl<'tcx> LateLintPass<'tcx> for Regex {
74113
fn check_crate(&mut self, cx: &LateContext<'tcx>) {
@@ -92,17 +131,69 @@ impl<'tcx> LateLintPass<'tcx> for Regex {
92131
}
93132

94133
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
95-
if let ExprKind::Call(fun, [arg]) = expr.kind
96-
&& let Some(def_id) = path_def_id(cx, fun)
97-
&& let Some(regex_kind) = self.definitions.get(&def_id)
98-
{
134+
if let Some((regex_kind, _, arg)) = extract_regex_call(&self.definitions, cx, expr) {
99135
match regex_kind {
100136
RegexKind::Unicode => check_regex(cx, arg, true),
101137
RegexKind::UnicodeSet => check_set(cx, arg, true),
102138
RegexKind::Bytes => check_regex(cx, arg, false),
103139
RegexKind::BytesSet => check_set(cx, arg, false),
104140
}
105141
}
142+
143+
if let ExprKind::Loop(block, _, _, span) = expr.kind {
144+
let mut visitor = RegexCompVisitor {
145+
cx,
146+
loop_span: span,
147+
definitions: &self.definitions,
148+
};
149+
150+
visitor.visit_block(block);
151+
}
152+
}
153+
}
154+
155+
struct RegexCompVisitor<'pass, 'tcx> {
156+
definitions: &'pass DefIdMap<RegexKind>,
157+
cx: &'pass LateContext<'tcx>,
158+
loop_span: Span,
159+
}
160+
161+
impl<'pass, 'tcx> Visitor<'tcx> for RegexCompVisitor<'pass, 'tcx> {
162+
type NestedFilter = intravisit::nested_filter::None;
163+
164+
fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
165+
if let Some((_, fun, arg)) = extract_regex_call(self.definitions, self.cx, expr)
166+
&& (matches!(arg.kind, ExprKind::Lit(_)) || const_str(self.cx, arg).is_some())
167+
{
168+
span_lint_and_help(
169+
self.cx,
170+
REGEX_COMPILE_IN_LOOP,
171+
fun.span,
172+
"compiling a regex in a loop",
173+
Some(self.loop_span),
174+
"move the regex construction outside this loop",
175+
);
176+
}
177+
178+
// Avoid recursing into loops, as the LateLintPass::visit_expr will do this already.
179+
if !matches!(expr.kind, ExprKind::Loop(..)) {
180+
intravisit::walk_expr(self, expr);
181+
}
182+
}
183+
}
184+
185+
fn extract_regex_call<'tcx>(
186+
definitions: &DefIdMap<RegexKind>,
187+
cx: &LateContext<'tcx>,
188+
expr: &'tcx Expr<'tcx>,
189+
) -> Option<(RegexKind, &'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
190+
if let ExprKind::Call(fun, [arg]) = expr.kind
191+
&& let Some(def_id) = path_def_id(cx, fun)
192+
&& let Some(regex_kind) = definitions.get(&def_id)
193+
{
194+
Some((*regex_kind, fun, arg))
195+
} else {
196+
None
106197
}
107198
}
108199

tests/ui/regex.rs

Lines changed: 25 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_compile_in_loop)]
99

1010
extern crate regex;
1111

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

121+
fn regex_compile_in_loop() {
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+
128+
if true {
129+
let regex = Regex::new("a.b");
130+
//~^ ERROR: compiling a regex in a loop
131+
}
132+
133+
for _ in 0..10 {
134+
let nested_regex = Regex::new("a.b");
135+
//~^ ERROR: compiling a regex in a loop
136+
}
137+
}
138+
139+
for i in 0..10 {
140+
let dependant_regex = Regex::new(&format!("{i}"));
141+
}
142+
}
143+
121144
fn main() {
122145
syntax_error();
123146
trivial_regex();
147+
regex_compile_in_loop();
124148
}

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-compile-in-loop` implied by `-D warnings`
210+
= help: to override `-D warnings` add `#[allow(clippy::regex_compile_in_loop)]`
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:129: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:134: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:133:9
244+
|
245+
LL | for _ in 0..10 {
246+
| ^^^^^^^^^^^^^^
247+
248+
error: aborting due to 28 previous errors
199249

0 commit comments

Comments
 (0)