]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/regex.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / regex.rs
1 use regex_syntax;
2 use rustc::hir::*;
3 use rustc::lint::*;
4 use rustc::ty;
5 use rustc::middle::const_val::ConstVal;
6 use rustc_const_eval::ConstContext;
7 use rustc::ty::subst::Substs;
8 use std::collections::HashSet;
9 use std::error::Error;
10 use syntax::ast::{LitKind, NodeId};
11 use syntax::codemap::{BytePos, Span};
12 use syntax::symbol::InternedString;
13 use utils::{is_expn_of, match_def_path, match_type, opt_def_id, paths, span_help_and_lint, span_lint};
14
15 /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
16 /// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
17 /// regex syntax.
18 ///
19 /// **Why is this bad?** This will lead to a runtime panic.
20 ///
21 /// **Known problems:** None.
22 ///
23 /// **Example:**
24 /// ```rust
25 /// Regex::new("|")
26 /// ```
27 declare_lint! {
28 pub INVALID_REGEX,
29 Deny,
30 "invalid regular expressions"
31 }
32
33 /// **What it does:** Checks for trivial [regex](https://crates.io/crates/regex)
34 /// creation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`).
35 ///
36 /// **Why is this bad?** Matching the regex can likely be replaced by `==` or
37 /// `str::starts_with`, `str::ends_with` or `std::contains` or other `str`
38 /// methods.
39 ///
40 /// **Known problems:** None.
41 ///
42 /// **Example:**
43 /// ```rust
44 /// Regex::new("^foobar")
45 /// ```
46 declare_lint! {
47 pub TRIVIAL_REGEX,
48 Warn,
49 "trivial regular expressions"
50 }
51
52 /// **What it does:** Checks for usage of `regex!(_)` which (as of now) is
53 /// usually slower than `Regex::new(_)` unless called in a loop (which is a bad
54 /// idea anyway).
55 ///
56 /// **Why is this bad?** Performance, at least for now. The macro version is
57 /// likely to catch up long-term, but for now the dynamic version is faster.
58 ///
59 /// **Known problems:** None.
60 ///
61 /// **Example:**
62 /// ```rust
63 /// regex!("foo|bar")
64 /// ```
65 declare_lint! {
66 pub REGEX_MACRO,
67 Warn,
68 "use of `regex!(_)` instead of `Regex::new(_)`"
69 }
70
71 #[derive(Clone, Default)]
72 pub struct Pass {
73 spans: HashSet<Span>,
74 last: Option<NodeId>,
75 }
76
77 impl LintPass for Pass {
78 fn get_lints(&self) -> LintArray {
79 lint_array!(INVALID_REGEX, REGEX_MACRO, TRIVIAL_REGEX)
80 }
81 }
82
83 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
84 fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
85 self.spans.clear();
86 }
87
88 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
89 if_chain! {
90 if self.last.is_none();
91 if let Some(ref expr) = block.expr;
92 if match_type(cx, cx.tables.expr_ty(expr), &paths::REGEX);
93 if let Some(span) = is_expn_of(expr.span, "regex");
94 then {
95 if !self.spans.contains(&span) {
96 span_lint(cx,
97 REGEX_MACRO,
98 span,
99 "`regex!(_)` found. \
100 Please use `Regex::new(_)`, which is faster for now.");
101 self.spans.insert(span);
102 }
103 self.last = Some(block.id);
104 }
105 }
106 }
107
108 fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, block: &'tcx Block) {
109 if self.last.map_or(false, |id| block.id == id) {
110 self.last = None;
111 }
112 }
113
114 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
115 if_chain! {
116 if let ExprCall(ref fun, ref args) = expr.node;
117 if let ExprPath(ref qpath) = fun.node;
118 if args.len() == 1;
119 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, fun.hir_id));
120 then {
121 if match_def_path(cx.tcx, def_id, &paths::REGEX_NEW) ||
122 match_def_path(cx.tcx, def_id, &paths::REGEX_BUILDER_NEW) {
123 check_regex(cx, &args[0], true);
124 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_NEW) ||
125 match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
126 check_regex(cx, &args[0], false);
127 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_SET_NEW) {
128 check_set(cx, &args[0], true);
129 } else if match_def_path(cx.tcx, def_id, &paths::REGEX_BYTES_SET_NEW) {
130 check_set(cx, &args[0], false);
131 }
132 }
133 }
134 }
135 }
136
137 #[allow(cast_possible_truncation)]
138 fn str_span(base: Span, s: &str, c: usize) -> Span {
139 let mut si = s.char_indices().skip(c);
140
141 match (si.next(), si.next()) {
142 (Some((l, _)), Some((h, _))) => {
143 Span::new(base.lo() + BytePos(l as u32), base.lo() + BytePos(h as u32), base.ctxt())
144 },
145 _ => base,
146 }
147 }
148
149 fn const_str<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) -> Option<InternedString> {
150 let parent_item = cx.tcx.hir.get_parent(e.id);
151 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
152 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
153 match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(e) {
154 Ok(&ty::Const {
155 val: ConstVal::Str(r),
156 ..
157 }) => Some(r),
158 _ => None,
159 }
160 }
161
162 fn is_trivial_regex(s: &regex_syntax::Expr) -> Option<&'static str> {
163 use regex_syntax::Expr;
164
165 match *s {
166 Expr::Empty | Expr::StartText | Expr::EndText => Some("the regex is unlikely to be useful as it is"),
167 Expr::Literal { .. } => Some("consider using `str::contains`"),
168 Expr::Concat(ref exprs) => match exprs.len() {
169 2 => match (&exprs[0], &exprs[1]) {
170 (&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"),
171 (&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"),
172 (&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"),
173 _ => None,
174 },
175 3 => if let (&Expr::StartText, &Expr::Literal { .. }, &Expr::EndText) = (&exprs[0], &exprs[1], &exprs[2]) {
176 Some("consider using `==` on `str`s")
177 } else {
178 None
179 },
180 _ => None,
181 },
182 _ => None,
183 }
184 }
185
186 fn check_set<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
187 if_chain! {
188 if let ExprAddrOf(_, ref expr) = expr.node;
189 if let ExprArray(ref exprs) = expr.node;
190 then {
191 for expr in exprs {
192 check_regex(cx, expr, utf8);
193 }
194 }
195 }
196 }
197
198 fn check_regex<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, utf8: bool) {
199 let builder = regex_syntax::ExprBuilder::new().unicode(utf8);
200
201 if let ExprLit(ref lit) = expr.node {
202 if let LitKind::Str(ref r, _) = lit.node {
203 let r = &r.as_str();
204 match builder.parse(r) {
205 Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
206 span_help_and_lint(
207 cx,
208 TRIVIAL_REGEX,
209 expr.span,
210 "trivial regex",
211 &format!("consider using {}", repl),
212 );
213 },
214 Err(e) => {
215 span_lint(
216 cx,
217 INVALID_REGEX,
218 str_span(expr.span, r, e.position()),
219 &format!("regex syntax error: {}", e.description()),
220 );
221 },
222 }
223 }
224 } else if let Some(r) = const_str(cx, expr) {
225 match builder.parse(&r) {
226 Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
227 span_help_and_lint(
228 cx,
229 TRIVIAL_REGEX,
230 expr.span,
231 "trivial regex",
232 &format!("consider using {}", repl),
233 );
234 },
235 Err(e) => {
236 span_lint(
237 cx,
238 INVALID_REGEX,
239 expr.span,
240 &format!("regex syntax error on position {}: {}", e.position(), e.description()),
241 );
242 },
243 }
244 }
245 }