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