]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/regex.rs
Auto merge of #5671 - ebroto:changelog_144_145, r=flip1995
[rust.git] / clippy_lints / src / regex.rs
1 use crate::consts::{constant, Constant};
2 use crate::utils::{is_expn_of, match_def_path, match_type, paths, span_lint, span_lint_and_help};
3 use if_chain::if_chain;
4 use rustc_ast::ast::{LitKind, StrStyle};
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_hir::{Block, BorrowKind, Crate, Expr, ExprKind, HirId};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
9 use rustc_span::source_map::{BytePos, Span};
10 use std::convert::TryFrom;
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
14     /// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
15     /// regex syntax.
16     ///
17     /// **Why is this bad?** This will lead to a runtime panic.
18     ///
19     /// **Known problems:** None.
20     ///
21     /// **Example:**
22     /// ```ignore
23     /// Regex::new("|")
24     /// ```
25     pub INVALID_REGEX,
26     correctness,
27     "invalid regular expressions"
28 }
29
30 declare_clippy_lint! {
31     /// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
32     /// creation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`).
33     ///
34     /// **Why is this bad?** Matching the regex can likely be replaced by `==` or
35     /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
36     /// methods.
37     ///
38     /// **Known problems:** None.
39     ///
40     /// **Example:**
41     /// ```ignore
42     /// Regex::new("^foobar")
43     /// ```
44     pub TRIVIAL_REGEX,
45     style,
46     "trivial regular expressions"
47 }
48
49 declare_clippy_lint! {
50     /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
51     /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
52     /// idea anyway).
53     ///
54     /// **Why is this bad?** Performance, at least for now. The macro version is
55     /// likely to catch up long-term, but for now the dynamic version is faster.
56     ///
57     /// **Known problems:** None.
58     ///
59     /// **Example:**
60     /// ```ignore
61     /// regex!("foo|bar")
62     /// ```
63     pub REGEX_MACRO,
64     style,
65     "use of `regex!(_)` instead of `Regex::new(_)`"
66 }
67
68 #[derive(Clone, Default)]
69 pub struct Regex {
70     spans: FxHashSet<Span>,
71     last: Option<HirId>,
72 }
73
74 impl_lint_pass!(Regex => [INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX]);
75
76 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Regex {
77     fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate<'_>) {
78         self.spans.clear();
79     }
80
81     fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block<'_>) {
82         if_chain! {
83             if self.last.is_none();
84             if let Some(ref expr) = block.expr;
85             if match_type(cx, cx.tables.expr_ty(expr), &paths::REGEX);
86             if let Some(span) = is_expn_of(expr.span, "regex");
87             then {
88                 if !self.spans.contains(&span) {
89                     span_lint(
90                         cx,
91                         REGEX_MACRO,
92                         span,
93                         "`regex!(_)` found. \
94                         Please use `Regex::new(_)`, which is faster for now."
95                     );
96                     self.spans.insert(span);
97                 }
98                 self.last = Some(block.hir_id);
99             }
100         }
101     }
102
103     fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block<'_>) {
104         if self.last.map_or(false, |id| block.hir_id == id) {
105             self.last = None;
106         }
107     }
108
109     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
110         if_chain! {
111             if let ExprKind::Call(ref fun, ref args) = expr.kind;
112             if let ExprKind::Path(ref qpath) = fun.kind;
113             if args.len() == 1;
114             if let Some(def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
115             then {
116                 if match_def_path(cx, def_id, &paths::REGEX_NEW) ||
117                    match_def_path(cx, def_id, &paths::REGEX_BUILDER_NEW) {
118                     check_regex(cx, &args[0], true);
119                 } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_NEW) ||
120                    match_def_path(cx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
121                     check_regex(cx, &args[0], false);
122                 } else if match_def_path(cx, def_id, &paths::REGEX_SET_NEW) {
123                     check_set(cx, &args[0], true);
124                 } else if match_def_path(cx, def_id, &paths::REGEX_BYTES_SET_NEW) {
125                     check_set(cx, &args[0], false);
126                 }
127             }
128         }
129     }
130 }
131
132 #[allow(clippy::cast_possible_truncation)] // truncation very unlikely here
133 #[must_use]
134 fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span {
135     let offset = u32::from(offset);
136     let end = base.lo() + BytePos(u32::try_from(c.end.offset).expect("offset too large") + offset);
137     let start = base.lo() + BytePos(u32::try_from(c.start.offset).expect("offset too large") + offset);
138     assert!(start <= end);
139     Span::new(start, end, base.ctxt())
140 }
141
142 fn const_str<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) -> Option<String> {
143     constant(cx, cx.tables, e).and_then(|(c, _)| match c {
144         Constant::Str(s) => Some(s),
145         _ => None,
146     })
147 }
148
149 fn is_trivial_regex(s: &regex_syntax::hir::Hir) -> Option<&'static str> {
150     use regex_syntax::hir::Anchor::{EndText, StartText};
151     use regex_syntax::hir::HirKind::{Alternation, Anchor, Concat, Empty, Literal};
152
153     let is_literal = |e: &[regex_syntax::hir::Hir]| {
154         e.iter().all(|e| match *e.kind() {
155             Literal(_) => true,
156             _ => false,
157         })
158     };
159
160     match *s.kind() {
161         Empty | Anchor(_) => Some("the regex is unlikely to be useful as it is"),
162         Literal(_) => Some("consider using `str::contains`"),
163         Alternation(ref exprs) => {
164             if exprs.iter().all(|e| e.kind().is_empty()) {
165                 Some("the regex is unlikely to be useful as it is")
166             } else {
167                 None
168             }
169         },
170         Concat(ref exprs) => match (exprs[0].kind(), exprs[exprs.len() - 1].kind()) {
171             (&Anchor(StartText), &Anchor(EndText)) if exprs[1..(exprs.len() - 1)].is_empty() => {
172                 Some("consider using `str::is_empty`")
173             },
174             (&Anchor(StartText), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
175                 Some("consider using `==` on `str`s")
176             },
177             (&Anchor(StartText), &Literal(_)) if is_literal(&exprs[1..]) => Some("consider using `str::starts_with`"),
178             (&Literal(_), &Anchor(EndText)) if is_literal(&exprs[1..(exprs.len() - 1)]) => {
179                 Some("consider using `str::ends_with`")
180             },
181             _ if is_literal(exprs) => Some("consider using `str::contains`"),
182             _ => None,
183         },
184         _ => None,
185     }
186 }
187
188 fn check_set<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, utf8: bool) {
189     if_chain! {
190         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) = expr.kind;
191         if let ExprKind::Array(exprs) = expr.kind;
192         then {
193             for expr in exprs {
194                 check_regex(cx, expr, utf8);
195             }
196         }
197     }
198 }
199
200 fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, utf8: bool) {
201     let mut parser = regex_syntax::ParserBuilder::new()
202         .unicode(utf8)
203         .allow_invalid_utf8(!utf8)
204         .build();
205
206     if let ExprKind::Lit(ref lit) = expr.kind {
207         if let LitKind::Str(ref r, style) = lit.node {
208             let r = &r.as_str();
209             let offset = if let StrStyle::Raw(n) = style { 2 + n } else { 1 };
210             match parser.parse(r) {
211                 Ok(r) => {
212                     if let Some(repl) = is_trivial_regex(&r) {
213                         span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
214                     }
215                 },
216                 Err(regex_syntax::Error::Parse(e)) => {
217                     span_lint(
218                         cx,
219                         INVALID_REGEX,
220                         str_span(expr.span, *e.span(), offset),
221                         &format!("regex syntax error: {}", e.kind()),
222                     );
223                 },
224                 Err(regex_syntax::Error::Translate(e)) => {
225                     span_lint(
226                         cx,
227                         INVALID_REGEX,
228                         str_span(expr.span, *e.span(), offset),
229                         &format!("regex syntax error: {}", e.kind()),
230                     );
231                 },
232                 Err(e) => {
233                     span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
234                 },
235             }
236         }
237     } else if let Some(r) = const_str(cx, expr) {
238         match parser.parse(&r) {
239             Ok(r) => {
240                 if let Some(repl) = is_trivial_regex(&r) {
241                     span_lint_and_help(cx, TRIVIAL_REGEX, expr.span, "trivial regex", None, repl);
242                 }
243             },
244             Err(regex_syntax::Error::Parse(e)) => {
245                 span_lint(
246                     cx,
247                     INVALID_REGEX,
248                     expr.span,
249                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
250                 );
251             },
252             Err(regex_syntax::Error::Translate(e)) => {
253                 span_lint(
254                     cx,
255                     INVALID_REGEX,
256                     expr.span,
257                     &format!("regex syntax error on position {}: {}", e.span().start.offset, e.kind()),
258                 );
259             },
260             Err(e) => {
261                 span_lint(cx, INVALID_REGEX, expr.span, &format!("regex syntax error: {}", e));
262             },
263         }
264     }
265 }