]>
Commit | Line | Data |
---|---|---|
17df50a5 | 1 | use clippy_utils::consts::{constant, Constant}; |
cdc7bbd5 XL |
2 | use clippy_utils::diagnostics::{span_lint, span_lint_and_help}; |
3 | use clippy_utils::{match_def_path, paths}; | |
f20569fa XL |
4 | use if_chain::if_chain; |
5 | use rustc_ast::ast::{LitKind, StrStyle}; | |
c295e0f8 | 6 | use rustc_hir::{BorrowKind, Expr, ExprKind}; |
f20569fa | 7 | use rustc_lint::{LateContext, LateLintPass}; |
c295e0f8 | 8 | use rustc_session::{declare_lint_pass, declare_tool_lint}; |
f20569fa | 9 | use rustc_span::source_map::{BytePos, Span}; |
f20569fa XL |
10 | |
11 | declare_clippy_lint! { | |
94222f64 XL |
12 | /// ### What it does |
13 | /// Checks [regex](https://crates.io/crates/regex) creation | |
f20569fa XL |
14 | /// (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`) for correct |
15 | /// regex syntax. | |
16 | /// | |
94222f64 XL |
17 | /// ### Why is this bad? |
18 | /// This will lead to a runtime panic. | |
f20569fa | 19 | /// |
94222f64 | 20 | /// ### Example |
f20569fa | 21 | /// ```ignore |
064997fb | 22 | /// Regex::new("(") |
f20569fa | 23 | /// ``` |
a2a8927a | 24 | #[clippy::version = "pre 1.29.0"] |
f20569fa XL |
25 | pub INVALID_REGEX, |
26 | correctness, | |
27 | "invalid regular expressions" | |
28 | } | |
29 | ||
30 | declare_clippy_lint! { | |
94222f64 XL |
31 | /// ### What it does |
32 | /// Checks for trivial [regex](https://crates.io/crates/regex) | |
f20569fa XL |
33 | /// creation (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`). |
34 | /// | |
94222f64 XL |
35 | /// ### Why is this bad? |
36 | /// Matching the regex can likely be replaced by `==` or | |
f20569fa XL |
37 | /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str` |
38 | /// methods. | |
39 | /// | |
94222f64 XL |
40 | /// ### Known problems |
41 | /// If the same regex is going to be applied to multiple | |
f20569fa XL |
42 | /// inputs, the precomputations done by `Regex` construction can give |
43 | /// significantly better performance than any of the `str`-based methods. | |
44 | /// | |
94222f64 | 45 | /// ### Example |
f20569fa XL |
46 | /// ```ignore |
47 | /// Regex::new("^foobar") | |
48 | /// ``` | |
a2a8927a | 49 | #[clippy::version = "pre 1.29.0"] |
f20569fa XL |
50 | pub TRIVIAL_REGEX, |
51 | nursery, | |
52 | "trivial regular expressions" | |
53 | } | |
54 | ||
c295e0f8 | 55 | declare_lint_pass!(Regex => [INVALID_REGEX, TRIVIAL_REGEX]); |
f20569fa XL |
56 | |
57 | impl<'tcx> LateLintPass<'tcx> for Regex { | |
58 | fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { | |
59 | if_chain! { | |
f2b60f7d | 60 | if let ExprKind::Call(fun, [arg]) = expr.kind; |
f20569fa | 61 | if let ExprKind::Path(ref qpath) = fun.kind; |
f20569fa XL |
62 | if let Some(def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id(); |
63 | then { | |
64 | if match_def_path(cx, def_id, &paths::REGEX_NEW) || | |
65 | match_def_path(cx, def_id, &paths::REGEX_BUILDER_NEW) { | |
f2b60f7d | 66 | check_regex(cx, arg, true); |
f20569fa XL |
67 | } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_NEW) || |
68 | match_def_path(cx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) { | |
f2b60f7d | 69 | check_regex(cx, arg, false); |
f20569fa | 70 | } else if match_def_path(cx, def_id, &paths::REGEX_SET_NEW) { |
f2b60f7d | 71 | check_set(cx, arg, true); |
f20569fa | 72 | } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_SET_NEW) { |
f2b60f7d | 73 | check_set(cx, arg, false); |
f20569fa XL |
74 | } |
75 | } | |
76 | } | |
77 | } | |
78 | } | |
79 | ||
f20569fa | 80 | #[must_use] |
5e7ed085 | 81 | fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u8) -> Span { |
f20569fa XL |
82 | let offset = u32::from(offset); |
83 | let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset); | |
84 | let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + offset); | |
85 | assert!(start <= end); | |
c295e0f8 | 86 | Span::new(start, end, base.ctxt(), base.parent()) |
f20569fa XL |
87 | } |
88 | ||
89 | fn const_str<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> Option<String> { | |
90 | constant(cx, cx.typeck_results(), e).and_then(|(c, _)| match c { | |
91 | Constant::Str(s) => Some(s), | |
92 | _ => None, | |
93 | }) | |
94 | } | |
95 | ||
96 | fn is_trivial_regex(s: ®ex_syntax::hir::Hir) -> Option<&'static str> { | |
97 | use regex_syntax::hir::Anchor::{EndText, StartText}; | |
98 | use regex_syntax::hir::HirKind::{Alternation, Anchor, Concat, Empty, Literal}; | |
99 | ||
100 | let is_literal = |e: &[regex_syntax::hir::Hir]| e.iter().all(|e| matches!(*e.kind(), Literal(_))); | |
101 | ||
102 | match *s.kind() { | |
103 | Empty | Anchor(_) => Some("the regex is unlikely to be useful as it is"), | |
104 | Literal(_) => Some("consider using `str::contains`"), | |
105 | Alternation(ref exprs) => { | |
106 | if exprs.iter().all(|e| e.kind().is_empty()) { | |
107 | Some("the regex is unlikely to be useful as it is") | |
108 | } else { | |
109 | None | |
110 | } | |
111 | }, | |
112 | Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) { | |
113 | (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => { | |
114 | Some("consider using `str::is_empty`") | |
115 | }, | |
116 | (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => { | |
117 | Some("consider using `==` on `str`s") | |
118 | }, | |
119 | (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"), | |
120 | (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => { | |
121 | Some("consider using `str::ends_with`") | |
122 | }, | |
123 | _ if is_literal(exprs) => Some("consider using `str::contains`"), | |
124 | _ => None, | |
125 | }, | |
126 | _ => None, | |
127 | } | |
128 | } | |
129 | ||
130 | fn check_set<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) { | |
131 | if_chain! { | |
cdc7bbd5 | 132 | if let ExprKind::AddrOf(BorrowKind::Ref, _, expr) = expr.kind; |
f20569fa XL |
133 | if let ExprKind::Array(exprs) = expr.kind; |
134 | then { | |
135 | for expr in exprs { | |
136 | check_regex(cx, expr, utf8); | |
137 | } | |
138 | } | |
139 | } | |
140 | } | |
141 | ||
142 | fn check_regex<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) { | |
143 | let mut parser = regex_syntax::ParserBuilder::new() | |
144 | .unicode(true) | |
145 | .allow_invalid_utf8(!utf8) | |
146 | .build(); | |
147 | ||
148 | if let ExprKind::Lit(ref lit) = expr.kind { | |
149 | if let LitKind::Str(ref r, style) = lit.node { | |
a2a8927a | 150 | let r = r.as_str(); |
f20569fa XL |
151 | let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 }; |
152 | match parser.parse(r) { | |
153 | Ok(r) => { | |
154 | if let Some(repl) = is_trivial_regex(&r) { | |
155 | span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl); | |
156 | } | |
157 | }, | |
158 | Err(regex_syntax::Error::Parse(e)) => { | |
159 | span_lint( | |
160 | cx, | |
161 | INVALID_REGEX, | |
162 | str_span(expr.span, *e.span(), offset), | |
163 | &format!("regex syntax error: {}", e.kind()), | |
164 | ); | |
165 | }, | |
166 | Err(regex_syntax::Error::Translate(e)) => { | |
167 | span_lint( | |
168 | cx, | |
169 | INVALID_REGEX, | |
170 | str_span(expr.span, *e.span(), offset), | |
171 | &format!("regex syntax error: {}", e.kind()), | |
172 | ); | |
173 | }, | |
174 | Err(e) => { | |
2b03887a | 175 | span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {e}")); |
f20569fa XL |
176 | }, |
177 | } | |
178 | } | |
179 | } else if let Some(r) = const_str(cx, expr) { | |
180 | match parser.parse(&r) { | |
181 | Ok(r) => { | |
182 | if let Some(repl) = is_trivial_regex(&r) { | |
183 | span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl); | |
184 | } | |
185 | }, | |
186 | Err(regex_syntax::Error::Parse(e)) => { | |
187 | span_lint( | |
188 | cx, | |
189 | INVALID_REGEX, | |
190 | expr.span, | |
191 | &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()), | |
192 | ); | |
193 | }, | |
194 | Err(regex_syntax::Error::Translate(e)) => { | |
195 | span_lint( | |
196 | cx, | |
197 | INVALID_REGEX, | |
198 | expr.span, | |
199 | &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()), | |
200 | ); | |
201 | }, | |
202 | Err(e) => { | |
2b03887a | 203 | span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {e}")); |
f20569fa XL |
204 | }, |
205 | } | |
206 | } | |
207 | } |