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