You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Auto merge of rust-lang#13412 - GnomedDev:regex-comp-in-loop, r=y21
Implement lint for regex::Regex compilation inside a loop
Closesrust-lang#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.
Copy file name to clipboardexpand all lines: clippy_lints/src/regex.rs
+63-2
Original file line number
Diff line number
Diff line change
@@ -6,7 +6,7 @@ use clippy_utils::source::SpanRangeExt;
6
6
use clippy_utils::{def_path_res_with_base, find_crates, path_def_id, paths};
7
7
use rustc_ast::ast::{LitKind,StrStyle};
8
8
use rustc_hir::def_id::DefIdMap;
9
-
use rustc_hir::{BorrowKind,Expr,ExprKind};
9
+
use rustc_hir::{BorrowKind,Expr,ExprKind,OwnerId};
10
10
use rustc_lint::{LateContext,LateLintPass};
11
11
use rustc_session::impl_lint_pass;
12
12
use rustc_span::{BytePos,Span};
@@ -55,6 +55,44 @@ declare_clippy_lint! {
55
55
"trivial regular expressions"
56
56
}
57
57
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
+
pubREGEX_CREATION_IN_LOOPS,
92
+
perf,
93
+
"regular expression compilation performed in a loop"
0 commit comments