4 use rustc::middle::const_val::ConstVal;
5 use rustc_const_eval::ConstContext;
6 use rustc::ty::subst::Substs;
7 use std::collections::HashSet;
9 use syntax::ast::{LitKind, NodeId};
10 use syntax::codemap::{Span, BytePos};
11 use syntax::symbol::InternedString;
12 use utils::{is_expn_of, match_def_path, match_type, paths, span_lint, span_help_and_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.
29 "invalid regular expressions"
32 /// **What it does:** Checks for trivial [regex] creation (with `Regex::new`,
33 /// `RegexBuilder::new` or `RegexSet::new`).
35 /// [regex]: https://crates.io/crates/regex
37 /// **Why is this bad?** 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:** None.
45 /// Regex::new("^foobar")
50 "trivial regular expressions"
53 /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
54 /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
57 /// **Why is this bad?** Performance, at least for now. The macro version is
58 /// likely to catch up long-term, but for now the dynamic version is faster.
60 /// **Known problems:** None.
69 "use of `regex!(_)` instead of `Regex::new(_)`"
72 #[derive(Clone, Default)]
78 impl LintPass for Pass {
79 fn get_lints(&self) -> LintArray {
80 lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
84 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
85 fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
89 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
92 let Some(ref expr) = block.expr,
93 match_type(cx, cx.tables.expr_ty(expr), &paths::REGEX),
94 let Some(span) = is_expn_of(expr.span, "regex"),
96 if !self.spans.contains(&span) {
100 "`regex!(_)` found. \
101 Please use `Regex::new(_)`, which is faster for now.");
102 self.spans.insert(span);
104 self.last = Some(block.id);
108 fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
109 if self.last.map_or(false, |id| block.id == id) {
114 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
116 let ExprCall(ref fun, ref args) = expr.node,
117 let ExprPath(ref qpath) = fun.node,
120 let def_id = cx.tables.qpath_def(qpath, fun.hir_id).def_id();
121 if match_def_path(cx.tcx, def_id, &paths::REGEX_NEW) ||
122 match_def_path(cx.tcx, def_id, &paths::REGEX_BUILDER_NEW) {
123 check_regex(cx, &args[0], true);
124 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_NEW) ||
125 match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
126 check_regex(cx, &args[0], false);
127 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_SET_NEW) {
128 check_set(cx, &args[0], true);
129 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_SET_NEW) {
130 check_set(cx, &args[0], false);
136 #[allow(cast_possible_truncation)]
137 fn str_span(base: Span, s: &str, c: usize) -> Span {
138 let mut si = s.char_indices().skip(c);
140 match (si.next(), si.next()) {
141 (Some((l, _)), Some((h, _))) => {
142 Span::new(base.lo() + BytePos(l as u32), base.lo() + BytePos(h as u32), base.ctxt())
148 fn const_str(cx: &LateContext, e: &Expr) -> Option<InternedString> {
149 let parent_item = cx.tcx.hir.get_parent(e.id);
150 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
151 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
152 match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(e) {
153 Ok(ConstVal::Str(r)) => Some(r),
158 fn is_trivial_regex(s: ®ex_syntax::Expr) -> Option<&'static str> {
159 use regex_syntax::Expr;
162 Expr::Empty | Expr::StartText | Expr::EndText => Some("the regex is unlikely to be useful as it is"),
163 Expr::Literal { .. } => Some("consider using `str::contains`"),
164 Expr::Concat(ref exprs) => {
167 match (&exprs[0], &exprs[1]) {
168 (&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"),
169 (&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"),
170 (&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"),
175 if let (&Expr::StartText, &Expr::Literal { .. }, &Expr::EndText) =
176 (&exprs[0], &exprs[1], &exprs[2])
178 Some("consider using `==` on `str`s")
190 fn check_set(cx: &LateContext, expr: &Expr, utf8: bool) {
192 let ExprAddrOf(_, ref expr) = expr.node,
193 let ExprArray(ref exprs) = expr.node,
196 check_regex(cx, expr, utf8);
201 fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
202 let builder = regex_syntax::ExprBuilder::new().unicode(utf8);
204 if let ExprLit(ref lit) = expr.node {
205 if let LitKind::Str(ref r, _) = lit.node {
207 match builder.parse(r) {
209 if let Some(repl) = is_trivial_regex(&r) {
215 &format!("consider using {}", repl),
223 str_span(expr.span, r, e.position()),
224 &format!("regex syntax error: {}", e.description()),
229 } else if let Some(r) = const_str(cx, expr) {
230 match builder.parse(&r) {
232 if let Some(repl) = is_trivial_regex(&r) {
238 &format!("consider using {}", repl),
247 &format!("regex syntax error on position {}: {}", e.position(), e.description()),