2 use crate::rustc::hir::*;
3 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use crate::rustc::{declare_tool_lint, lint_array};
5 use crate::rustc_data_structures::fx::FxHashSet;
6 use if_chain::if_chain;
7 use crate::syntax::ast::{LitKind, NodeId, StrStyle};
8 use crate::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};
12 /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
13 /// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
16 /// **Why is this bad?** This will lead to a runtime panic.
18 /// **Known problems:** None.
24 declare_clippy_lint! {
27 "invalid regular expressions"
30 /// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
31 /// creation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`).
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`
37 /// **Known problems:** None.
41 /// Regex::new("^foobar")
43 declare_clippy_lint! {
46 "trivial regular expressions"
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
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.
56 /// **Known problems:** None.
62 declare_clippy_lint! {
65 "use of `regex!(_)` instead of `Regex::new(_)`"
68 #[derive(Clone, Default)]
70 spans: FxHashSet<Span>,
74 impl LintPass for Pass {
75 fn get_lints(&self) -> LintArray {
76 lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
80 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
81 fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
85 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
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");
92 if !self.spans.contains(&span) {
97 Please use `Regex::new(_)`, which is faster for now.");
98 self.spans.insert(span);
100 self.last = Some(block.id);
105 fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
106 if self.last.map_or(false, |id| block.id == id) {
111 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
113 if let ExprKind::Call(ref fun, ref args) = expr.node;
114 if let ExprKind::Path(ref qpath) = fun.node;
116 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, fun.hir_id));
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);
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())
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),
149 fn is_trivial_regex(s: ®ex_syntax::hir::Hir) -> Option<&'static str> {
150 use regex_syntax::hir::HirKind::*;
151 use regex_syntax::hir::Anchor::*;
153 let is_literal = |e: &[regex_syntax::hir::Hir]| e.iter().all(|e| match *e.kind() {
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")
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`"),
179 fn check_set<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
181 if let ExprKind::AddrOf(_, ref expr) = expr.node;
182 if let ExprKind::Array(ref exprs) = expr.node;
185 check_regex(cx, expr, utf8);
191 fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
192 let mut parser = regex_syntax::ParserBuilder::new()
194 .allow_invalid_utf8(!utf8)
197 if let ExprKind::Lit(ref lit) = expr.node {
198 if let LitKind::Str(ref r, style) = lit.node {
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) {
211 Err(regex_syntax::Error::Parse(e)) => {
215 str_span(expr.span, *e.span(), offset),
216 &format!("regex syntax error: {}", e.kind()),
219 Err(regex_syntax::Error::Translate(e)) => {
223 str_span(expr.span, *e.span(), offset),
224 &format!("regex syntax error: {}", e.kind()),
232 &format!("regex syntax error: {}", e),
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) {
248 Err(regex_syntax::Error::Parse(e)) => {
253 &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
256 Err(regex_syntax::Error::Translate(e)) => {
261 &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
269 &format!("regex syntax error: {}", e),