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