1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::consts::{constant, Constant};
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_data_structures::fx::FxHashSet;
15 use crate::syntax::ast::{LitKind, NodeId, StrStyle};
16 use crate::syntax::source_map::{BytePos, Span};
17 use crate::utils::{is_expn_of, match_def_path, match_type, opt_def_id, paths, span_help_and_lint, span_lint};
18 use if_chain::if_chain;
20 use std::convert::TryFrom;
22 /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
23 /// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
26 /// **Why is this bad?** This will lead to a runtime panic.
28 /// **Known problems:** None.
34 declare_clippy_lint! {
37 "invalid regular expressions"
40 /// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
41 /// creation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`).
43 /// **Why is this bad?** Matching the regex can likely be replaced by `==` or
44 /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
47 /// **Known problems:** None.
51 /// Regex::new("^foobar")
53 declare_clippy_lint! {
56 "trivial regular expressions"
59 /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
60 /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
63 /// **Why is this bad?** Performance, at least for now. The macro version is
64 /// likely to catch up long-term, but for now the dynamic version is faster.
66 /// **Known problems:** None.
72 declare_clippy_lint! {
75 "use of `regex!(_)` instead of `Regex::new(_)`"
78 #[derive(Clone, Default)]
80 spans: FxHashSet<Span>,
84 impl LintPass for Pass {
85 fn get_lints(&self) -> LintArray {
86 lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
90 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
91 fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
95 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
97 if self.last.is_none();
98 if let Some(ref expr) = block.expr;
99 if match_type(cx, cx.tables.expr_ty(expr), &paths::REGEX);
100 if let Some(span) = is_expn_of(expr.span, "regex");
102 if !self.spans.contains(&span) {
106 "`regex!(_)` found. \
107 Please use `Regex::new(_)`, which is faster for now.");
108 self.spans.insert(span);
110 self.last = Some(block.id);
115 fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
116 if self.last.map_or(false, |id| block.id == id) {
121 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
123 if let ExprKind::Call(ref fun, ref args) = expr.node;
124 if let ExprKind::Path(ref qpath) = fun.node;
126 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, fun.hir_id));
128 if match_def_path(cx.tcx, def_id, &paths::REGEX_NEW) ||
129 match_def_path(cx.tcx, def_id, &paths::REGEX_BUILDER_NEW) {
130 check_regex(cx, &args[0], true);
131 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_NEW) ||
132 match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
133 check_regex(cx, &args[0], false);
134 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_SET_NEW) {
135 check_set(cx, &args[0], true);
136 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_SET_NEW) {
137 check_set(cx, &args[0], false);
144 #[allow(clippy::cast_possible_truncation)] // truncation very unlikely here
145 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
146 let offset = u32::from(offset);
147 let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset);
148 let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + offset);
149 assert!(start <= end);
150 Span::new(start, end, base.ctxt())
153 fn const_str<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) -> Option<String> {
154 constant(cx, cx.tables, e).and_then(|(c, _)| match c {
155 Constant::Str(s) => Some(s),
160 fn is_trivial_regex(s: ®ex_syntax::hir::Hir) -> Option<&'static str> {
161 use regex_syntax::hir::Anchor::*;
162 use regex_syntax::hir::HirKind::*;
164 let is_literal = |e: &[regex_syntax::hir::Hir]| {
165 e.iter().all(|e| match *e.kind() {
172 Empty | Anchor(_) => Some("the regex is unlikely to be useful as it is"),
173 Literal(_) => Some("consider using `str::contains`"),
174 Alternation(ref exprs) => {
175 if exprs.iter().all(|e| e.kind().is_empty()) {
176 Some("the regex is unlikely to be useful as it is")
181 Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
182 (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => {
183 Some("consider using `str::is_empty`")
185 (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
186 Some("consider using `==` on `str`s")
188 (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
189 (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
190 Some("consider using `str::ends_with`")
192 _ if is_literal(exprs) => Some("consider using `str::contains`"),
199 fn check_set<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
201 if let ExprKind::AddrOf(_, ref expr) = expr.node;
202 if let ExprKind::Array(ref exprs) = expr.node;
205 check_regex(cx, expr, utf8);
211 fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
212 let mut parser = regex_syntax::ParserBuilder::new()
214 .allow_invalid_utf8(!utf8)
217 if let ExprKind::Lit(ref lit) = expr.node {
218 if let LitKind::Str(ref r, style) = lit.node {
220 let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
221 match parser.parse(r) {
223 if let Some(repl) = is_trivial_regex(&r) {
224 span_help_and_lint(cx, TRIVIAL_REGEX, expr.span, "trivial regex", repl);
227 Err(regex_syntax::Error::Parse(e)) => {
231 str_span(expr.span, *e.span(), offset),
232 &format!("regex syntax error: {}", e.kind()),
235 Err(regex_syntax::Error::Translate(e)) => {
239 str_span(expr.span, *e.span(), offset),
240 &format!("regex syntax error: {}", e.kind()),
244 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
248 } else if let Some(r) = const_str(cx, expr) {
249 match parser.parse(&r) {
251 if let Some(repl) = is_trivial_regex(&r) {
252 span_help_and_lint(cx, TRIVIAL_REGEX, expr.span, "trivial regex", repl);
255 Err(regex_syntax::Error::Parse(e)) => {
260 &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
263 Err(regex_syntax::Error::Translate(e)) => {
268 &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
272 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));