]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
deduplicate `single_match_else` reporting
[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;
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, in_external_macro, expr_block, walk_ptrs_ty,
13             is_expn_of};
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 = if is_unit_expr(&arms[1].body) {
183             None
184         } else if let ExprBlock(_) = arms[1].body.node {
185             // matches with blocks that contain statements are prettier as `if let + else`
186             Some(&*arms[1].body)
187         } else {
188             // allow match arms with just expressions
189             return;
190         };
191         let ty = cx.tables.expr_ty(ex);
192         if ty.sty != ty::TyBool || cx.current_level(MATCH_BOOL) == Allow {
193             check_single_match_single_pattern(cx, ex, arms, expr, els);
194             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
195         }
196     }
197 }
198
199 fn check_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
200     if arms[1].pats[0].node == PatKind::Wild {
201         report_single_match_single_pattern(cx, ex, arms, expr, els);
202     }
203 }
204
205 fn report_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
206     let lint = if els.is_some() {
207         SINGLE_MATCH_ELSE
208     } else {
209         SINGLE_MATCH
210     };
211     let els_str = els.map_or(String::new(), |els| format!(" else {}", expr_block(cx, els, None, "..")));
212     span_lint_and_then(cx,
213                         lint,
214                         expr.span,
215                         "you seem to be trying to use match for destructuring a single pattern. \
216                         Consider using `if let`",
217                         |db| {
218         db.span_suggestion(expr.span,
219                             "try this",
220                             format!("if let {} = {} {}{}",
221                                     snippet(cx, arms[0].pats[0].span, ".."),
222                                     snippet(cx, ex.span, ".."),
223                                     expr_block(cx, &arms[0].body, None, ".."),
224                                     els_str));
225     });
226 }
227
228 fn check_single_match_opt_like(
229     cx: &LateContext,
230     ex: &Expr,
231     arms: &[Arm],
232     expr: &Expr,
233     ty: ty::Ty,
234     els: Option<&Expr>
235 ) {
236     // list of candidate Enums we know will never get any more members
237     let candidates = &[(&paths::COW, "Borrowed"),
238                        (&paths::COW, "Cow::Borrowed"),
239                        (&paths::COW, "Cow::Owned"),
240                        (&paths::COW, "Owned"),
241                        (&paths::OPTION, "None"),
242                        (&paths::RESULT, "Err"),
243                        (&paths::RESULT, "Ok")];
244
245     let path = match arms[1].pats[0].node {
246         PatKind::TupleStruct(ref path, ref inner, _) => {
247             // contains any non wildcard patterns? e.g. Err(err)
248             if inner.iter().any(|pat| pat.node != PatKind::Wild) {
249                 return;
250             }
251             print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
252         },
253         PatKind::Binding(BindByValue(MutImmutable), _, ident, None) => ident.node.to_string(),
254         PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
255         _ => return,
256     };
257
258     for &(ty_path, pat_path) in candidates {
259         if &path == pat_path && match_type(cx, ty, ty_path) {
260             report_single_match_single_pattern(cx, ex, arms, expr, els);
261         }
262     }
263 }
264
265 fn check_match_bool(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
266     // type of expression == bool
267     if cx.tables.expr_ty(ex).sty == ty::TyBool {
268         span_lint_and_then(cx,
269                            MATCH_BOOL,
270                            expr.span,
271                            "you seem to be trying to match on a boolean expression",
272                            move |db| {
273             if arms.len() == 2 && arms[0].pats.len() == 1 {
274                 // no guards
275                 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
276                     if let ExprLit(ref lit) = arm_bool.node {
277                         match lit.node {
278                             LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
279                             LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
280                             _ => None,
281                         }
282                     } else {
283                         None
284                     }
285                 } else {
286                     None
287                 };
288
289                 if let Some((true_expr, false_expr)) = exprs {
290                     let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
291                         (false, false) => {
292                             Some(format!("if {} {} else {}",
293                                          snippet(cx, ex.span, "b"),
294                                          expr_block(cx, true_expr, None, ".."),
295                                          expr_block(cx, false_expr, None, "..")))
296                         },
297                         (false, true) => {
298                             Some(format!("if {} {}", snippet(cx, ex.span, "b"), expr_block(cx, true_expr, None, "..")))
299                         },
300                         (true, false) => {
301                             let test = Sugg::hir(cx, ex, "..");
302                             Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
303                         },
304                         (true, true) => None,
305                     };
306
307                     if let Some(sugg) = sugg {
308                         db.span_suggestion(expr.span, "consider using an if/else expression", sugg);
309                     }
310                 }
311             }
312
313         });
314     }
315 }
316
317 fn check_overlapping_arms(cx: &LateContext, ex: &Expr, arms: &[Arm]) {
318     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
319         let ranges = all_ranges(cx, arms);
320         let type_ranges = type_ranges(&ranges);
321         if !type_ranges.is_empty() {
322             if let Some((start, end)) = overlapping(&type_ranges) {
323                 span_note_and_lint(cx,
324                                    MATCH_OVERLAPPING_ARM,
325                                    start.span,
326                                    "some ranges overlap",
327                                    end.span,
328                                    "overlaps with this");
329             }
330         }
331     }
332 }
333
334 fn check_wild_err_arm(cx: &LateContext, ex: &Expr, arms: &[Arm]) {
335     let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
336     if match_type(cx, ex_ty, &paths::RESULT) {
337         for arm in arms {
338             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
339                 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
340                 if_let_chain! {[
341                     path_str == "Err",
342                     inner.iter().any(|pat| pat.node == PatKind::Wild),
343                     let ExprBlock(ref block) = arm.body.node,
344                     is_panic_block(cx, block)
345                 ], {
346                     // `Err(_)` arm with `panic!` found
347                     span_note_and_lint(cx,
348                                        MATCH_WILD_ERR_ARM,
349                                        arm.pats[0].span,
350                                        "Err(_) will match all errors, maybe not a good idea",
351                                        arm.pats[0].span,
352                                        "to remove this warning, match each error seperately \
353                                         or use unreachable macro");
354                 }}
355             }
356         }
357     }
358 }
359
360 // If the block contains only a `panic!` macro (as expression or statement)
361 fn is_panic_block(cx: &LateContext, block: &Block) -> bool {
362     match (&block.expr, block.stmts.len(), block.stmts.first()) {
363         (&Some(ref exp), 0, _) => {
364             is_expn_of(cx, exp.span, "panic").is_some() && is_expn_of(cx, exp.span, "unreachable").is_none()
365         },
366         (&None, 1, Some(stmt)) => {
367             is_expn_of(cx, stmt.span, "panic").is_some() && is_expn_of(cx, stmt.span, "unreachable").is_none()
368         },
369         _ => false,
370     }
371 }
372
373 fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: MatchSource, expr: &Expr) {
374     if has_only_ref_pats(arms) {
375         if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
376             span_lint_and_then(cx,
377                                MATCH_REF_PATS,
378                                expr.span,
379                                "you don't need to add `&` to both the expression and the patterns",
380                                |db| {
381                 let inner = Sugg::hir(cx, inner, "..");
382                 let template = match_template(expr.span, source, &inner);
383                 db.span_suggestion(expr.span, "try", template);
384             });
385         } else {
386             span_lint_and_then(cx,
387                                MATCH_REF_PATS,
388                                expr.span,
389                                "you don't need to add `&` to all patterns",
390                                |db| {
391                 let ex = Sugg::hir(cx, ex, "..");
392                 let template = match_template(expr.span, source, &ex.deref());
393                 db.span_suggestion(expr.span,
394                                    "instead of prefixing all patterns with `&`, you can dereference the expression",
395                                    template);
396             });
397         }
398     }
399 }
400
401 /// Get all arms that are unbounded `PatRange`s.
402 fn all_ranges<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arms: &[Arm]) -> Vec<SpannedRange<ConstVal<'tcx>>> {
403     let constcx = ConstContext::with_tables(cx.tcx, cx.tables);
404     arms.iter()
405         .flat_map(|arm| {
406             if let Arm { ref pats, guard: None, .. } = *arm {
407                     pats.iter()
408                 } else {
409                     [].iter()
410                 }
411                 .filter_map(|pat| {
412                     if_let_chain! {[
413                     let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node,
414                     let Ok(lhs) = constcx.eval(lhs),
415                     let Ok(rhs) = constcx.eval(rhs)
416                 ], {
417                     let rhs = match *range_end {
418                         RangeEnd::Included => Bound::Included(rhs),
419                         RangeEnd::Excluded => Bound::Excluded(rhs),
420                     };
421                     return Some(SpannedRange { span: pat.span, node: (lhs, rhs) });
422                 }}
423
424                     if_let_chain! {[
425                     let PatKind::Lit(ref value) = pat.node,
426                     let Ok(value) = constcx.eval(value)
427                 ], {
428                     return Some(SpannedRange { span: pat.span, node: (value.clone(), Bound::Included(value)) });
429                 }}
430
431                     None
432                 })
433         })
434         .collect()
435 }
436
437 #[derive(Debug, Eq, PartialEq)]
438 pub struct SpannedRange<T> {
439     pub span: Span,
440     pub node: (T, Bound<T>),
441 }
442
443 type TypedRanges = Vec<SpannedRange<ConstInt>>;
444
445 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway and other types than
446 /// `Uint` and `Int` probably don't make sense.
447 fn type_ranges(ranges: &[SpannedRange<ConstVal>]) -> TypedRanges {
448     ranges.iter()
449         .filter_map(|range| match range.node {
450             (ConstVal::Integral(start), Bound::Included(ConstVal::Integral(end))) => {
451                 Some(SpannedRange {
452                     span: range.span,
453                     node: (start, Bound::Included(end)),
454                 })
455             },
456             (ConstVal::Integral(start), Bound::Excluded(ConstVal::Integral(end))) => {
457                 Some(SpannedRange {
458                     span: range.span,
459                     node: (start, Bound::Excluded(end)),
460                 })
461             },
462             (ConstVal::Integral(start), Bound::Unbounded) => {
463                 Some(SpannedRange {
464                     span: range.span,
465                     node: (start, Bound::Unbounded),
466                 })
467             },
468             _ => None,
469         })
470         .collect()
471 }
472
473 fn is_unit_expr(expr: &Expr) -> bool {
474     match expr.node {
475         ExprTup(ref v) if v.is_empty() => true,
476         ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
477         _ => false,
478     }
479 }
480
481 fn has_only_ref_pats(arms: &[Arm]) -> bool {
482     let mapped = arms.iter()
483         .flat_map(|a| &a.pats)
484         .map(|p| {
485             match p.node {
486                 PatKind::Ref(..) => Some(true),  // &-patterns
487                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
488                 _ => None,                    // any other pattern is not fine
489             }
490         })
491         .collect::<Option<Vec<bool>>>();
492     // look for Some(v) where there's at least one true element
493     mapped.map_or(false, |v| v.iter().any(|el| *el))
494 }
495
496 fn match_template(span: Span, source: MatchSource, expr: &Sugg) -> String {
497     match source {
498         MatchSource::Normal => format!("match {} {{ .. }}", expr),
499         MatchSource::IfLetDesugar { .. } => format!("if let .. = {} {{ .. }}", expr),
500         MatchSource::WhileLetDesugar => format!("while let .. = {} {{ .. }}", expr),
501         MatchSource::ForLoopDesugar => span_bug!(span, "for loop desugared to match with &-patterns!"),
502         MatchSource::TryDesugar => span_bug!(span, "`?` operator desugared to match with &-patterns!"),
503     }
504 }
505
506 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
507     where T: Copy + Ord
508 {
509     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
510     enum Kind<'a, T: 'a> {
511         Start(T, &'a SpannedRange<T>),
512         End(Bound<T>, &'a SpannedRange<T>),
513     }
514
515     impl<'a, T: Copy> Kind<'a, T> {
516         fn range(&self) -> &'a SpannedRange<T> {
517             match *self {
518                 Kind::Start(_, r) |
519                 Kind::End(_, r) => r,
520             }
521         }
522
523         fn value(self) -> Bound<T> {
524             match self {
525                 Kind::Start(t, _) => Bound::Included(t),
526                 Kind::End(t, _) => t,
527             }
528         }
529     }
530
531     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
532         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
533             Some(self.cmp(other))
534         }
535     }
536
537     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
538         fn cmp(&self, other: &Self) -> Ordering {
539             match (self.value(), other.value()) {
540                 (Bound::Included(a), Bound::Included(b)) |
541                 (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
542                 // Range patterns cannot be unbounded (yet)
543                 (Bound::Unbounded, _) |
544                 (_, Bound::Unbounded) => unimplemented!(),
545                 (Bound::Included(a), Bound::Excluded(b)) => {
546                     match a.cmp(&b) {
547                         Ordering::Equal => Ordering::Greater,
548                         other => other,
549                     }
550                 },
551                 (Bound::Excluded(a), Bound::Included(b)) => {
552                     match a.cmp(&b) {
553                         Ordering::Equal => Ordering::Less,
554                         other => other,
555                     }
556                 },
557             }
558         }
559     }
560
561     let mut values = Vec::with_capacity(2 * ranges.len());
562
563     for r in ranges {
564         values.push(Kind::Start(r.node.0, r));
565         values.push(Kind::End(r.node.1, r));
566     }
567
568     values.sort();
569
570     for (a, b) in values.iter().zip(values.iter().skip(1)) {
571         match (a, b) {
572             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
573                 if ra.node != rb.node {
574                     return Some((ra, rb));
575                 }
576             },
577             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
578             _ => return Some((a.range(), b.range())),
579         }
580     }
581
582     None
583 }