]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/regex.rs
Merge commit '0e87918536b9833bbc6c683d1f9d51ee2bf03ef1' into clippyup
[rust.git] / clippy_lints / src / regex.rs
1 use crate::consts::{constant, Constant};
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
3 use clippy_utils::{match_def_path, paths};
4 use if_chain::if_chain;
5 use rustc_ast::ast::{LitKind, StrStyle};
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_hir::{BorrowKind, Expr, ExprKind, HirId};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 use rustc_span::source_map::{BytePos, Span};
11 use std::convert::TryFrom;
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
15     /// (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`) for correct
16     /// regex syntax.
17     ///
18     /// **Why is this bad?** This will lead to a runtime panic.
19     ///
20     /// **Known problems:** None.
21     ///
22     /// **Example:**
23     /// ```ignore
24     /// Regex::new("|")
25     /// ```
26     pub INVALID_REGEX,
27     correctness,
28     "invalid regular expressions"
29 }
30
31 declare_clippy_lint! {
32     /// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
33     /// creation (with `Regex::new`, `RegexBuilder::new`, or `RegexSet::new`).
34     ///
35     /// **Why is this bad?** Matching the regex can likely be replaced by `==` or
36     /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
37     /// methods.
38     ///
39     /// **Known problems:** If the same regex is going to be applied to multiple
40     /// inputs, the precomputations done by `Regex` construction can give
41     /// significantly better performance than any of the `str`-based methods.
42     ///
43     /// **Example:**
44     /// ```ignore
45     /// Regex::new("^foobar")
46     /// ```
47     pub TRIVIAL_REGEX,
48     nursery,
49     "trivial regular expressions"
50 }
51
52 #[derive(Clone, Default)]
53 pub struct Regex {
54     spans: FxHashSet<Span>,
55     last: Option<HirId>,
56 }
57
58 impl_lint_pass!(Regex => [INVALID_REGEX, TRIVIAL_REGEX]);
59
60 impl<'tcx> LateLintPass<'tcx> for Regex {
61     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
62         if_chain! {
63             if let ExprKind::Call(ref fun, ref args) = expr.kind;
64             if let ExprKind::Path(ref qpath) = fun.kind;
65             if args.len() == 1;
66             if let Some(def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
67             then {
68                 if match_def_path(cx, def_id, &paths::REGEX_NEW) ||
69                    match_def_path(cx, def_id, &paths::REGEX_BUILDER_NEW) {
70                     check_regex(cx, &args[0], true);
71                 } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_NEW) ||
72                    match_def_path(cx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
73                     check_regex(cx, &args[0], false);
74                 } else if match_def_path(cx, def_id, &paths::REGEX_SET_NEW) {
75                     check_set(cx, &args[0], true);
76                 } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_SET_NEW) {
77                     check_set(cx, &args[0], false);
78                 }
79             }
80         }
81     }
82 }
83
84 #[allow(clippy::cast_possible_truncation)] // truncation very unlikely here
85 #[must_use]
86 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
87     let offset = u32::from(offset);
88     let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset);
89     let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + offset);
90     assert!(start <= end);
91     Span::new(start, end, base.ctxt())
92 }
93
94 fn const_str<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> Option<String> {
95     constant(cx, cx.typeck_results(), e).and_then(|(c, _)| match c {
96         Constant::Str(s) => Some(s),
97         _ => None,
98     })
99 }
100
101 fn is_trivial_regex(s: &regex_syntax::hir::Hir) -> Option<&'static str> {
102     use regex_syntax::hir::Anchor::{EndText, StartText};
103     use regex_syntax::hir::HirKind::{Alternation, Anchor, Concat, Empty, Literal};
104
105     let is_literal = |e: &[regex_syntax::hir::Hir]| e.iter().all(|e| matches!(*e.kind(), Literal(_)));
106
107     match *s.kind() {
108         Empty | Anchor(_) => Some("the regex is unlikely to be useful as it is"),
109         Literal(_) => Some("consider using `str::contains`"),
110         Alternation(ref exprs) => {
111             if exprs.iter().all(|e| e.kind().is_empty()) {
112                 Some("the regex is unlikely to be useful as it is")
113             } else {
114                 None
115             }
116         },
117         Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
118             (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => {
119                 Some("consider using `str::is_empty`")
120             },
121             (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
122                 Some("consider using `==` on `str`s")
123             },
124             (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
125             (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
126                 Some("consider using `str::ends_with`")
127             },
128             _ if is_literal(exprs) => Some("consider using `str::contains`"),
129             _ => None,
130         },
131         _ => None,
132     }
133 }
134
135 fn check_set<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) {
136     if_chain! {
137         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) = expr.kind;
138         if let ExprKind::Array(exprs) = expr.kind;
139         then {
140             for expr in exprs {
141                 check_regex(cx, expr, utf8);
142             }
143         }
144     }
145 }
146
147 fn check_regex<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, utf8: bool) {
148     let mut parser = regex_syntax::ParserBuilder::new()
149         .unicode(true)
150         .allow_invalid_utf8(!utf8)
151         .build();
152
153     if let ExprKind::Lit(ref lit) = expr.kind {
154         if let LitKind::Str(ref r, style) = lit.node {
155             let r = &r.as_str();
156             let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
157             match parser.parse(r) {
158                 Ok(r) => {
159                     if let Some(repl) = is_trivial_regex(&r) {
160                         span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
161                     }
162                 },
163                 Err(regex_syntax::Error::Parse(e)) => {
164                     span_lint(
165                         cx,
166                         INVALID_REGEX,
167                         str_span(expr.span, *e.span(), offset),
168                         &format!("regex syntax error: {}", e.kind()),
169                     );
170                 },
171                 Err(regex_syntax::Error::Translate(e)) => {
172                     span_lint(
173                         cx,
174                         INVALID_REGEX,
175                         str_span(expr.span, *e.span(), offset),
176                         &format!("regex syntax error: {}", e.kind()),
177                     );
178                 },
179                 Err(e) => {
180                     span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
181                 },
182             }
183         }
184     } else if let Some(r) = const_str(cx, expr) {
185         match parser.parse(&r) {
186             Ok(r) => {
187                 if let Some(repl) = is_trivial_regex(&r) {
188                     span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
189                 }
190             },
191             Err(regex_syntax::Error::Parse(e)) => {
192                 span_lint(
193                     cx,
194                     INVALID_REGEX,
195                     expr.span,
196                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
197                 );
198             },
199             Err(regex_syntax::Error::Translate(e)) => {
200                 span_lint(
201                     cx,
202                     INVALID_REGEX,
203                     expr.span,
204                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
205                 );
206             },
207             Err(e) => {
208                 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
209             },
210         }
211     }
212 }