]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/regex.rs
Fix ICE for issue 2594
[rust.git] / clippy_lints / src / regex.rs
1 use regex_syntax;
2 use rustc::hir::*;
3 use rustc::lint::*;
4 use std::collections::HashSet;
5 use syntax::ast::{LitKind, NodeId, StrStyle};
6 use syntax::codemap::{BytePos, Span};
7 use utils::{is_expn_of, match_def_path, match_type, opt_def_id, paths, span_help_and_lint, span_lint};
8 use consts::{constant, Constant};
9
10 /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
11 /// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
12 /// regex syntax.
13 ///
14 /// **Why is this bad?** This will lead to a runtime panic.
15 ///
16 /// **Known problems:** None.
17 ///
18 /// **Example:**
19 /// ```rust
20 /// Regex::new("|")
21 /// ```
22 declare_clippy_lint! {
23     pub INVALID_REGEX,
24     correctness,
25     "invalid regular expressions"
26 }
27
28 /// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
29 /// creation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`).
30 ///
31 /// **Why is this bad?** Matching the regex can likely be replaced by `==` or
32 /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
33 /// methods.
34 ///
35 /// **Known problems:** None.
36 ///
37 /// **Example:**
38 /// ```rust
39 /// Regex::new("^foobar")
40 /// ```
41 declare_clippy_lint! {
42     pub TRIVIAL_REGEX,
43     style,
44     "trivial regular expressions"
45 }
46
47 /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
48 /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
49 /// idea anyway).
50 ///
51 /// **Why is this bad?** Performance, at least for now. The macro version is
52 /// likely to catch up long-term, but for now the dynamic version is faster.
53 ///
54 /// **Known problems:** None.
55 ///
56 /// **Example:**
57 /// ```rust
58 /// regex!("foo|bar")
59 /// ```
60 declare_clippy_lint! {
61     pub REGEX_MACRO,
62     style,
63     "use of `regex!(_)` instead of `Regex::new(_)`"
64 }
65
66 #[derive(Clone, Default)]
67 pub struct Pass {
68     spans: HashSet<Span>,
69     last: Option<NodeId>,
70 }
71
72 impl LintPass for Pass {
73     fn get_lints(&self) -> LintArray {
74         lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
75     }
76 }
77
78 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
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, "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.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.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 ExprCall(ref fun, ref args) = expr.node;
112             if let ExprPath(ref qpath) = fun.node;
113             if args.len() == 1;
114             if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, fun.hir_id));
115             then {
116                 if match_def_path(cx.tcx, def_id, &paths::REGEX_NEW) ||
117                    match_def_path(cx.tcx, def_id, &paths::REGEX_BUILDER_NEW) {
118                     check_regex(cx, &args[0], true);
119                 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_NEW) ||
120                    match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
121                     check_regex(cx, &args[0], false);
122                 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_SET_NEW) {
123                     check_set(cx, &args[0], true);
124                 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_SET_NEW) {
125                     check_set(cx, &args[0], false);
126                 }
127             }
128         }
129     }
130 }
131
132 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
133     let offset = u32::from(offset);
134     let end = base.lo() + BytePos(c.end.offset as u32 + offset);
135     let start = base.lo() + BytePos(c.start.offset as u32 + offset);
136     assert!(start <= end);
137     Span::new(start, end, base.ctxt())
138 }
139
140 fn const_str<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) -> Option<String> {
141     constant(cx, cx.tables, e).and_then(|(c, _)| match c {
142         Constant::Str(s) => Some(s),
143         _ => None,
144     })
145 }
146
147 fn is_trivial_regex(s: &regex_syntax::hir::Hir) -> Option<&'static str> {
148     use regex_syntax::hir::HirKind::*;
149     use regex_syntax::hir::Anchor::*;
150
151     let is_literal = |e: &[regex_syntax::hir::Hir]| e.iter().all(|e| match *e.kind() {
152         Literal(_) => true,
153         _ => false,
154     });
155
156     match *s.kind() {
157         Empty |
158         Anchor(_) => Some("the regex is unlikely to be useful as it is"),
159         Literal(_) => Some("consider using `str::contains`"),
160         Alternation(ref exprs) => if exprs.iter().all(|e| e.kind().is_empty()) {
161             Some("the regex is unlikely to be useful as it is")
162         } else {
163             None
164         },
165         Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
166             (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => Some("consider using `str::is_empty`"),
167             (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => Some("consider using `==` on `str`s"),
168             (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
169             (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => Some("consider using `str::ends_with`"),
170             _ if is_literal(exprs) => Some("consider using `str::contains`"),
171             _ => None,
172         },
173         _ => None,
174     }
175 }
176
177 fn check_set<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
178     if_chain! {
179         if let ExprAddrOf(_, ref expr) = expr.node;
180         if let ExprArray(ref exprs) = expr.node;
181         then {
182             for expr in exprs {
183                 check_regex(cx, expr, utf8);
184             }
185         }
186     }
187 }
188
189 fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
190     let mut parser = regex_syntax::ParserBuilder::new()
191         .unicode(utf8)
192         .allow_invalid_utf8(!utf8)
193         .build();
194
195     if let ExprLit(ref lit) = expr.node {
196         if let LitKind::Str(ref r, style) = lit.node {
197             let r = &r.as_str();
198             let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
199             match parser.parse(r) {
200                 Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
201                     span_help_and_lint(
202                         cx,
203                         TRIVIAL_REGEX,
204                         expr.span,
205                         "trivial regex",
206                         repl,
207                     );
208                 },
209                 Err(regex_syntax::Error::Parse(e)) => {
210                     span_lint(
211                         cx,
212                         INVALID_REGEX,
213                         str_span(expr.span, *e.span(), offset),
214                         &format!("regex syntax error: {}", e.kind()),
215                     );
216                 },
217                 Err(regex_syntax::Error::Translate(e)) => {
218                     span_lint(
219                         cx,
220                         INVALID_REGEX,
221                         str_span(expr.span, *e.span(), offset),
222                         &format!("regex syntax error: {}", e.kind()),
223                     );
224                 },
225                 Err(e) => {
226                     span_lint(
227                         cx,
228                         INVALID_REGEX,
229                         expr.span,
230                         &format!("regex syntax error: {}", e),
231                     );
232                 },
233             }
234         }
235     } else if let Some(r) = const_str(cx, expr) {
236         match parser.parse(&r) {
237             Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
238                 span_help_and_lint(
239                     cx,
240                     TRIVIAL_REGEX,
241                     expr.span,
242                     "trivial regex",
243                     repl,
244                 );
245             },
246             Err(regex_syntax::Error::Parse(e)) => {
247                 span_lint(
248                     cx,
249                     INVALID_REGEX,
250                     expr.span,
251                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
252                 );
253             },
254             Err(regex_syntax::Error::Translate(e)) => {
255                 span_lint(
256                     cx,
257                     INVALID_REGEX,
258                     expr.span,
259                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
260                 );
261             },
262             Err(e) => {
263                 span_lint(
264                     cx,
265                     INVALID_REGEX,
266                     expr.span,
267                     &format!("regex syntax error: {}", e),
268                 );
269             },
270         }
271     }
272 }