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