]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/regex.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / regex.rs
1 use crate::consts::{constant, Constant};
2 use crate::utils::{is_expn_of, match_def_path, match_type, paths, span_help_and_lint, span_lint};
3 use if_chain::if_chain;
4 use regex_syntax;
5 use rustc::hir::*;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_tool_lint, lint_array};
8 use rustc_data_structures::fx::FxHashSet;
9 use std::convert::TryFrom;
10 use syntax::ast::{LitKind, StrStyle};
11 use syntax::source_map::{BytePos, Span};
12
13 declare_clippy_lint! {
14     /// **What it does:** 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?** This will lead to a runtime panic.
19     ///
20     /// **Known problems:** None.
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:** 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?** Matching the regex can likely be replaced by `==` or
36     /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
37     /// methods.
38     ///
39     /// **Known problems:** None.
40     ///
41     /// **Example:**
42     /// ```ignore
43     /// Regex::new("^foobar")
44     /// ```
45     pub TRIVIAL_REGEX,
46     style,
47     "trivial regular expressions"
48 }
49
50 declare_clippy_lint! {
51     /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
52     /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
53     /// idea anyway).
54     ///
55     /// **Why is this bad?** Performance, at least for now. The macro version is
56     /// likely to catch up long-term, but for now the dynamic version is faster.
57     ///
58     /// **Known problems:** None.
59     ///
60     /// **Example:**
61     /// ```ignore
62     /// regex!("foo|bar")
63     /// ```
64     pub REGEX_MACRO,
65     style,
66     "use of `regex!(_)` instead of `Regex::new(_)`"
67 }
68
69 #[derive(Clone, Default)]
70 pub struct Pass {
71     spans: FxHashSet<Span>,
72     last: Option<HirId>,
73 }
74
75 impl LintPass for Pass {
76     fn get_lints(&self) -> LintArray {
77         lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
78     }
79
80     fn name(&self) -> &'static str {
81         "Regex"
82     }
83 }
84
85 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
86     fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
87         self.spans.clear();
88     }
89
90     fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
91         if_chain! {
92             if self.last.is_none();
93             if let Some(ref expr) = block.expr;
94             if match_type(cx, cx.tables.expr_ty(expr), &paths::REGEX);
95             if let Some(span) = is_expn_of(expr.span, "regex");
96             then {
97                 if !self.spans.contains(&span) {
98                     span_lint(cx,
99                               REGEX_MACRO,
100                               span,
101                               "`regex!(_)` found. \
102                               Please use `Regex::new(_)`, which is faster for now.");
103                     self.spans.insert(span);
104                 }
105                 self.last = Some(block.hir_id);
106             }
107         }
108     }
109
110     fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
111         if self.last.map_or(false, |id| block.hir_id == id) {
112             self.last = None;
113         }
114     }
115
116     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
117         if_chain! {
118             if let ExprKind::Call(ref fun, ref args) = expr.node;
119             if let ExprKind::Path(ref qpath) = fun.node;
120             if args.len() == 1;
121             if let Some(def_id) = cx.tables.qpath_def(qpath, fun.hir_id).opt_def_id();
122             then {
123                 if match_def_path(cx.tcx, def_id, &paths::REGEX_NEW) ||
124                    match_def_path(cx.tcx, def_id, &paths::REGEX_BUILDER_NEW) {
125                     check_regex(cx, &args[0], true);
126                 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_NEW) ||
127                    match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
128                     check_regex(cx, &args[0], false);
129                 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_SET_NEW) {
130                     check_set(cx, &args[0], true);
131                 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_SET_NEW) {
132                     check_set(cx, &args[0], false);
133                 }
134             }
135         }
136     }
137 }
138
139 #[allow(clippy::cast_possible_truncation)] // truncation very unlikely here
140 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
141     let offset = u32::from(offset);
142     let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset);
143     let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + offset);
144     assert!(start <= end);
145     Span::new(start, end, base.ctxt())
146 }
147
148 fn const_str<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) -> Option<String> {
149     constant(cx, cx.tables, e).and_then(|(c, _)| match c {
150         Constant::Str(s) => Some(s),
151         _ => None,
152     })
153 }
154
155 fn is_trivial_regex(s: &regex_syntax::hir::Hir) -> Option<&'static str> {
156     use regex_syntax::hir::Anchor::*;
157     use regex_syntax::hir::HirKind::*;
158
159     let is_literal = |e: &[regex_syntax::hir::Hir]| {
160         e.iter().all(|e| match *e.kind() {
161             Literal(_) => true,
162             _ => false,
163         })
164     };
165
166     match *s.kind() {
167         Empty | Anchor(_) => Some("the regex is unlikely to be useful as it is"),
168         Literal(_) => Some("consider using `str::contains`"),
169         Alternation(ref exprs) => {
170             if exprs.iter().all(|e| e.kind().is_empty()) {
171                 Some("the regex is unlikely to be useful as it is")
172             } else {
173                 None
174             }
175         },
176         Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
177             (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => {
178                 Some("consider using `str::is_empty`")
179             },
180             (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
181                 Some("consider using `==` on `str`s")
182             },
183             (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
184             (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
185                 Some("consider using `str::ends_with`")
186             },
187             _ if is_literal(exprs) => Some("consider using `str::contains`"),
188             _ => None,
189         },
190         _ => None,
191     }
192 }
193
194 fn check_set<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
195     if_chain! {
196         if let ExprKind::AddrOf(_, ref expr) = expr.node;
197         if let ExprKind::Array(ref exprs) = expr.node;
198         then {
199             for expr in exprs {
200                 check_regex(cx, expr, utf8);
201             }
202         }
203     }
204 }
205
206 fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
207     let mut parser = regex_syntax::ParserBuilder::new()
208         .unicode(utf8)
209         .allow_invalid_utf8(!utf8)
210         .build();
211
212     if let ExprKind::Lit(ref lit) = expr.node {
213         if let LitKind::Str(ref r, style) = lit.node {
214             let r = &r.as_str();
215             let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
216             match parser.parse(r) {
217                 Ok(r) => {
218                     if let Some(repl) = is_trivial_regex(&r) {
219                         span_help_and_lint(cx, TRIVIAL_REGEX, expr.span, "trivial regex", repl);
220                     }
221                 },
222                 Err(regex_syntax::Error::Parse(e)) => {
223                     span_lint(
224                         cx,
225                         INVALID_REGEX,
226                         str_span(expr.span, *e.span(), offset),
227                         &format!("regex syntax error: {}", e.kind()),
228                     );
229                 },
230                 Err(regex_syntax::Error::Translate(e)) => {
231                     span_lint(
232                         cx,
233                         INVALID_REGEX,
234                         str_span(expr.span, *e.span(), offset),
235                         &format!("regex syntax error: {}", e.kind()),
236                     );
237                 },
238                 Err(e) => {
239                     span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
240                 },
241             }
242         }
243     } else if let Some(r) = const_str(cx, expr) {
244         match parser.parse(&r) {
245             Ok(r) => {
246                 if let Some(repl) = is_trivial_regex(&r) {
247                     span_help_and_lint(cx, TRIVIAL_REGEX, expr.span, "trivial regex", repl);
248                 }
249             },
250             Err(regex_syntax::Error::Parse(e)) => {
251                 span_lint(
252                     cx,
253                     INVALID_REGEX,
254                     expr.span,
255                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
256                 );
257             },
258             Err(regex_syntax::Error::Translate(e)) => {
259                 span_lint(
260                     cx,
261                     INVALID_REGEX,
262                     expr.span,
263                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
264                 );
265             },
266             Err(e) => {
267                 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
268             },
269         }
270     }
271 }