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