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