|
| 1 | +use regex_syntax; |
| 2 | +use std::error::Error; |
| 3 | +use syntax::ast::Lit_::LitStr; |
| 4 | +use syntax::codemap::{Span, BytePos}; |
| 5 | +use syntax::parse::token::InternedString; |
| 6 | +use rustc_front::hir::*; |
| 7 | +use rustc::middle::const_eval::{eval_const_expr_partial, ConstVal}; |
| 8 | +use rustc::middle::const_eval::EvalHint::ExprTypeChecked; |
| 9 | +use rustc::lint::*; |
| 10 | + |
| 11 | +use utils::{match_path, REGEX_NEW_PATH, span_lint}; |
| 12 | + |
| 13 | +/// **What it does:** This lint checks `Regex::new(_)` invocations for correct regex syntax. It is `deny` by default. |
| 14 | +/// |
| 15 | +/// **Why is this bad?** This will lead to a runtime panic. |
| 16 | +/// |
| 17 | +/// **Known problems:** None. |
| 18 | +/// |
| 19 | +/// **Example:** `Regex::new("|")` |
| 20 | +declare_lint! { |
| 21 | + pub INVALID_REGEX, |
| 22 | + Deny, |
| 23 | + "finds invalid regular expressions in `Regex::new(_)` invocations" |
| 24 | +} |
| 25 | + |
| 26 | +#[derive(Copy,Clone)] |
| 27 | +pub struct RegexPass; |
| 28 | + |
| 29 | +impl LintPass for RegexPass { |
| 30 | + fn get_lints(&self) -> LintArray { |
| 31 | + lint_array!(INVALID_REGEX) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl LateLintPass for RegexPass { |
| 36 | + fn check_expr(&mut self, cx: &LateContext, expr: &Expr) { |
| 37 | + if_let_chain!{[ |
| 38 | + let ExprCall(ref fun, ref args) = expr.node, |
| 39 | + let ExprPath(_, ref path) = fun.node, |
| 40 | + match_path(path, ®EX_NEW_PATH) && args.len() == 1 |
| 41 | + ], { |
| 42 | + if let ExprLit(ref lit) = args[0].node { |
| 43 | + if let LitStr(ref r, _) = lit.node { |
| 44 | + if let Err(e) = regex_syntax::Expr::parse(r) { |
| 45 | + span_lint(cx, |
| 46 | + INVALID_REGEX, |
| 47 | + str_span(args[0].span, &r, e.position()), |
| 48 | + &format!("Regex syntax error: {}", |
| 49 | + e.description())); |
| 50 | + } |
| 51 | + } |
| 52 | + } else { |
| 53 | + if_let_chain!{[ |
| 54 | + let Some(r) = const_str(cx, &*args[0]), |
| 55 | + let Err(e) = regex_syntax::Expr::parse(&r) |
| 56 | + ], { |
| 57 | + span_lint(cx, |
| 58 | + INVALID_REGEX, |
| 59 | + args[0].span, |
| 60 | + &format!("Regex syntax error on position {}: {}", |
| 61 | + e.position(), |
| 62 | + e.description())); |
| 63 | + }} |
| 64 | + } |
| 65 | + }} |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +#[allow(cast_possible_truncation)] |
| 70 | +fn str_span(base: Span, s: &str, c: usize) -> Span { |
| 71 | + let lo = match s.char_indices().nth(c) { |
| 72 | + Some((b, _)) => base.lo + BytePos(b as u32), |
| 73 | + _ => base.hi |
| 74 | + }; |
| 75 | + Span{ lo: lo, hi: lo, ..base } |
| 76 | +} |
| 77 | + |
| 78 | +fn const_str(cx: &LateContext, e: &Expr) -> Option<InternedString> { |
| 79 | + match eval_const_expr_partial(cx.tcx, e, ExprTypeChecked, None) { |
| 80 | + Ok(ConstVal::Str(r)) => Some(r), |
| 81 | + _ => None |
| 82 | + } |
| 83 | +} |
0 commit comments