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