]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/regex.rs
Rollup merge of #88215 - jyn514:lazy-loading, r=petrochenkov
[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_data_structures::fx::FxHashSet;
7 use rustc_hir::{BorrowKind, Expr, ExprKind, HirId};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 use rustc_span::source_map::{BytePos, Span};
11 use std::convert::TryFrom;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks [regex](https://crates.io/crates/regex) creation
16     /// (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`) for correct
17     /// regex syntax.
18     ///
19     /// ### Why is this bad?
20     /// This will lead to a runtime panic.
21     ///
22     /// ### Example
23     /// ```ignore
24     /// Regex::new("|")
25     /// ```
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     pub TRIVIAL_REGEX,
51     nursery,
52     "trivial regular expressions"
53 }
54
55 #[derive(Clone, Default)]
56 pub struct Regex {
57     spans: FxHashSet<Span>,
58     last: Option<HirId>,
59 }
60
61 impl_lint_pass!(Regex => [INVALID_REGEX, TRIVIAL_REGEX]);
62
63 impl<'tcx> LateLintPass<'tcx> for Regex {
64     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
65         if_chain! {
66             if let ExprKind::Call(fun, args) = expr.kind;
67             if let ExprKind::Path(ref qpath) = fun.kind;
68             if args.len() == 1;
69             if let Some(def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
70             then {
71                 if match_def_path(cx, def_id, &paths::REGEX_NEW) ||
72                    match_def_path(cx, def_id, &paths::REGEX_BUILDER_NEW) {
73                     check_regex(cx, &args[0], true);
74                 } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_NEW) ||
75                    match_def_path(cx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
76                     check_regex(cx, &args[0], false);
77                 } else if match_def_path(cx, def_id, &paths::REGEX_SET_NEW) {
78                     check_set(cx, &args[0], true);
79                 } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_SET_NEW) {
80                     check_set(cx, &args[0], false);
81                 }
82             }
83         }
84     }
85 }
86
87 #[allow(clippy::cast_possible_truncation)] // truncation very unlikely here
88 #[must_use]
89 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
90     let offset = u32::from(offset);
91     let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset);
92     let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + offset);
93     assert!(start <= end);
94     Span::new(start, end, base.ctxt())
95 }
96
97 fn const_str<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> Option<String> {
98     constant(cx, cx.typeck_results(), e).and_then(|(c, _)| match c {
99         Constant::Str(s) => Some(s),
100         _ => None,
101     })
102 }
103
104 fn is_trivial_regex(s: &regex_syntax::hir::Hir) -> Option<&'static str> {
105     use regex_syntax::hir::Anchor::{EndText, StartText};
106     use regex_syntax::hir::HirKind::{Alternation, Anchor, Concat, Empty, Literal};
107
108     let is_literal = |e: &[regex_syntax::hir::Hir]| e.iter().all(|e| matches!(*e.kind(), Literal(_)));
109
110     match *s.kind() {
111         Empty | Anchor(_) => Some("the regex is unlikely to be useful as it is"),
112         Literal(_) => Some("consider using `str::contains`"),
113         Alternation(ref exprs) => {
114             if exprs.iter().all(|e| e.kind().is_empty()) {
115                 Some("the regex is unlikely to be useful as it is")
116             } else {
117                 None
118             }
119         },
120         Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
121             (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => {
122                 Some("consider using `str::is_empty`")
123             },
124             (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
125                 Some("consider using `==` on `str`s")
126             },
127             (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
128             (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
129                 Some("consider using `str::ends_with`")
130             },
131             _ if is_literal(exprs) => Some("consider using `str::contains`"),
132             _ => None,
133         },
134         _ => None,
135     }
136 }
137
138 fn check_set<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) {
139     if_chain! {
140         if let ExprKind::AddrOf(BorrowKind::Ref, _, expr) = expr.kind;
141         if let ExprKind::Array(exprs) = expr.kind;
142         then {
143             for expr in exprs {
144                 check_regex(cx, expr, utf8);
145             }
146         }
147     }
148 }
149
150 fn check_regex<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) {
151     let mut parser = regex_syntax::ParserBuilder::new()
152         .unicode(true)
153         .allow_invalid_utf8(!utf8)
154         .build();
155
156     if let ExprKind::Lit(ref lit) = expr.kind {
157         if let LitKind::Str(ref r, style) = lit.node {
158             let r = &r.as_str();
159             let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
160             match parser.parse(r) {
161                 Ok(r) => {
162                     if let Some(repl) = is_trivial_regex(&r) {
163                         span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
164                     }
165                 },
166                 Err(regex_syntax::Error::Parse(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(regex_syntax::Error::Translate(e)) => {
175                     span_lint(
176                         cx,
177                         INVALID_REGEX,
178                         str_span(expr.span, *e.span(), offset),
179                         &format!("regex syntax error: {}", e.kind()),
180                     );
181                 },
182                 Err(e) => {
183                     span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
184                 },
185             }
186         }
187     } else if let Some(r) = const_str(cx, expr) {
188         match parser.parse(&r) {
189             Ok(r) => {
190                 if let Some(repl) = is_trivial_regex(&r) {
191                     span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
192                 }
193             },
194             Err(regex_syntax::Error::Parse(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(regex_syntax::Error::Translate(e)) => {
203                 span_lint(
204                     cx,
205                     INVALID_REGEX,
206                     expr.span,
207                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
208                 );
209             },
210             Err(e) => {
211                 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
212             },
213         }
214     }
215 }