4 use std::collections::HashSet;
6 use syntax::ast::{LitKind, NodeId, StrStyle};
7 use syntax::codemap::{BytePos, Span};
8 use utils::{is_expn_of, match_def_path, match_type, opt_def_id, paths, span_help_and_lint, span_lint};
9 use consts::{constant, Constant};
11 /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
12 /// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
15 /// **Why is this bad?** This will lead to a runtime panic.
17 /// **Known problems:** None.
26 "invalid regular expressions"
29 /// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
30 /// creation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`).
32 /// **Why is this bad?** Matching the regex can likely be replaced by `==` or
33 /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
36 /// **Known problems:** None.
40 /// Regex::new("^foobar")
45 "trivial regular expressions"
48 /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
49 /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
52 /// **Why is this bad?** Performance, at least for now. The macro version is
53 /// likely to catch up long-term, but for now the dynamic version is faster.
55 /// **Known problems:** None.
64 "use of `regex!(_)` instead of `Regex::new(_)`"
67 #[derive(Clone, Default)]
73 impl LintPass for Pass {
74 fn get_lints(&self) -> LintArray {
75 lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
79 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
80 fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
84 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
86 if self.last.is_none();
87 if let Some(ref expr) = block.expr;
88 if match_type(cx, cx.tables.expr_ty(expr), &paths::REGEX);
89 if let Some(span) = is_expn_of(expr.span, "regex");
91 if !self.spans.contains(&span) {
96 Please use `Regex::new(_)`, which is faster for now.");
97 self.spans.insert(span);
99 self.last = Some(block.id);
104 fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
105 if self.last.map_or(false, |id| block.id == id) {
110 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
112 if let ExprCall(ref fun, ref args) = expr.node;
113 if let ExprPath(ref qpath) = fun.node;
115 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, fun.hir_id));
117 if match_def_path(cx.tcx, def_id, &paths::REGEX_NEW) ||
118 match_def_path(cx.tcx, def_id, &paths::REGEX_BUILDER_NEW) {
119 check_regex(cx, &args[0], true);
120 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_NEW) ||
121 match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
122 check_regex(cx, &args[0], false);
123 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_SET_NEW) {
124 check_set(cx, &args[0], true);
125 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_SET_NEW) {
126 check_set(cx, &args[0], false);
133 #[allow(cast_possible_truncation)]
134 fn str_span(base: Span, s: &str, c: usize) -> Span {
135 let mut si = s.char_indices().skip(c);
137 match (si.next(), si.next()) {
138 (Some((l, _)), Some((h, _))) => {
139 Span::new(base.lo() + BytePos(l as u32), base.lo() + BytePos(h as u32), base.ctxt())
145 fn const_str<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) -> Option<String> {
146 constant(cx, e).and_then(|(c, _)| match c {
147 Constant::Str(s) => Some(s),
152 fn is_trivial_regex(s: ®ex_syntax::Expr) -> Option<&'static str> {
153 use regex_syntax::Expr;
156 Expr::Empty | Expr::StartText | Expr::EndText => Some("the regex is unlikely to be useful as it is"),
157 Expr::Literal { .. } => Some("consider using `str::contains`"),
158 Expr::Concat(ref exprs) => match exprs.len() {
159 2 => match (&exprs[0], &exprs[1]) {
160 (&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"),
161 (&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"),
162 (&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"),
165 3 => if let (&Expr::StartText, &Expr::Literal { .. }, &Expr::EndText) = (&exprs[0], &exprs[1], &exprs[2]) {
166 Some("consider using `==` on `str`s")
176 fn check_set<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
178 if let ExprAddrOf(_, ref expr) = expr.node;
179 if let ExprArray(ref exprs) = expr.node;
182 check_regex(cx, expr, utf8);
188 fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
189 let builder = regex_syntax::ExprBuilder::new().unicode(utf8);
191 if let ExprLit(ref lit) = expr.node {
192 if let LitKind::Str(ref r, style) = lit.node {
194 let offset = if let StrStyle::Raw(n) = style { 1 + n } else { 0 };
195 match builder.parse(r) {
196 Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
202 &format!("consider using {}", repl),
209 str_span(expr.span, r, e.position() + offset),
210 &format!("regex syntax error: {}", e.description()),
215 } else if let Some(r) = const_str(cx, expr) {
216 match builder.parse(&r) {
217 Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
223 &format!("consider using {}", repl),
231 &format!("regex syntax error on position {}: {}", e.position(), e.description()),