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