]> git.lizzy.rs Git - rust.git/blob - src/regex.rs
8876a649e5d9d403d5124132e83a14d2f279f0ce
[rust.git] / 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::EvalHint::ExprTypeChecked;
6 use rustc_const_eval::eval_const_expr_partial;
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::parse::token::InternedString;
12 use utils::{is_expn_of, match_def_path, match_type, paths, span_lint, span_help_and_lint};
13
14 /// **What it does:** This lint checks `Regex::new(_)` invocations for correct regex syntax.
15 ///
16 /// **Why is this bad?** This will lead to a runtime panic.
17 ///
18 /// **Known problems:** None.
19 ///
20 /// **Example:** `Regex::new("|")`
21 declare_lint! {
22     pub INVALID_REGEX,
23     Deny,
24     "finds invalid regular expressions in `Regex::new(_)` invocations"
25 }
26
27 /// **What it does:** This lint checks for `Regex::new(_)` invocations with trivial regex.
28 ///
29 /// **Why is this bad?** This can likely be replaced by `==` or `str::starts_with`,
30 /// `str::ends_with` or `std::contains` or other `str` methods.
31 ///
32 /// **Known problems:** None.
33 ///
34 /// **Example:** `Regex::new("^foobar")`
35 declare_lint! {
36     pub TRIVIAL_REGEX,
37     Warn,
38     "finds trivial regular expressions in `Regex::new(_)` invocations"
39 }
40
41 /// **What it does:** This lint checks for usage of `regex!(_)` which as of now is usually slower than `Regex::new(_)` unless called in a loop (which is a bad idea anyway).
42 ///
43 /// **Why is this bad?** Performance, at least for now. The macro version is likely to catch up long-term, but for now the dynamic version is faster.
44 ///
45 /// **Known problems:** None
46 ///
47 /// **Example:** `regex!("foo|bar")`
48 declare_lint! {
49     pub REGEX_MACRO,
50     Warn,
51     "finds use of `regex!(_)`, suggests `Regex::new(_)` instead"
52 }
53
54 #[derive(Clone, Default)]
55 pub struct RegexPass {
56     spans: HashSet<Span>,
57     last: Option<NodeId>,
58 }
59
60 impl LintPass for RegexPass {
61     fn get_lints(&self) -> LintArray {
62         lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
63     }
64 }
65
66 impl LateLintPass for RegexPass {
67     fn check_crate(&mut self, _: &LateContext, _: &Crate) {
68         self.spans.clear();
69     }
70
71     fn check_block(&mut self, cx: &LateContext, block: &Block) {
72         if_let_chain!{[
73             self.last.is_none(),
74             let Some(ref expr) = block.expr,
75             match_type(cx, cx.tcx.expr_ty(expr), &paths::REGEX),
76             let Some(span) = is_expn_of(cx, expr.span, "regex"),
77         ], {
78             if !self.spans.contains(&span) {
79                 span_lint(cx,
80                           REGEX_MACRO,
81                           span,
82                           "`regex!(_)` found. \
83                           Please use `Regex::new(_)`, which is faster for now.");
84                 self.spans.insert(span);
85             }
86             self.last = Some(block.id);
87         }}
88     }
89
90     fn check_block_post(&mut self, _: &LateContext, block: &Block) {
91         if self.last.map_or(false, |id| block.id == id) {
92             self.last = None;
93         }
94     }
95
96     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
97         if_let_chain!{[
98             let ExprCall(ref fun, ref args) = expr.node,
99             args.len() == 1,
100             let Some(def) = cx.tcx.def_map.borrow().get(&fun.id),
101         ], {
102             let def_id = def.def_id();
103             if match_def_path(cx, def_id, &paths::REGEX_NEW) {
104                 check_regex(cx, &args[0], true);
105             } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_NEW) {
106                 check_regex(cx, &args[0], false);
107             } else if match_def_path(cx, def_id, &paths::REGEX_SET_NEW) {
108                 check_set(cx, &args[0], true);
109             } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_SET_NEW) {
110                 check_set(cx, &args[0], false);
111             }
112         }}
113     }
114 }
115
116 #[allow(cast_possible_truncation)]
117 fn str_span(base: Span, s: &str, c: usize) -> Span {
118     let mut si = s.char_indices().skip(c);
119
120     match (si.next(), si.next())  {
121         (Some((l, _)), Some((h, _))) => {
122             Span {
123                 lo: base.lo + BytePos(l as u32),
124                 hi: base.lo + BytePos(h as u32),
125                 ..base
126             }
127         }
128         _ => base,
129     }
130 }
131
132 fn const_str(cx: &LateContext, e: &Expr) -> Option<InternedString> {
133     match eval_const_expr_partial(cx.tcx, e, ExprTypeChecked, None) {
134         Ok(ConstVal::Str(r)) => Some(r),
135         _ => None,
136     }
137 }
138
139 fn is_trivial_regex(s: &regex_syntax::Expr) -> Option<&'static str> {
140     use regex_syntax::Expr;
141
142     match *s {
143         Expr::Empty | Expr::StartText | Expr::EndText => Some("the regex is unlikely to be useful as it is"),
144         Expr::Literal { .. } => Some("consider using `str::contains`"),
145         Expr::Concat(ref exprs) => {
146             match exprs.len() {
147                 2 => {
148                     match (&exprs[0], &exprs[1]) {
149                         (&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"),
150                         (&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"),
151                         (&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"),
152                         _ => None,
153                     }
154                 }
155                 3 => {
156                     if let (&Expr::StartText, &Expr::Literal {..}, &Expr::EndText) = (&exprs[0], &exprs[1], &exprs[2]) {
157                         Some("consider using `==` on `str`s")
158                     } else {
159                         None
160                     }
161                 }
162                 _ => None,
163             }
164         }
165         _ => None,
166     }
167 }
168
169 fn check_set(cx: &LateContext, expr: &Expr, utf8: bool) {
170     if_let_chain! {[
171         let ExprAddrOf(_, ref expr) = expr.node,
172         let ExprVec(ref exprs) = expr.node,
173     ], {
174         for expr in exprs {
175             check_regex(cx, expr, utf8);
176         }
177     }}
178 }
179
180 fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
181     let builder = regex_syntax::ExprBuilder::new().unicode(utf8);
182
183     if let ExprLit(ref lit) = expr.node {
184         if let LitKind::Str(ref r, _) = lit.node {
185             match builder.parse(r) {
186                 Ok(r) => {
187                     if let Some(repl) = is_trivial_regex(&r) {
188                         span_help_and_lint(cx, TRIVIAL_REGEX, expr.span,
189                                            "trivial regex",
190                                            &format!("consider using {}", repl));
191                     }
192                 }
193                 Err(e) => {
194                     span_lint(cx,
195                               INVALID_REGEX,
196                               str_span(expr.span, r, e.position()),
197                               &format!("regex syntax error: {}",
198                                        e.description()));
199                 }
200             }
201         }
202     } else if let Some(r) = const_str(cx, expr) {
203         match builder.parse(&r) {
204             Ok(r) => {
205                 if let Some(repl) = is_trivial_regex(&r) {
206                     span_help_and_lint(cx, TRIVIAL_REGEX, expr.span,
207                                        "trivial regex",
208                                        &format!("consider using {}", repl));
209                 }
210             }
211             Err(e) => {
212                 span_lint(cx,
213                           INVALID_REGEX,
214                           expr.span,
215                           &format!("regex syntax error on position {}: {}",
216                                    e.position(),
217                                    e.description()));
218             }
219         }
220     }
221 }