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