]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Merge pull request #1860 from Vurich/master
[rust.git] / clippy_lints / src / matches.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use rustc::middle::const_val::ConstVal;
4 use rustc::ty::{self, Ty};
5 use rustc_const_eval::ConstContext;
6 use rustc_const_math::ConstInt;
7 use std::cmp::Ordering;
8 use std::collections::Bound;
9 use syntax::ast::LitKind;
10 use syntax::codemap::Span;
11 use utils::paths;
12 use utils::{match_type, snippet, span_note_and_lint, span_lint_and_then, span_lint_and_sugg, in_external_macro,
13             expr_block, walk_ptrs_ty, is_expn_of, remove_blocks};
14 use utils::sugg::Sugg;
15
16 /// **What it does:** Checks for matches with a single arm where an `if let`
17 /// will usually suffice.
18 ///
19 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
20 ///
21 /// **Known problems:** None.
22 ///
23 /// **Example:**
24 /// ```rust
25 /// match x {
26 ///     Some(ref foo) => bar(foo),
27 ///     _ => ()
28 /// }
29 /// ```
30 declare_lint! {
31     pub SINGLE_MATCH,
32     Warn,
33     "a match statement with a single nontrivial arm (i.e. where the other arm \
34      is `_ => {}`) instead of `if let`"
35 }
36
37 /// **What it does:** Checks for matches with a two arms where an `if let` will
38 /// usually suffice.
39 ///
40 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
41 ///
42 /// **Known problems:** Personal style preferences may differ.
43 ///
44 /// **Example:**
45 /// ```rust
46 /// match x {
47 ///     Some(ref foo) => bar(foo),
48 ///     _ => bar(other_ref),
49 /// }
50 /// ```
51 declare_lint! {
52     pub SINGLE_MATCH_ELSE,
53     Allow,
54     "a match statement with a two arms where the second arm's pattern is a wildcard \
55      instead of `if let`"
56 }
57
58 /// **What it does:** Checks for matches where all arms match a reference,
59 /// suggesting to remove the reference and deref the matched expression
60 /// instead. It also checks for `if let &foo = bar` blocks.
61 ///
62 /// **Why is this bad?** It just makes the code less readable. That reference
63 /// destructuring adds nothing to the code.
64 ///
65 /// **Known problems:** None.
66 ///
67 /// **Example:**
68 /// ```rust
69 /// match x {
70 ///     &A(ref y) => foo(y),
71 ///     &B => bar(),
72 ///     _ => frob(&x),
73 /// }
74 /// ```
75 declare_lint! {
76     pub MATCH_REF_PATS,
77     Warn,
78     "a match or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
79 }
80
81 /// **What it does:** Checks for matches where match expression is a `bool`. It
82 /// suggests to replace the expression with an `if...else` block.
83 ///
84 /// **Why is this bad?** It makes the code less readable.
85 ///
86 /// **Known problems:** None.
87 ///
88 /// **Example:**
89 /// ```rust
90 /// let condition: bool = true;
91 /// match condition {
92 ///     true => foo(),
93 ///     false => bar(),
94 /// }
95 /// ```
96 declare_lint! {
97     pub MATCH_BOOL,
98     Warn,
99     "a match on a boolean expression instead of an `if..else` block"
100 }
101
102 /// **What it does:** Checks for overlapping match arms.
103 ///
104 /// **Why is this bad?** It is likely to be an error and if not, makes the code
105 /// less obvious.
106 ///
107 /// **Known problems:** None.
108 ///
109 /// **Example:**
110 /// ```rust
111 /// let x = 5;
112 /// match x {
113 ///     1 ... 10 => println!("1 ... 10"),
114 ///     5 ... 15 => println!("5 ... 15"),
115 ///     _ => (),
116 /// }
117 /// ```
118 declare_lint! {
119     pub MATCH_OVERLAPPING_ARM,
120     Warn,
121     "a match with overlapping arms"
122 }
123
124 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
125 /// and take drastic actions like `panic!`.
126 ///
127 /// **Why is this bad?** It is generally a bad practice, just like
128 /// catching all exceptions in java with `catch(Exception)`
129 ///
130 /// **Known problems:** None.
131 ///
132 /// **Example:**
133 /// ```rust
134 /// let x : Result(i32, &str) = Ok(3);
135 /// match x {
136 ///     Ok(_) => println!("ok"),
137 ///     Err(_) => panic!("err"),
138 /// }
139 /// ```
140 declare_lint! {
141     pub MATCH_WILD_ERR_ARM,
142     Warn,
143     "a match with `Err(_)` arm and take drastic actions"
144 }
145
146 #[allow(missing_copy_implementations)]
147 pub struct MatchPass;
148
149 impl LintPass for MatchPass {
150     fn get_lints(&self) -> LintArray {
151         lint_array!(SINGLE_MATCH,
152                     MATCH_REF_PATS,
153                     MATCH_BOOL,
154                     SINGLE_MATCH_ELSE,
155                     MATCH_OVERLAPPING_ARM,
156                     MATCH_WILD_ERR_ARM)
157     }
158 }
159
160 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
161     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
162         if in_external_macro(cx, expr.span) {
163             return;
164         }
165         if let ExprMatch(ref ex, ref arms, MatchSource::Normal) = expr.node {
166             check_single_match(cx, ex, arms, expr);
167             check_match_bool(cx, ex, arms, expr);
168             check_overlapping_arms(cx, ex, arms);
169             check_wild_err_arm(cx, ex, arms);
170         }
171         if let ExprMatch(ref ex, ref arms, source) = expr.node {
172             check_match_ref_pats(cx, ex, arms, source, expr);
173         }
174     }
175 }
176
177 #[cfg_attr(rustfmt, rustfmt_skip)]
178 fn check_single_match(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
179     if arms.len() == 2 &&
180       arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
181       arms[1].pats.len() == 1 && arms[1].guard.is_none() {
182         let els = remove_blocks(&arms[1].body);
183         let els = if is_unit_expr(els) {
184             None
185         } else if let ExprBlock(_) = els.node {
186             // matches with blocks that contain statements are prettier as `if let + else`
187             Some(els)
188         } else {
189             // allow match arms with just expressions
190             return;
191         };
192         let ty = cx.tables.expr_ty(ex);
193         if ty.sty != ty::TyBool || cx.current_level(MATCH_BOOL) == Allow {
194             check_single_match_single_pattern(cx, ex, arms, expr, els);
195             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
196         }
197     }
198 }
199
200 fn check_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
201     if arms[1].pats[0].node == PatKind::Wild {
202         report_single_match_single_pattern(cx, ex, arms, expr, els);
203     }
204 }
205
206 fn report_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
207     let lint = if els.is_some() {
208         SINGLE_MATCH_ELSE
209     } else {
210         SINGLE_MATCH
211     };
212     let els_str = els.map_or(String::new(), |els| format!(" else {}", expr_block(cx, els, None, "..")));
213     span_lint_and_sugg(cx,
214                        lint,
215                        expr.span,
216                        "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
217                         let`",
218                        "try this",
219                        format!("if let {} = {} {}{}",
220                                snippet(cx, arms[0].pats[0].span, ".."),
221                                snippet(cx, ex.span, ".."),
222                                expr_block(cx, &arms[0].body, None, ".."),
223                                els_str));
224 }
225
226 fn check_single_match_opt_like(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, ty: Ty, els: Option<&Expr>) {
227     // list of candidate Enums we know will never get any more members
228     let candidates = &[(&paths::COW, "Borrowed"),
229                        (&paths::COW, "Cow::Borrowed"),
230                        (&paths::COW, "Cow::Owned"),
231                        (&paths::COW, "Owned"),
232                        (&paths::OPTION, "None"),
233                        (&paths::RESULT, "Err"),
234                        (&paths::RESULT, "Ok")];
235
236     let path = match arms[1].pats[0].node {
237         PatKind::TupleStruct(ref path, ref inner, _) => {
238             // contains any non wildcard patterns? e.g. Err(err)
239             if inner.iter().any(|pat| pat.node != PatKind::Wild) {
240                 return;
241             }
242             print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
243         },
244         PatKind::Binding(BindByValue(MutImmutable), _, ident, None) => ident.node.to_string(),
245         PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
246         _ => return,
247     };
248
249     for &(ty_path, pat_path) in candidates {
250         if path == *pat_path && match_type(cx, ty, ty_path) {
251             report_single_match_single_pattern(cx, ex, arms, expr, els);
252         }
253     }
254 }
255
256 fn check_match_bool(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
257     // type of expression == bool
258     if cx.tables.expr_ty(ex).sty == ty::TyBool {
259         span_lint_and_then(cx,
260                            MATCH_BOOL,
261                            expr.span,
262                            "you seem to be trying to match on a boolean expression",
263                            move |db| {
264             if arms.len() == 2 && arms[0].pats.len() == 1 {
265                 // no guards
266                 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
267                     if let ExprLit(ref lit) = arm_bool.node {
268                         match lit.node {
269                             LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
270                             LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
271                             _ => None,
272                         }
273                     } else {
274                         None
275                     }
276                 } else {
277                     None
278                 };
279
280                 if let Some((true_expr, false_expr)) = exprs {
281                     let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
282                         (false, false) => {
283                             Some(format!("if {} {} else {}",
284                                          snippet(cx, ex.span, "b"),
285                                          expr_block(cx, true_expr, None, ".."),
286                                          expr_block(cx, false_expr, None, "..")))
287                         },
288                         (false, true) => {
289                             Some(format!("if {} {}", snippet(cx, ex.span, "b"), expr_block(cx, true_expr, None, "..")))
290                         },
291                         (true, false) => {
292                             let test = Sugg::hir(cx, ex, "..");
293                             Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
294                         },
295                         (true, true) => None,
296                     };
297
298                     if let Some(sugg) = sugg {
299                         db.span_suggestion(expr.span, "consider using an if/else expression", sugg);
300                     }
301                 }
302             }
303
304         });
305     }
306 }
307
308 fn check_overlapping_arms(cx: &LateContext, ex: &Expr, arms: &[Arm]) {
309     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
310         let ranges = all_ranges(cx, arms);
311         let type_ranges = type_ranges(&ranges);
312         if !type_ranges.is_empty() {
313             if let Some((start, end)) = overlapping(&type_ranges) {
314                 span_note_and_lint(cx,
315                                    MATCH_OVERLAPPING_ARM,
316                                    start.span,
317                                    "some ranges overlap",
318                                    end.span,
319                                    "overlaps with this");
320             }
321         }
322     }
323 }
324
325 fn check_wild_err_arm(cx: &LateContext, ex: &Expr, arms: &[Arm]) {
326     let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
327     if match_type(cx, ex_ty, &paths::RESULT) {
328         for arm in arms {
329             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
330                 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
331                 if_let_chain! {[
332                     path_str == "Err",
333                     inner.iter().any(|pat| pat.node == PatKind::Wild),
334                     let ExprBlock(ref block) = arm.body.node,
335                     is_panic_block(block)
336                 ], {
337                     // `Err(_)` arm with `panic!` found
338                     span_note_and_lint(cx,
339                                        MATCH_WILD_ERR_ARM,
340                                        arm.pats[0].span,
341                                        "Err(_) will match all errors, maybe not a good idea",
342                                        arm.pats[0].span,
343                                        "to remove this warning, match each error seperately \
344                                         or use unreachable macro");
345                 }}
346             }
347         }
348     }
349 }
350
351 // If the block contains only a `panic!` macro (as expression or statement)
352 fn is_panic_block(block: &Block) -> bool {
353     match (&block.expr, block.stmts.len(), block.stmts.first()) {
354         (&Some(ref exp), 0, _) => {
355             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
356         },
357         (&None, 1, Some(stmt)) => {
358             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
359         },
360         _ => false,
361     }
362 }
363
364 fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: MatchSource, expr: &Expr) {
365     if has_only_ref_pats(arms) {
366         if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
367             span_lint_and_then(cx,
368                                MATCH_REF_PATS,
369                                expr.span,
370                                "you don't need to add `&` to both the expression and the patterns",
371                                |db| {
372                 let inner = Sugg::hir(cx, inner, "..");
373                 let template = match_template(expr.span, source, &inner);
374                 db.span_suggestion(expr.span, "try", template);
375             });
376         } else {
377             span_lint_and_then(cx,
378                                MATCH_REF_PATS,
379                                expr.span,
380                                "you don't need to add `&` to all patterns",
381                                |db| {
382                 let ex = Sugg::hir(cx, ex, "..");
383                 let template = match_template(expr.span, source, &ex.deref());
384                 db.span_suggestion(expr.span,
385                                    "instead of prefixing all patterns with `&`, you can dereference the expression",
386                                    template);
387             });
388         }
389     }
390 }
391
392 /// Get all arms that are unbounded `PatRange`s.
393 fn all_ranges<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arms: &[Arm]) -> Vec<SpannedRange<ConstVal<'tcx>>> {
394     let constcx = ConstContext::with_tables(cx.tcx, cx.tables);
395     arms.iter()
396         .flat_map(|arm| {
397             if let Arm { ref pats, guard: None, .. } = *arm {
398                     pats.iter()
399                 } else {
400                     [].iter()
401                 }
402                 .filter_map(|pat| {
403                     if_let_chain! {[
404                     let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node,
405                     let Ok(lhs) = constcx.eval(lhs),
406                     let Ok(rhs) = constcx.eval(rhs)
407                 ], {
408                     let rhs = match *range_end {
409                         RangeEnd::Included => Bound::Included(rhs),
410                         RangeEnd::Excluded => Bound::Excluded(rhs),
411                     };
412                     return Some(SpannedRange { span: pat.span, node: (lhs, rhs) });
413                 }}
414
415                     if_let_chain! {[
416                     let PatKind::Lit(ref value) = pat.node,
417                     let Ok(value) = constcx.eval(value)
418                 ], {
419                     return Some(SpannedRange { span: pat.span, node: (value.clone(), Bound::Included(value)) });
420                 }}
421
422                     None
423                 })
424         })
425         .collect()
426 }
427
428 #[derive(Debug, Eq, PartialEq)]
429 pub struct SpannedRange<T> {
430     pub span: Span,
431     pub node: (T, Bound<T>),
432 }
433
434 type TypedRanges = Vec<SpannedRange<ConstInt>>;
435
436 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway and other types than
437 /// `Uint` and `Int` probably don't make sense.
438 fn type_ranges(ranges: &[SpannedRange<ConstVal>]) -> TypedRanges {
439     ranges.iter()
440         .filter_map(|range| match range.node {
441             (ConstVal::Integral(start), Bound::Included(ConstVal::Integral(end))) => {
442                 Some(SpannedRange {
443                     span: range.span,
444                     node: (start, Bound::Included(end)),
445                 })
446             },
447             (ConstVal::Integral(start), Bound::Excluded(ConstVal::Integral(end))) => {
448                 Some(SpannedRange {
449                     span: range.span,
450                     node: (start, Bound::Excluded(end)),
451                 })
452             },
453             (ConstVal::Integral(start), Bound::Unbounded) => {
454                 Some(SpannedRange {
455                     span: range.span,
456                     node: (start, Bound::Unbounded),
457                 })
458             },
459             _ => None,
460         })
461         .collect()
462 }
463
464 fn is_unit_expr(expr: &Expr) -> bool {
465     match expr.node {
466         ExprTup(ref v) if v.is_empty() => true,
467         ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
468         _ => false,
469     }
470 }
471
472 fn has_only_ref_pats(arms: &[Arm]) -> bool {
473     let mapped = arms.iter()
474         .flat_map(|a| &a.pats)
475         .map(|p| {
476             match p.node {
477                 PatKind::Ref(..) => Some(true),  // &-patterns
478                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
479                 _ => None,                    // any other pattern is not fine
480             }
481         })
482         .collect::<Option<Vec<bool>>>();
483     // look for Some(v) where there's at least one true element
484     mapped.map_or(false, |v| v.iter().any(|el| *el))
485 }
486
487 fn match_template(span: Span, source: MatchSource, expr: &Sugg) -> String {
488     match source {
489         MatchSource::Normal => format!("match {} {{ .. }}", expr),
490         MatchSource::IfLetDesugar { .. } => format!("if let .. = {} {{ .. }}", expr),
491         MatchSource::WhileLetDesugar => format!("while let .. = {} {{ .. }}", expr),
492         MatchSource::ForLoopDesugar => span_bug!(span, "for loop desugared to match with &-patterns!"),
493         MatchSource::TryDesugar => span_bug!(span, "`?` operator desugared to match with &-patterns!"),
494     }
495 }
496
497 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
498     where T: Copy + Ord
499 {
500     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
501     enum Kind<'a, T: 'a> {
502         Start(T, &'a SpannedRange<T>),
503         End(Bound<T>, &'a SpannedRange<T>),
504     }
505
506     impl<'a, T: Copy> Kind<'a, T> {
507         fn range(&self) -> &'a SpannedRange<T> {
508             match *self {
509                 Kind::Start(_, r) |
510                 Kind::End(_, r) => r,
511             }
512         }
513
514         fn value(self) -> Bound<T> {
515             match self {
516                 Kind::Start(t, _) => Bound::Included(t),
517                 Kind::End(t, _) => t,
518             }
519         }
520     }
521
522     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
523         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
524             Some(self.cmp(other))
525         }
526     }
527
528     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
529         fn cmp(&self, other: &Self) -> Ordering {
530             match (self.value(), other.value()) {
531                 (Bound::Included(a), Bound::Included(b)) |
532                 (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
533                 // Range patterns cannot be unbounded (yet)
534                 (Bound::Unbounded, _) |
535                 (_, Bound::Unbounded) => unimplemented!(),
536                 (Bound::Included(a), Bound::Excluded(b)) => {
537                     match a.cmp(&b) {
538                         Ordering::Equal => Ordering::Greater,
539                         other => other,
540                     }
541                 },
542                 (Bound::Excluded(a), Bound::Included(b)) => {
543                     match a.cmp(&b) {
544                         Ordering::Equal => Ordering::Less,
545                         other => other,
546                     }
547                 },
548             }
549         }
550     }
551
552     let mut values = Vec::with_capacity(2 * ranges.len());
553
554     for r in ranges {
555         values.push(Kind::Start(r.node.0, r));
556         values.push(Kind::End(r.node.1, r));
557     }
558
559     values.sort();
560
561     for (a, b) in values.iter().zip(values.iter().skip(1)) {
562         match (a, b) {
563             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
564                 if ra.node != rb.node {
565                     return Some((ra, rb));
566                 }
567             },
568             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
569             _ => return Some((a.range(), b.range())),
570         }
571     }
572
573     None
574 }