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