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