rust-clippy/clippy_lints/src/regex.rs

253 lines
8.1 KiB
Rust
Raw Normal View History

2016-02-04 23:36:06 +00:00
use regex_syntax;
use rustc::hir::*;
2016-02-24 16:38:57 +00:00
use rustc::lint::*;
use rustc::middle::const_val::ConstVal;
2017-01-13 16:04:56 +00:00
use rustc_const_eval::ConstContext;
2017-07-31 10:37:38 +00:00
use rustc::ty::subst::Substs;
2016-02-08 22:48:04 +00:00
use std::collections::HashSet;
2016-02-24 16:38:57 +00:00
use std::error::Error;
2016-02-14 15:55:02 +00:00
use syntax::ast::{LitKind, NodeId};
2016-02-05 15:48:35 +00:00
use syntax::codemap::{Span, BytePos};
use syntax::symbol::InternedString;
2016-05-25 15:15:19 +00:00
use utils::{is_expn_of, match_def_path, match_type, paths, span_lint, span_help_and_lint};
2016-02-04 23:36:06 +00:00
2017-09-01 20:43:34 +00:00
/// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
/// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
/// regex syntax.
2016-07-15 22:25:44 +00:00
///
2016-02-04 23:36:06 +00:00
/// **Why is this bad?** This will lead to a runtime panic.
///
/// **Known problems:** None.
///
2016-07-15 22:25:44 +00:00
/// **Example:**
/// ```rust
/// Regex::new("|")
/// ```
2016-02-04 23:36:06 +00:00
declare_lint! {
pub INVALID_REGEX,
Deny,
"invalid regular expressions"
2016-02-04 23:36:06 +00:00
}
/// **What it does:** Checks for trivial [regex] creation (with `Regex::new`,
2016-05-25 22:08:31 +00:00
/// `RegexBuilder::new` or `RegexSet::new`).
2016-02-05 22:10:48 +00:00
///
2016-07-15 22:25:44 +00:00
/// [regex]: https://crates.io/crates/regex
///
/// **Why is this bad?** Matching the regex can likely be replaced by `==` or
/// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
/// methods.
2016-02-05 22:10:48 +00:00
///
/// **Known problems:** None.
///
2016-07-15 22:25:44 +00:00
/// **Example:**
/// ```rust
/// Regex::new("^foobar")
/// ```
2016-02-05 22:10:48 +00:00
declare_lint! {
pub TRIVIAL_REGEX,
Warn,
"trivial regular expressions"
2016-02-05 22:10:48 +00:00
}
/// **What it does:** 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).
2016-02-07 21:50:54 +00:00
///
/// **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.
2016-02-07 21:50:54 +00:00
///
/// **Known problems:** None.
2016-02-07 21:50:54 +00:00
///
2016-07-15 22:25:44 +00:00
/// **Example:**
/// ```rust
/// regex!("foo|bar")
/// ```
2016-02-07 21:50:54 +00:00
declare_lint! {
pub REGEX_MACRO,
2016-02-08 22:48:04 +00:00
Warn,
"use of `regex!(_)` instead of `Regex::new(_)`"
2016-02-07 21:50:54 +00:00
}
2016-02-14 15:55:02 +00:00
#[derive(Clone, Default)]
2016-06-10 14:17:20 +00:00
pub struct Pass {
2016-02-14 15:55:02 +00:00
spans: HashSet<Span>,
2016-02-24 16:38:57 +00:00
last: Option<NodeId>,
2016-02-14 15:55:02 +00:00
}
2016-02-04 23:36:06 +00:00
2016-06-10 14:17:20 +00:00
impl LintPass for Pass {
2016-02-04 23:36:06 +00:00
fn get_lints(&self) -> LintArray {
2016-02-07 21:50:54 +00:00
lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
2016-02-04 23:36:06 +00:00
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
2016-02-14 15:55:02 +00:00
self.spans.clear();
2016-02-07 21:50:54 +00:00
}
fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
2016-02-14 15:55:02 +00:00
if_let_chain!{[
self.last.is_none(),
let Some(ref expr) = block.expr,
2017-01-13 16:04:56 +00:00
match_type(cx, cx.tables.expr_ty(expr), &paths::REGEX),
let Some(span) = is_expn_of(expr.span, "regex"),
2016-02-14 15:55:02 +00:00
], {
if !self.spans.contains(&span) {
span_lint(cx,
REGEX_MACRO,
span,
"`regex!(_)` found. \
Please use `Regex::new(_)`, which is faster for now.");
2016-05-25 15:15:19 +00:00
self.spans.insert(span);
2016-02-14 15:55:02 +00:00
}
self.last = Some(block.id);
}}
}
2016-02-24 16:38:57 +00:00
fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
2016-02-14 15:55:02 +00:00
if self.last.map_or(false, |id| block.id == id) {
2016-02-24 16:38:57 +00:00
self.last = None;
2016-02-14 15:55:02 +00:00
}
}
2016-02-07 21:50:54 +00:00
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
2016-02-04 23:36:06 +00:00
if_let_chain!{[
let ExprCall(ref fun, ref args) = expr.node,
let ExprPath(ref qpath) = fun.node,
2016-05-25 15:15:19 +00:00
args.len() == 1,
2016-02-04 23:36:06 +00:00
], {
2017-08-15 09:10:49 +00:00
let def_id = cx.tables.qpath_def(qpath, fun.hir_id).def_id();
2017-01-13 16:04:56 +00:00
if match_def_path(cx.tcx, def_id, &paths::REGEX_NEW) ||
match_def_path(cx.tcx, def_id, &paths::REGEX_BUILDER_NEW) {
2016-05-25 15:15:19 +00:00
check_regex(cx, &args[0], true);
2017-01-13 16:04:56 +00:00
} else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_NEW) ||
match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
2016-05-25 19:36:51 +00:00
check_regex(cx, &args[0], false);
2017-01-13 16:04:56 +00:00
} else if match_def_path(cx.tcx, def_id, &paths::REGEX_SET_NEW) {
2016-05-25 15:15:19 +00:00
check_set(cx, &args[0], true);
2017-01-13 16:04:56 +00:00
} else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_SET_NEW) {
2016-05-25 15:15:19 +00:00
check_set(cx, &args[0], false);
2016-02-05 15:48:35 +00:00
}
2016-02-04 23:36:06 +00:00
}}
}
}
2016-02-05 15:48:35 +00:00
#[allow(cast_possible_truncation)]
fn str_span(base: Span, s: &str, c: usize) -> Span {
2016-05-07 22:56:23 +00:00
let mut si = s.char_indices().skip(c);
match (si.next(), si.next()) {
2016-05-07 22:56:23 +00:00
(Some((l, _)), Some((h, _))) => {
2017-09-03 21:15:15 +00:00
Span::new(base.lo() + BytePos(l as u32), base.lo() + BytePos(h as u32), base.ctxt())
2016-12-20 17:21:30 +00:00
},
2016-05-07 22:56:23 +00:00
_ => base,
2016-02-29 11:19:32 +00:00
}
2016-02-05 15:48:35 +00:00
}
fn const_str(cx: &LateContext, e: &Expr) -> Option<InternedString> {
2017-07-31 10:37:38 +00:00
let parent_item = cx.tcx.hir.get_parent(e.id);
let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(e) {
2016-02-05 15:48:35 +00:00
Ok(ConstVal::Str(r)) => Some(r),
2016-02-24 16:38:57 +00:00
_ => None,
2016-02-05 15:48:35 +00:00
}
}
2016-02-05 22:10:48 +00:00
2016-02-06 17:06:39 +00:00
fn is_trivial_regex(s: &regex_syntax::Expr) -> Option<&'static str> {
use regex_syntax::Expr;
2016-02-05 22:10:48 +00:00
2016-02-06 17:06:39 +00:00
match *s {
Expr::Empty | Expr::StartText | Expr::EndText => Some("the regex is unlikely to be useful as it is"),
2016-04-14 18:14:03 +00:00
Expr::Literal { .. } => Some("consider using `str::contains`"),
2016-02-06 17:06:39 +00:00
Expr::Concat(ref exprs) => {
match exprs.len() {
2016-02-24 16:38:57 +00:00
2 => {
match (&exprs[0], &exprs[1]) {
(&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"),
2016-04-14 18:14:03 +00:00
(&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"),
(&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"),
2016-02-24 16:38:57 +00:00
_ => None,
}
2016-12-20 17:21:30 +00:00
},
2016-02-06 17:06:39 +00:00
3 => {
2016-12-20 17:21:30 +00:00
if let (&Expr::StartText, &Expr::Literal { .. }, &Expr::EndText) =
2017-08-09 07:30:56 +00:00
(&exprs[0], &exprs[1], &exprs[2])
{
2016-02-06 17:06:39 +00:00
Some("consider using `==` on `str`s")
2016-02-24 16:38:57 +00:00
} else {
2016-02-06 17:06:39 +00:00
None
}
2016-12-20 17:21:30 +00:00
},
2016-02-06 17:06:39 +00:00
_ => None,
}
2016-12-20 17:21:30 +00:00
},
2016-02-06 17:06:39 +00:00
_ => None,
2016-02-05 22:10:48 +00:00
}
}
2016-05-25 15:15:19 +00:00
fn check_set(cx: &LateContext, expr: &Expr, utf8: bool) {
if_let_chain! {[
let ExprAddrOf(_, ref expr) = expr.node,
let ExprArray(ref exprs) = expr.node,
2016-05-25 15:15:19 +00:00
], {
for expr in exprs {
check_regex(cx, expr, utf8);
}
}}
}
fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
let builder = regex_syntax::ExprBuilder::new().unicode(utf8);
if let ExprLit(ref lit) = expr.node {
if let LitKind::Str(ref r, _) = lit.node {
let r = &r.as_str();
2016-05-25 15:15:19 +00:00
match builder.parse(r) {
Ok(r) => {
if let Some(repl) = is_trivial_regex(&r) {
2017-08-09 07:30:56 +00:00
span_help_and_lint(
cx,
TRIVIAL_REGEX,
expr.span,
"trivial regex",
&format!("consider using {}", repl),
);
2016-05-25 15:15:19 +00:00
}
2016-12-20 17:21:30 +00:00
},
2016-05-25 15:15:19 +00:00
Err(e) => {
2017-08-09 07:30:56 +00:00
span_lint(
cx,
INVALID_REGEX,
str_span(expr.span, r, e.position()),
&format!("regex syntax error: {}", e.description()),
);
2016-12-20 17:21:30 +00:00
},
2016-05-25 15:15:19 +00:00
}
}
} else if let Some(r) = const_str(cx, expr) {
match builder.parse(&r) {
Ok(r) => {
if let Some(repl) = is_trivial_regex(&r) {
2017-08-09 07:30:56 +00:00
span_help_and_lint(
cx,
TRIVIAL_REGEX,
expr.span,
"trivial regex",
&format!("consider using {}", repl),
);
2016-05-25 15:15:19 +00:00
}
2016-12-20 17:21:30 +00:00
},
2016-05-25 15:15:19 +00:00
Err(e) => {
2017-08-09 07:30:56 +00:00
span_lint(
cx,
INVALID_REGEX,
expr.span,
&format!("regex syntax error on position {}: {}", e.position(), e.description()),
);
2016-12-20 17:21:30 +00:00
},
2016-05-25 15:15:19 +00:00
}
}
}