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