]> git.lizzy.rs Git - rust.git/blob - src/regex.rs
72a33757027e3aadbd54786c344d2bda68f7b4b5
[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_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             let ExprPath(_, ref path) = fun.node,
100             match_path(path, &paths::REGEX_NEW) && args.len() == 1
101         ], {
102             if let ExprLit(ref lit) = args[0].node {
103                 if let LitKind::Str(ref r, _) = lit.node {
104                     match regex_syntax::Expr::parse(r) {
105                         Ok(r) => {
106                             if let Some(repl) = is_trivial_regex(&r) {
107                                 span_help_and_lint(cx, TRIVIAL_REGEX, args[0].span,
108                                                    "trivial regex",
109                                                    &format!("consider using {}", repl));
110                             }
111                         }
112                         Err(e) => {
113                             span_lint(cx,
114                                       INVALID_REGEX,
115                                       str_span(args[0].span, &r, e.position()),
116                                       &format!("regex syntax error: {}",
117                                                e.description()));
118                         }
119                     }
120                 }
121             } else if let Some(r) = const_str(cx, &*args[0]) {
122                 match regex_syntax::Expr::parse(&r) {
123                     Ok(r) => {
124                         if let Some(repl) = is_trivial_regex(&r) {
125                             span_help_and_lint(cx, TRIVIAL_REGEX, args[0].span,
126                                                "trivial regex",
127                                                &format!("consider using {}", repl));
128                         }
129                     }
130                     Err(e) => {
131                         span_lint(cx,
132                                   INVALID_REGEX,
133                                   args[0].span,
134                                   &format!("regex syntax error on position {}: {}",
135                                            e.position(),
136                                            e.description()));
137                     }
138                 }
139             }
140         }}
141     }
142 }
143
144 #[allow(cast_possible_truncation)]
145 fn str_span(base: Span, s: &str, c: usize) -> Span {
146     let lo = match s.char_indices().nth(c) {
147         Some((b, _)) => base.lo + BytePos(b as u32),
148         _ => base.hi,
149     };
150     Span {
151         lo: lo,
152         hi: lo,
153         ..base
154     }
155 }
156
157 fn const_str(cx: &LateContext, e: &Expr) -> Option<InternedString> {
158     match eval_const_expr_partial(cx.tcx, e, ExprTypeChecked, None) {
159         Ok(ConstVal::Str(r)) => Some(r),
160         _ => None,
161     }
162 }
163
164 fn is_trivial_regex(s: &regex_syntax::Expr) -> Option<&'static str> {
165     use regex_syntax::Expr;
166
167     match *s {
168         Expr::Empty | Expr::StartText | Expr::EndText => Some("the regex is unlikely to be useful as it is"),
169         Expr::Literal { .. } => Some("consider using `str::contains`"),
170         Expr::Concat(ref exprs) => {
171             match exprs.len() {
172                 2 => {
173                     match (&exprs[0], &exprs[1]) {
174                         (&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"),
175                         (&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"),
176                         (&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"),
177                         _ => None,
178                     }
179                 }
180                 3 => {
181                     if let (&Expr::StartText, &Expr::Literal {..}, &Expr::EndText) = (&exprs[0], &exprs[1], &exprs[2]) {
182                         Some("consider using `==` on `str`s")
183                     } else {
184                         None
185                     }
186                 }
187                 _ => None,
188             }
189         }
190         _ => None,
191     }
192 }