]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/regex.rs
Rollup merge of #74344 - estebank:stringly-wobbly, r=eddyb
[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:** None.
39     ///
40     /// **Example:**
41     /// ```ignore
42     /// Regex::new("^foobar")
43     /// ```
44     pub TRIVIAL_REGEX,
45     style,
46     "trivial regular expressions"
47 }
48
49 #[derive(Clone, Default)]
50 pub struct Regex {
51     spans: FxHashSet<Span>,
52     last: Option<HirId>,
53 }
54
55 impl_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(ref fun, ref 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 #[allow(clippy::cast_possible_truncation)] // truncation very unlikely here
82 #[must_use]
83 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
84     let offset = u32::from(offset);
85     let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset);
86     let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + offset);
87     assert!(start <= end);
88     Span::new(start, end, base.ctxt())
89 }
90
91 fn const_str<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> Option<String> {
92     constant(cx, cx.tables(), e).and_then(|(c, _)| match c {
93         Constant::Str(s) => Some(s),
94         _ => None,
95     })
96 }
97
98 fn is_trivial_regex(s: &regex_syntax::hir::Hir) -> Option<&'static str> {
99     use regex_syntax::hir::Anchor::{EndText, StartText};
100     use regex_syntax::hir::HirKind::{Alternation, Anchor, Concat, Empty, Literal};
101
102     let is_literal = |e: &[regex_syntax::hir::Hir]| e.iter().all(|e| matches!(*e.kind(), Literal(_)));
103
104     match *s.kind() {
105         Empty | Anchor(_) => Some("the regex is unlikely to be useful as it is"),
106         Literal(_) => Some("consider using `str::contains`"),
107         Alternation(ref exprs) => {
108             if exprs.iter().all(|e| e.kind().is_empty()) {
109                 Some("the regex is unlikely to be useful as it is")
110             } else {
111                 None
112             }
113         },
114         Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
115             (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => {
116                 Some("consider using `str::is_empty`")
117             },
118             (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
119                 Some("consider using `==` on `str`s")
120             },
121             (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
122             (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
123                 Some("consider using `str::ends_with`")
124             },
125             _ if is_literal(exprs) => Some("consider using `str::contains`"),
126             _ => None,
127         },
128         _ => None,
129     }
130 }
131
132 fn check_set<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) {
133     if_chain! {
134         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) = expr.kind;
135         if let ExprKind::Array(exprs) = expr.kind;
136         then {
137             for expr in exprs {
138                 check_regex(cx, expr, utf8);
139             }
140         }
141     }
142 }
143
144 fn check_regex<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) {
145     let mut parser = regex_syntax::ParserBuilder::new()
146         .unicode(utf8)
147         .allow_invalid_utf8(!utf8)
148         .build();
149
150     if let ExprKind::Lit(ref lit) = expr.kind {
151         if let LitKind::Str(ref r, style) = lit.node {
152             let r = &r.as_str();
153             let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
154             match parser.parse(r) {
155                 Ok(r) => {
156                     if let Some(repl) = is_trivial_regex(&r) {
157                         span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
158                     }
159                 },
160                 Err(regex_syntax::Error::Parse(e)) => {
161                     span_lint(
162                         cx,
163                         INVALID_REGEX,
164                         str_span(expr.span, *e.span(), offset),
165                         &format!("regex syntax error: {}", e.kind()),
166                     );
167                 },
168                 Err(regex_syntax::Error::Translate(e)) => {
169                     span_lint(
170                         cx,
171                         INVALID_REGEX,
172                         str_span(expr.span, *e.span(), offset),
173                         &format!("regex syntax error: {}", e.kind()),
174                     );
175                 },
176                 Err(e) => {
177                     span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
178                 },
179             }
180         }
181     } else if let Some(r) = const_str(cx, expr) {
182         match parser.parse(&r) {
183             Ok(r) => {
184                 if let Some(repl) = is_trivial_regex(&r) {
185                     span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
186                 }
187             },
188             Err(regex_syntax::Error::Parse(e)) => {
189                 span_lint(
190                     cx,
191                     INVALID_REGEX,
192                     expr.span,
193                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
194                 );
195             },
196             Err(regex_syntax::Error::Translate(e)) => {
197                 span_lint(
198                     cx,
199                     INVALID_REGEX,
200                     expr.span,
201                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
202                 );
203             },
204             Err(e) => {
205                 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
206             },
207         }
208     }
209 }