4 use rustc::middle::const_val::ConstVal;
5 use rustc_const_eval::EvalHint::ExprTypeChecked;
6 use rustc_const_eval::eval_const_expr_partial;
7 use std::collections::HashSet;
9 use syntax::ast::{LitKind, NodeId};
10 use syntax::codemap::{Span, BytePos};
11 use syntax::parse::token::InternedString;
12 use utils::{is_expn_of, match_path, match_type, paths, span_lint, span_help_and_lint};
14 /// **What it does:** This lint checks `Regex::new(_)` invocations for correct regex syntax.
16 /// **Why is this bad?** This will lead to a runtime panic.
18 /// **Known problems:** None.
20 /// **Example:** `Regex::new("|")`
24 "finds invalid regular expressions in `Regex::new(_)` invocations"
27 /// **What it does:** This lint checks for `Regex::new(_)` invocations with trivial regex.
29 /// **Why is this bad?** This can likely be replaced by `==` or `str::starts_with`,
30 /// `str::ends_with` or `std::contains` or other `str` methods.
32 /// **Known problems:** None.
34 /// **Example:** `Regex::new("^foobar")`
38 "finds trivial regular expressions in `Regex::new(_)` invocations"
41 /// **What it does:** This lint checks for usage of `regex!(_)` which as of now is usually slower than `Regex::new(_)` unless called in a loop (which is a bad idea anyway).
43 /// **Why is this bad?** Performance, at least for now. The macro version is likely to catch up long-term, but for now the dynamic version is faster.
45 /// **Known problems:** None
47 /// **Example:** `regex!("foo|bar")`
51 "finds use of `regex!(_)`, suggests `Regex::new(_)` instead"
54 #[derive(Clone, Default)]
55 pub struct RegexPass {
60 impl LintPass for RegexPass {
61 fn get_lints(&self) -> LintArray {
62 lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
66 impl LateLintPass for RegexPass {
67 fn check_crate(&mut self, _: &LateContext, _: &Crate) {
71 fn check_block(&mut self, cx: &LateContext, block: &Block) {
74 let Some(ref expr) = block.expr,
75 match_type(cx, cx.tcx.expr_ty(expr), &paths::REGEX),
76 let Some(span) = is_expn_of(cx, expr.span, "regex"),
78 if !self.spans.contains(&span) {
83 Please use `Regex::new(_)`, which is faster for now.");
84 self.spans.insert(span);
86 self.last = Some(block.id);
90 fn check_block_post(&mut self, _: &LateContext, block: &Block) {
91 if self.last.map_or(false, |id| block.id == id) {
96 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
98 let ExprCall(ref fun, ref args) = expr.node,
99 let ExprPath(_, ref path) = fun.node,
100 match_path(path, &paths::REGEX_NEW) && args.len() == 1
102 if let ExprLit(ref lit) = args[0].node {
103 if let LitKind::Str(ref r, _) = lit.node {
104 match regex_syntax::Expr::parse(r) {
106 if let Some(repl) = is_trivial_regex(&r) {
107 span_help_and_lint(cx, TRIVIAL_REGEX, args[0].span,
109 &format!("consider using {}", repl));
115 str_span(args[0].span, &r, e.position()),
116 &format!("regex syntax error: {}",
121 } else if let Some(r) = const_str(cx, &*args[0]) {
122 match regex_syntax::Expr::parse(&r) {
124 if let Some(repl) = is_trivial_regex(&r) {
125 span_help_and_lint(cx, TRIVIAL_REGEX, args[0].span,
127 &format!("consider using {}", repl));
134 &format!("regex syntax error on position {}: {}",
144 #[allow(cast_possible_truncation)]
145 fn str_span(base: Span, s: &str, c: usize) -> Span {
146 let mut si = s.char_indices().skip(c);
148 match (si.next(), si.next()) {
149 (Some((l, _)), Some((h, _))) => {
151 lo: base.lo + BytePos(l as u32),
152 hi: base.lo + BytePos(h as u32),
160 fn const_str(cx: &LateContext, e: &Expr) -> Option<InternedString> {
161 match eval_const_expr_partial(cx.tcx, e, ExprTypeChecked, None) {
162 Ok(ConstVal::Str(r)) => Some(r),
167 fn is_trivial_regex(s: ®ex_syntax::Expr) -> Option<&'static str> {
168 use regex_syntax::Expr;
171 Expr::Empty | Expr::StartText | Expr::EndText => Some("the regex is unlikely to be useful as it is"),
172 Expr::Literal { .. } => Some("consider using `str::contains`"),
173 Expr::Concat(ref exprs) => {
176 match (&exprs[0], &exprs[1]) {
177 (&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"),
178 (&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"),
179 (&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"),
184 if let (&Expr::StartText, &Expr::Literal {..}, &Expr::EndText) = (&exprs[0], &exprs[1], &exprs[2]) {
185 Some("consider using `==` on `str`s")