]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/regex.rs
Run rustfmt
[rust.git] / clippy_lints / src / regex.rs
1 use regex_syntax;
2 use rustc::hir::*;
3 use rustc::lint::*;
4 use rustc::middle::const_val::ConstVal;
5 use rustc_const_eval::ConstContext;
6 use rustc::ty::subst::Substs;
7 use std::collections::HashSet;
8 use std::error::Error;
9 use syntax::ast::{LitKind, NodeId};
10 use syntax::codemap::{Span, BytePos};
11 use syntax::symbol::InternedString;
12 use utils::{is_expn_of, match_def_path, match_type, paths, span_lint, span_help_and_lint};
13
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 /// ```rust
24 /// Regex::new("|")
25 /// ```
26 declare_lint! {
27     pub INVALID_REGEX,
28     Deny,
29     "invalid regular expressions"
30 }
31
32 /// **What it does:** Checks for trivial [regex] creation (with `Regex::new`,
33 /// `RegexBuilder::new` or `RegexSet::new`).
34 ///
35 /// [regex]: https://crates.io/crates/regex
36 ///
37 /// **Why is this bad?** Matching the regex can likely be replaced by `==` or
38 /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
39 /// methods.
40 ///
41 /// **Known problems:** None.
42 ///
43 /// **Example:**
44 /// ```rust
45 /// Regex::new("^foobar")
46 /// ```
47 declare_lint! {
48     pub TRIVIAL_REGEX,
49     Warn,
50     "trivial regular expressions"
51 }
52
53 /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
54 /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
55 /// idea anyway).
56 ///
57 /// **Why is this bad?** Performance, at least for now. The macro version is
58 /// likely to catch up long-term, but for now the dynamic version is faster.
59 ///
60 /// **Known problems:** None.
61 ///
62 /// **Example:**
63 /// ```rust
64 /// regex!("foo|bar")
65 /// ```
66 declare_lint! {
67     pub REGEX_MACRO,
68     Warn,
69     "use of `regex!(_)` instead of `Regex::new(_)`"
70 }
71
72 #[derive(Clone, Default)]
73 pub struct Pass {
74     spans: HashSet<Span>,
75     last: Option<NodeId>,
76 }
77
78 impl LintPass for Pass {
79     fn get_lints(&self) -> LintArray {
80         lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
81     }
82 }
83
84 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
85     fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
86         self.spans.clear();
87     }
88
89     fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
90         if_let_chain!{[
91             self.last.is_none(),
92             let Some(ref expr) = block.expr,
93             match_type(cx, cx.tables.expr_ty(expr), &paths::REGEX),
94             let Some(span) = is_expn_of(expr.span, "regex"),
95         ], {
96             if !self.spans.contains(&span) {
97                 span_lint(cx,
98                           REGEX_MACRO,
99                           span,
100                           "`regex!(_)` found. \
101                           Please use `Regex::new(_)`, which is faster for now.");
102                 self.spans.insert(span);
103             }
104             self.last = Some(block.id);
105         }}
106     }
107
108     fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
109         if self.last.map_or(false, |id| block.id == id) {
110             self.last = None;
111         }
112     }
113
114     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
115         if_let_chain!{[
116             let ExprCall(ref fun, ref args) = expr.node,
117             let ExprPath(ref qpath) = fun.node,
118             args.len() == 1,
119         ], {
120             let def_id = cx.tables.qpath_def(qpath, fun.hir_id).def_id();
121             if match_def_path(cx.tcx, def_id, &paths::REGEX_NEW) ||
122                match_def_path(cx.tcx, def_id, &paths::REGEX_BUILDER_NEW) {
123                 check_regex(cx, &args[0], true);
124             } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_NEW) ||
125                match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
126                 check_regex(cx, &args[0], false);
127             } else if match_def_path(cx.tcx, def_id, &paths::REGEX_SET_NEW) {
128                 check_set(cx, &args[0], true);
129             } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_SET_NEW) {
130                 check_set(cx, &args[0], false);
131             }
132         }}
133     }
134 }
135
136 #[allow(cast_possible_truncation)]
137 fn str_span(base: Span, s: &str, c: usize) -> Span {
138     let mut si = s.char_indices().skip(c);
139
140     match (si.next(), si.next()) {
141         (Some((l, _)), Some((h, _))) => {
142             Span::new(base.lo() + BytePos(l as u32), base.lo() + BytePos(h as u32), base.ctxt())
143         },
144         _ => base,
145     }
146 }
147
148 fn const_str(cx: &LateContext, e: &Expr) -> Option<InternedString> {
149     let parent_item = cx.tcx.hir.get_parent(e.id);
150     let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
151     let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
152     match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(e) {
153         Ok(ConstVal::Str(r)) => Some(r),
154         _ => None,
155     }
156 }
157
158 fn is_trivial_regex(s: &regex_syntax::Expr) -> Option<&'static str> {
159     use regex_syntax::Expr;
160
161     match *s {
162         Expr::Empty | Expr::StartText | Expr::EndText => Some("the regex is unlikely to be useful as it is"),
163         Expr::Literal { .. } => Some("consider using `str::contains`"),
164         Expr::Concat(ref exprs) => {
165             match exprs.len() {
166                 2 => {
167                     match (&exprs[0], &exprs[1]) {
168                         (&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"),
169                         (&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"),
170                         (&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"),
171                         _ => None,
172                     }
173                 },
174                 3 => {
175                     if let (&Expr::StartText, &Expr::Literal { .. }, &Expr::EndText) =
176                         (&exprs[0], &exprs[1], &exprs[2])
177                     {
178                         Some("consider using `==` on `str`s")
179                     } else {
180                         None
181                     }
182                 },
183                 _ => None,
184             }
185         },
186         _ => None,
187     }
188 }
189
190 fn check_set(cx: &LateContext, expr: &Expr, utf8: bool) {
191     if_let_chain! {[
192         let ExprAddrOf(_, ref expr) = expr.node,
193         let ExprArray(ref exprs) = expr.node,
194     ], {
195         for expr in exprs {
196             check_regex(cx, expr, utf8);
197         }
198     }}
199 }
200
201 fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
202     let builder = regex_syntax::ExprBuilder::new().unicode(utf8);
203
204     if let ExprLit(ref lit) = expr.node {
205         if let LitKind::Str(ref r, _) = lit.node {
206             let r = &r.as_str();
207             match builder.parse(r) {
208                 Ok(r) => {
209                     if let Some(repl) = is_trivial_regex(&r) {
210                         span_help_and_lint(
211                             cx,
212                             TRIVIAL_REGEX,
213                             expr.span,
214                             "trivial regex",
215                             &format!("consider using {}", repl),
216                         );
217                     }
218                 },
219                 Err(e) => {
220                     span_lint(
221                         cx,
222                         INVALID_REGEX,
223                         str_span(expr.span, r, e.position()),
224                         &format!("regex syntax error: {}", e.description()),
225                     );
226                 },
227             }
228         }
229     } else if let Some(r) = const_str(cx, expr) {
230         match builder.parse(&r) {
231             Ok(r) => {
232                 if let Some(repl) = is_trivial_regex(&r) {
233                     span_help_and_lint(
234                         cx,
235                         TRIVIAL_REGEX,
236                         expr.span,
237                         "trivial regex",
238                         &format!("consider using {}", repl),
239                     );
240                 }
241             },
242             Err(e) => {
243                 span_lint(
244                     cx,
245                     INVALID_REGEX,
246                     expr.span,
247                     &format!("regex syntax error on position {}: {}", e.position(), e.description()),
248                 );
249             },
250         }
251     }
252 }