1 use clippy_utils::consts::{constant, Constant};
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
3 use clippy_utils::{match_def_path, paths};
4 use if_chain::if_chain;
5 use rustc_ast::ast::{LitKind, StrStyle};
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_hir::{BorrowKind, Expr, ExprKind, HirId};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 use rustc_span::source_map::{BytePos, Span};
11 use std::convert::TryFrom;
13 declare_clippy_lint! {
15 /// Checks [regex](https://crates.io/crates/regex) creation
16 /// (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`) for correct
19 /// ### Why is this bad?
20 /// This will lead to a runtime panic.
28 "invalid regular expressions"
31 declare_clippy_lint! {
33 /// Checks for trivial [regex](https://crates.io/crates/regex)
34 /// creation (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`).
36 /// ### Why is this bad?
37 /// Matching the regex can likely be replaced by `==` or
38 /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
41 /// ### Known problems
42 /// If the same regex is going to be applied to multiple
43 /// inputs, the precomputations done by `Regex` construction can give
44 /// significantly better performance than any of the `str`-based methods.
48 /// Regex::new("^foobar")
52 "trivial regular expressions"
55 #[derive(Clone, Default)]
57 spans: FxHashSet<Span>,
61 impl_lint_pass!(Regex => [INVALID_REGEX, TRIVIAL_REGEX]);
63 impl<'tcx> LateLintPass<'tcx> for Regex {
64 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
66 if let ExprKind::Call(fun, args) = expr.kind;
67 if let ExprKind::Path(ref qpath) = fun.kind;
69 if let Some(def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
71 if match_def_path(cx, def_id, &paths::REGEX_NEW) ||
72 match_def_path(cx, def_id, &paths::REGEX_BUILDER_NEW) {
73 check_regex(cx, &args[0], true);
74 } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_NEW) ||
75 match_def_path(cx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
76 check_regex(cx, &args[0], false);
77 } else if match_def_path(cx, def_id, &paths::REGEX_SET_NEW) {
78 check_set(cx, &args[0], true);
79 } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_SET_NEW) {
80 check_set(cx, &args[0], false);
87 #[allow(clippy::cast_possible_truncation)] // truncation very unlikely here
89 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
90 let offset = u32::from(offset);
91 let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset);
92 let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + offset);
93 assert!(start <= end);
94 Span::new(start, end, base.ctxt())
97 fn const_str<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> Option<String> {
98 constant(cx, cx.typeck_results(), e).and_then(|(c, _)| match c {
99 Constant::Str(s) => Some(s),
104 fn is_trivial_regex(s: ®ex_syntax::hir::Hir) -> Option<&'static str> {
105 use regex_syntax::hir::Anchor::{EndText, StartText};
106 use regex_syntax::hir::HirKind::{Alternation, Anchor, Concat, Empty, Literal};
108 let is_literal = |e: &[regex_syntax::hir::Hir]| e.iter().all(|e| matches!(*e.kind(), Literal(_)));
111 Empty | Anchor(_) => Some("the regex is unlikely to be useful as it is"),
112 Literal(_) => Some("consider using `str::contains`"),
113 Alternation(ref exprs) => {
114 if exprs.iter().all(|e| e.kind().is_empty()) {
115 Some("the regex is unlikely to be useful as it is")
120 Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
121 (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => {
122 Some("consider using `str::is_empty`")
124 (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
125 Some("consider using `==` on `str`s")
127 (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
128 (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
129 Some("consider using `str::ends_with`")
131 _ if is_literal(exprs) => Some("consider using `str::contains`"),
138 fn check_set<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) {
140 if let ExprKind::AddrOf(BorrowKind::Ref, _, expr) = expr.kind;
141 if let ExprKind::Array(exprs) = expr.kind;
144 check_regex(cx, expr, utf8);
150 fn check_regex<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) {
151 let mut parser = regex_syntax::ParserBuilder::new()
153 .allow_invalid_utf8(!utf8)
156 if let ExprKind::Lit(ref lit) = expr.kind {
157 if let LitKind::Str(ref r, style) = lit.node {
159 let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
160 match parser.parse(r) {
162 if let Some(repl) = is_trivial_regex(&r) {
163 span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
166 Err(regex_syntax::Error::Parse(e)) => {
170 str_span(expr.span, *e.span(), offset),
171 &format!("regex syntax error: {}", e.kind()),
174 Err(regex_syntax::Error::Translate(e)) => {
178 str_span(expr.span, *e.span(), offset),
179 &format!("regex syntax error: {}", e.kind()),
183 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
187 } else if let Some(r) = const_str(cx, expr) {
188 match parser.parse(&r) {
190 if let Some(repl) = is_trivial_regex(&r) {
191 span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
194 Err(regex_syntax::Error::Parse(e)) => {
199 &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
202 Err(regex_syntax::Error::Translate(e)) => {
207 &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
211 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));