1 use crate::consts::{constant, Constant};
2 use crate::utils::{is_expn_of, match_def_path, match_type, paths, span_help_and_lint, span_lint};
3 use if_chain::if_chain;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_tool_lint, impl_lint_pass};
8 use rustc_data_structures::fx::FxHashSet;
9 use std::convert::TryFrom;
10 use syntax::ast::{LitKind, StrStyle};
11 use syntax::source_map::{BytePos, Span};
13 declare_clippy_lint! {
14 /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
15 /// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
18 /// **Why is this bad?** This will lead to a runtime panic.
20 /// **Known problems:** None.
28 "invalid regular expressions"
31 declare_clippy_lint! {
32 /// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
33 /// creation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`).
35 /// **Why is this bad?** Matching the regex can likely be replaced by `==` or
36 /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
39 /// **Known problems:** None.
43 /// Regex::new("^foobar")
47 "trivial regular expressions"
50 declare_clippy_lint! {
51 /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
52 /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
55 /// **Why is this bad?** Performance, at least for now. The macro version is
56 /// likely to catch up long-term, but for now the dynamic version is faster.
58 /// **Known problems:** None.
66 "use of `regex!(_)` instead of `Regex::new(_)`"
69 #[derive(Clone, Default)]
71 spans: FxHashSet<Span>,
75 impl_lint_pass!(Regex => [INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX]);
77 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Regex {
78 fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
82 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
84 if self.last.is_none();
85 if let Some(ref expr) = block.expr;
86 if match_type(cx, cx.tables.expr_ty(expr), &paths::REGEX);
87 if let Some(span) = is_expn_of(expr.span, "regex");
89 if !self.spans.contains(&span) {
94 Please use `Regex::new(_)`, which is faster for now.");
95 self.spans.insert(span);
97 self.last = Some(block.hir_id);
102 fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
103 if self.last.map_or(false, |id| block.hir_id == id) {
108 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
110 if let ExprKind::Call(ref fun, ref args) = expr.node;
111 if let ExprKind::Path(ref qpath) = fun.node;
113 if let Some(def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
115 if match_def_path(cx, def_id, &paths::REGEX_NEW) ||
116 match_def_path(cx, def_id, &paths::REGEX_BUILDER_NEW) {
117 check_regex(cx, &args[0], true);
118 } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_NEW) ||
119 match_def_path(cx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
120 check_regex(cx, &args[0], false);
121 } else if match_def_path(cx, def_id, &paths::REGEX_SET_NEW) {
122 check_set(cx, &args[0], true);
123 } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_SET_NEW) {
124 check_set(cx, &args[0], false);
131 #[allow(clippy::cast_possible_truncation)] // truncation very unlikely here
132 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
133 let offset = u32::from(offset);
134 let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset);
135 let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + 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, cx.tables, 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::Anchor::*;
149 use regex_syntax::hir::HirKind::*;
151 let is_literal = |e: &[regex_syntax::hir::Hir]| {
152 e.iter().all(|e| match *e.kind() {
159 Empty | Anchor(_) => Some("the regex is unlikely to be useful as it is"),
160 Literal(_) => Some("consider using `str::contains`"),
161 Alternation(ref exprs) => {
162 if exprs.iter().all(|e| e.kind().is_empty()) {
163 Some("the regex is unlikely to be useful as it is")
168 Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
169 (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => {
170 Some("consider using `str::is_empty`")
172 (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
173 Some("consider using `==` on `str`s")
175 (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
176 (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
177 Some("consider using `str::ends_with`")
179 _ if is_literal(exprs) => Some("consider using `str::contains`"),
186 fn check_set<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
188 if let ExprKind::AddrOf(_, ref expr) = expr.node;
189 if let ExprKind::Array(ref exprs) = expr.node;
192 check_regex(cx, expr, utf8);
198 fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
199 let mut parser = regex_syntax::ParserBuilder::new()
201 .allow_invalid_utf8(!utf8)
204 if let ExprKind::Lit(ref lit) = expr.node {
205 if let LitKind::Str(ref r, style) = lit.node {
207 let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
208 match parser.parse(r) {
210 if let Some(repl) = is_trivial_regex(&r) {
211 span_help_and_lint(cx, TRIVIAL_REGEX, expr.span, "trivial regex", repl);
214 Err(regex_syntax::Error::Parse(e)) => {
218 str_span(expr.span, *e.span(), offset),
219 &format!("regex syntax error: {}", e.kind()),
222 Err(regex_syntax::Error::Translate(e)) => {
226 str_span(expr.span, *e.span(), offset),
227 &format!("regex syntax error: {}", e.kind()),
231 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
235 } else if let Some(r) = const_str(cx, expr) {
236 match parser.parse(&r) {
238 if let Some(repl) = is_trivial_regex(&r) {
239 span_help_and_lint(cx, TRIVIAL_REGEX, expr.span, "trivial regex", repl);
242 Err(regex_syntax::Error::Parse(e)) => {
247 &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
250 Err(regex_syntax::Error::Translate(e)) => {
255 &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
259 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));