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