4 use std::collections::HashSet;
5 use syntax::ast::{LitKind, NodeId, StrStyle};
6 use syntax::codemap::{BytePos, Span};
7 use utils::{is_expn_of, match_def_path, match_type, opt_def_id, paths, span_help_and_lint, span_lint};
8 use consts::{constant, Constant};
10 /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
11 /// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
14 /// **Why is this bad?** This will lead to a runtime panic.
16 /// **Known problems:** None.
22 declare_clippy_lint! {
25 "invalid regular expressions"
28 /// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
29 /// creation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`).
31 /// **Why is this bad?** Matching the regex can likely be replaced by `==` or
32 /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
35 /// **Known problems:** None.
39 /// Regex::new("^foobar")
41 declare_clippy_lint! {
44 "trivial regular expressions"
47 /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
48 /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
51 /// **Why is this bad?** Performance, at least for now. The macro version is
52 /// likely to catch up long-term, but for now the dynamic version is faster.
54 /// **Known problems:** None.
60 declare_clippy_lint! {
63 "use of `regex!(_)` instead of `Regex::new(_)`"
66 #[derive(Clone, Default)]
72 impl LintPass for Pass {
73 fn get_lints(&self) -> LintArray {
74 lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
78 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
79 fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
83 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
85 if self.last.is_none();
86 if let Some(ref expr) = block.expr;
87 if match_type(cx, cx.tables.expr_ty(expr), &paths::REGEX);
88 if let Some(span) = is_expn_of(expr.span, "regex");
90 if !self.spans.contains(&span) {
95 Please use `Regex::new(_)`, which is faster for now.");
96 self.spans.insert(span);
98 self.last = Some(block.id);
103 fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
104 if self.last.map_or(false, |id| block.id == id) {
109 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
111 if let ExprCall(ref fun, ref args) = expr.node;
112 if let ExprPath(ref qpath) = fun.node;
114 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, fun.hir_id));
116 if match_def_path(cx.tcx, def_id, &paths::REGEX_NEW) ||
117 match_def_path(cx.tcx, def_id, &paths::REGEX_BUILDER_NEW) {
118 check_regex(cx, &args[0], true);
119 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_NEW) ||
120 match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
121 check_regex(cx, &args[0], false);
122 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_SET_NEW) {
123 check_set(cx, &args[0], true);
124 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_SET_NEW) {
125 check_set(cx, &args[0], false);
132 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: usize) -> Span {
133 let offset = offset as u32;
134 let end = base.lo() + BytePos(c.end.offset as u32 + offset);
135 let start = base.lo() + BytePos(c.start.offset as u32 + offset);
136 assert!(start <= end);
137 Span::new(start, end, base.ctxt())
140 fn const_str<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) -> Option<String> {
141 constant(cx, e).and_then(|(c, _)| match c {
142 Constant::Str(s) => Some(s),
147 fn is_trivial_regex(s: ®ex_syntax::hir::Hir) -> Option<&'static str> {
148 use regex_syntax::hir::HirKind::*;
149 use regex_syntax::hir::Anchor::*;
151 let is_literal = |e: &[regex_syntax::hir::Hir]| e.iter().all(|e| match *e.kind() {
158 Anchor(_) => Some("the regex is unlikely to be useful as it is"),
159 Literal(_) => Some("consider using `str::contains`"),
160 Alternation(ref exprs) => if exprs.iter().all(|e| e.kind().is_empty()) {
161 Some("the regex is unlikely to be useful as it is")
165 Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
166 (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => Some("consider using `str::is_empty`"),
167 (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => Some("consider using `==` on `str`s"),
168 (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
169 (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => Some("consider using `str::ends_with`"),
170 _ if is_literal(exprs) => Some("consider using `str::contains`"),
177 fn check_set<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
179 if let ExprAddrOf(_, ref expr) = expr.node;
180 if let ExprArray(ref exprs) = expr.node;
183 check_regex(cx, expr, utf8);
189 fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
190 let mut parser = regex_syntax::ParserBuilder::new()
192 .allow_invalid_utf8(!utf8)
195 if let ExprLit(ref lit) = expr.node {
196 if let LitKind::Str(ref r, style) = lit.node {
198 let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
199 match parser.parse(r) {
200 Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
209 Err(regex_syntax::Error::Parse(e)) => {
213 str_span(expr.span, *e.span(), offset),
214 &format!("regex syntax error: {}", e.kind()),
217 Err(regex_syntax::Error::Translate(e)) => {
221 str_span(expr.span, *e.span(), offset),
222 &format!("regex syntax error: {}", e.kind()),
230 &format!("regex syntax error: {}", e),
235 } else if let Some(r) = const_str(cx, expr) {
236 match parser.parse(&r) {
237 Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
246 Err(regex_syntax::Error::Parse(e)) => {
251 &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
254 Err(regex_syntax::Error::Translate(e)) => {
259 &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
267 &format!("regex syntax error: {}", e),