]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Fix cargo crash
[rust.git] / clippy_lints / src / matches.rs
1 use crate::consts::{constant, miri_to_const, Constant};
2 use crate::utils::paths;
3 use crate::utils::sugg::Sugg;
4 use crate::utils::usage::is_unused;
5 use crate::utils::{
6     expr_block, get_arg_name, get_parent_expr, in_macro, indent_of, is_allowed, is_expn_of, is_refutable,
7     is_type_diagnostic_item, is_wild, match_qpath, match_type, match_var, multispan_sugg, remove_blocks, snippet,
8     snippet_block, snippet_with_applicability, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
9     span_lint_and_then, walk_ptrs_ty,
10 };
11 use if_chain::if_chain;
12 use rustc_ast::ast::LitKind;
13 use rustc_errors::Applicability;
14 use rustc_hir::def::CtorKind;
15 use rustc_hir::{
16     Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Local, MatchSource, Mutability, Node, Pat, PatKind,
17     QPath, RangeEnd,
18 };
19 use rustc_lint::{LateContext, LateLintPass, LintContext};
20 use rustc_middle::lint::in_external_macro;
21 use rustc_middle::ty::{self, Ty};
22 use rustc_session::{declare_tool_lint, impl_lint_pass};
23 use rustc_span::source_map::Span;
24 use std::cmp::Ordering;
25 use std::collections::Bound;
26
27 declare_clippy_lint! {
28     /// **What it does:** Checks for matches with a single arm where an `if let`
29     /// will usually suffice.
30     ///
31     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
32     ///
33     /// **Known problems:** None.
34     ///
35     /// **Example:**
36     /// ```rust
37     /// # fn bar(stool: &str) {}
38     /// # let x = Some("abc");
39     /// match x {
40     ///     Some(ref foo) => bar(foo),
41     ///     _ => (),
42     /// }
43     /// ```
44     pub SINGLE_MATCH,
45     style,
46     "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
47 }
48
49 declare_clippy_lint! {
50     /// **What it does:** Checks for matches with two arms where an `if let else` will
51     /// usually suffice.
52     ///
53     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
54     ///
55     /// **Known problems:** Personal style preferences may differ.
56     ///
57     /// **Example:**
58     ///
59     /// Using `match`:
60     ///
61     /// ```rust
62     /// # fn bar(foo: &usize) {}
63     /// # let other_ref: usize = 1;
64     /// # let x: Option<&usize> = Some(&1);
65     /// match x {
66     ///     Some(ref foo) => bar(foo),
67     ///     _ => bar(&other_ref),
68     /// }
69     /// ```
70     ///
71     /// Using `if let` with `else`:
72     ///
73     /// ```rust
74     /// # fn bar(foo: &usize) {}
75     /// # let other_ref: usize = 1;
76     /// # let x: Option<&usize> = Some(&1);
77     /// if let Some(ref foo) = x {
78     ///     bar(foo);
79     /// } else {
80     ///     bar(&other_ref);
81     /// }
82     /// ```
83     pub SINGLE_MATCH_ELSE,
84     pedantic,
85     "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
86 }
87
88 declare_clippy_lint! {
89     /// **What it does:** Checks for matches where all arms match a reference,
90     /// suggesting to remove the reference and deref the matched expression
91     /// instead. It also checks for `if let &foo = bar` blocks.
92     ///
93     /// **Why is this bad?** It just makes the code less readable. That reference
94     /// destructuring adds nothing to the code.
95     ///
96     /// **Known problems:** None.
97     ///
98     /// **Example:**
99     /// ```rust,ignore
100     /// match x {
101     ///     &A(ref y) => foo(y),
102     ///     &B => bar(),
103     ///     _ => frob(&x),
104     /// }
105     /// ```
106     pub MATCH_REF_PATS,
107     style,
108     "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
109 }
110
111 declare_clippy_lint! {
112     /// **What it does:** Checks for matches where match expression is a `bool`. It
113     /// suggests to replace the expression with an `if...else` block.
114     ///
115     /// **Why is this bad?** It makes the code less readable.
116     ///
117     /// **Known problems:** None.
118     ///
119     /// **Example:**
120     /// ```rust
121     /// # fn foo() {}
122     /// # fn bar() {}
123     /// let condition: bool = true;
124     /// match condition {
125     ///     true => foo(),
126     ///     false => bar(),
127     /// }
128     /// ```
129     /// Use if/else instead:
130     /// ```rust
131     /// # fn foo() {}
132     /// # fn bar() {}
133     /// let condition: bool = true;
134     /// if condition {
135     ///     foo();
136     /// } else {
137     ///     bar();
138     /// }
139     /// ```
140     pub MATCH_BOOL,
141     pedantic,
142     "a `match` on a boolean expression instead of an `if..else` block"
143 }
144
145 declare_clippy_lint! {
146     /// **What it does:** Checks for overlapping match arms.
147     ///
148     /// **Why is this bad?** It is likely to be an error and if not, makes the code
149     /// less obvious.
150     ///
151     /// **Known problems:** None.
152     ///
153     /// **Example:**
154     /// ```rust
155     /// let x = 5;
156     /// match x {
157     ///     1...10 => println!("1 ... 10"),
158     ///     5...15 => println!("5 ... 15"),
159     ///     _ => (),
160     /// }
161     /// ```
162     pub MATCH_OVERLAPPING_ARM,
163     style,
164     "a `match` with overlapping arms"
165 }
166
167 declare_clippy_lint! {
168     /// **What it does:** Checks for arm which matches all errors with `Err(_)`
169     /// and take drastic actions like `panic!`.
170     ///
171     /// **Why is this bad?** It is generally a bad practice, just like
172     /// catching all exceptions in java with `catch(Exception)`
173     ///
174     /// **Known problems:** None.
175     ///
176     /// **Example:**
177     /// ```rust
178     /// let x: Result<i32, &str> = Ok(3);
179     /// match x {
180     ///     Ok(_) => println!("ok"),
181     ///     Err(_) => panic!("err"),
182     /// }
183     /// ```
184     pub MATCH_WILD_ERR_ARM,
185     style,
186     "a `match` with `Err(_)` arm and take drastic actions"
187 }
188
189 declare_clippy_lint! {
190     /// **What it does:** Checks for match which is used to add a reference to an
191     /// `Option` value.
192     ///
193     /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
194     ///
195     /// **Known problems:** None.
196     ///
197     /// **Example:**
198     /// ```rust
199     /// let x: Option<()> = None;
200     /// let r: Option<&()> = match x {
201     ///     None => None,
202     ///     Some(ref v) => Some(v),
203     /// };
204     /// ```
205     pub MATCH_AS_REF,
206     complexity,
207     "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
208 }
209
210 declare_clippy_lint! {
211     /// **What it does:** Checks for wildcard enum matches using `_`.
212     ///
213     /// **Why is this bad?** New enum variants added by library updates can be missed.
214     ///
215     /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
216     /// variants, and also may not use correct path to enum if it's not present in the current scope.
217     ///
218     /// **Example:**
219     /// ```rust
220     /// # enum Foo { A(usize), B(usize) }
221     /// # let x = Foo::B(1);
222     /// match x {
223     ///     A => {},
224     ///     _ => {},
225     /// }
226     /// ```
227     pub WILDCARD_ENUM_MATCH_ARM,
228     restriction,
229     "a wildcard enum match arm using `_`"
230 }
231
232 declare_clippy_lint! {
233     /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
234     ///
235     /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
236     /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
237     ///
238     /// **Known problems:** None.
239     ///
240     /// **Example:**
241     /// ```rust
242     /// match "foo" {
243     ///     "a" => {},
244     ///     "bar" | _ => {},
245     /// }
246     /// ```
247     pub WILDCARD_IN_OR_PATTERNS,
248     complexity,
249     "a wildcard pattern used with others patterns in same match arm"
250 }
251
252 declare_clippy_lint! {
253     /// **What it does:** Checks for matches being used to destructure a single-variant enum
254     /// or tuple struct where a `let` will suffice.
255     ///
256     /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
257     ///
258     /// **Known problems:** None.
259     ///
260     /// **Example:**
261     /// ```rust
262     /// enum Wrapper {
263     ///     Data(i32),
264     /// }
265     ///
266     /// let wrapper = Wrapper::Data(42);
267     ///
268     /// let data = match wrapper {
269     ///     Wrapper::Data(i) => i,
270     /// };
271     /// ```
272     ///
273     /// The correct use would be:
274     /// ```rust
275     /// enum Wrapper {
276     ///     Data(i32),
277     /// }
278     ///
279     /// let wrapper = Wrapper::Data(42);
280     /// let Wrapper::Data(data) = wrapper;
281     /// ```
282     pub INFALLIBLE_DESTRUCTURING_MATCH,
283     style,
284     "a `match` statement with a single infallible arm instead of a `let`"
285 }
286
287 declare_clippy_lint! {
288     /// **What it does:** Checks for useless match that binds to only one value.
289     ///
290     /// **Why is this bad?** Readability and needless complexity.
291     ///
292     /// **Known problems:**  Suggested replacements may be incorrect when `match`
293     /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
294     ///
295     /// **Example:**
296     /// ```rust
297     /// # let a = 1;
298     /// # let b = 2;
299     ///
300     /// // Bad
301     /// match (a, b) {
302     ///     (c, d) => {
303     ///         // useless match
304     ///     }
305     /// }
306     ///
307     /// // Good
308     /// let (c, d) = (a, b);
309     /// ```
310     pub MATCH_SINGLE_BINDING,
311     complexity,
312     "a match with a single binding instead of using `let` statement"
313 }
314
315 declare_clippy_lint! {
316     /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
317     ///
318     /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
319     /// matching all enum variants explicitly.
320     ///
321     /// **Known problems:** None.
322     ///
323     /// **Example:**
324     /// ```rust
325     /// # struct A { a: i32 }
326     /// let a = A { a: 5 };
327     ///
328     /// // Bad
329     /// match a {
330     ///     A { a: 5, .. } => {},
331     ///     _ => {},
332     /// }
333     ///
334     /// // Good
335     /// match a {
336     ///     A { a: 5 } => {},
337     ///     _ => {},
338     /// }
339     /// ```
340     pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
341     restriction,
342     "a match on a struct that binds all fields but still uses the wildcard pattern"
343 }
344
345 #[derive(Default)]
346 pub struct Matches {
347     infallible_destructuring_match_linted: bool,
348 }
349
350 impl_lint_pass!(Matches => [
351     SINGLE_MATCH,
352     MATCH_REF_PATS,
353     MATCH_BOOL,
354     SINGLE_MATCH_ELSE,
355     MATCH_OVERLAPPING_ARM,
356     MATCH_WILD_ERR_ARM,
357     MATCH_AS_REF,
358     WILDCARD_ENUM_MATCH_ARM,
359     WILDCARD_IN_OR_PATTERNS,
360     MATCH_SINGLE_BINDING,
361     INFALLIBLE_DESTRUCTURING_MATCH,
362     REST_PAT_IN_FULLY_BOUND_STRUCTS
363 ]);
364
365 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches {
366     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
367         if in_external_macro(cx.sess(), expr.span) {
368             return;
369         }
370         if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
371             check_single_match(cx, ex, arms, expr);
372             check_match_bool(cx, ex, arms, expr);
373             check_overlapping_arms(cx, ex, arms);
374             check_wild_err_arm(cx, ex, arms);
375             check_wild_enum_match(cx, ex, arms);
376             check_match_as_ref(cx, ex, arms, expr);
377             check_wild_in_or_pats(cx, arms);
378
379             if self.infallible_destructuring_match_linted {
380                 self.infallible_destructuring_match_linted = false;
381             } else {
382                 check_match_single_binding(cx, ex, arms, expr);
383             }
384         }
385         if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
386             check_match_ref_pats(cx, ex, arms, expr);
387         }
388     }
389
390     fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>) {
391         if_chain! {
392             if !in_external_macro(cx.sess(), local.span);
393             if !in_macro(local.span);
394             if let Some(ref expr) = local.init;
395             if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind;
396             if arms.len() == 1 && arms[0].guard.is_none();
397             if let PatKind::TupleStruct(
398                 QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pat.kind;
399             if args.len() == 1;
400             if let Some(arg) = get_arg_name(&args[0]);
401             let body = remove_blocks(&arms[0].body);
402             if match_var(body, arg);
403
404             then {
405                 let mut applicability = Applicability::MachineApplicable;
406                 self.infallible_destructuring_match_linted = true;
407                 span_lint_and_sugg(
408                     cx,
409                     INFALLIBLE_DESTRUCTURING_MATCH,
410                     local.span,
411                     "you seem to be trying to use `match` to destructure a single infallible pattern. \
412                     Consider using `let`",
413                     "try this",
414                     format!(
415                         "let {}({}) = {};",
416                         snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
417                         snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
418                         snippet_with_applicability(cx, target.span, "..", &mut applicability),
419                     ),
420                     applicability,
421                 );
422             }
423         }
424     }
425
426     fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat<'_>) {
427         if_chain! {
428             if !in_external_macro(cx.sess(), pat.span);
429             if !in_macro(pat.span);
430             if let PatKind::Struct(ref qpath, fields, true) = pat.kind;
431             if let QPath::Resolved(_, ref path) = qpath;
432             if let Some(def_id) = path.res.opt_def_id();
433             let ty = cx.tcx.type_of(def_id);
434             if let ty::Adt(def, _) = ty.kind;
435             if def.is_struct() || def.is_union();
436             if fields.len() == def.non_enum_variant().fields.len();
437
438             then {
439                 span_lint_and_help(
440                     cx,
441                     REST_PAT_IN_FULLY_BOUND_STRUCTS,
442                     pat.span,
443                     "unnecessary use of `..` pattern in struct binding. All fields were already bound",
444                     None,
445                     "consider removing `..` from this binding",
446                 );
447             }
448         }
449     }
450 }
451
452 #[rustfmt::skip]
453 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
454     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
455         if in_macro(expr.span) {
456             // Don't lint match expressions present in
457             // macro_rules! block
458             return;
459         }
460         if let PatKind::Or(..) = arms[0].pat.kind {
461             // don't lint for or patterns for now, this makes
462             // the lint noisy in unnecessary situations
463             return;
464         }
465         let els = remove_blocks(&arms[1].body);
466         let els = if is_unit_expr(els) {
467             None
468         } else if let ExprKind::Block(_, _) = els.kind {
469             // matches with blocks that contain statements are prettier as `if let + else`
470             Some(els)
471         } else {
472             // allow match arms with just expressions
473             return;
474         };
475         let ty = cx.tables.expr_ty(ex);
476         if ty.kind != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
477             check_single_match_single_pattern(cx, ex, arms, expr, els);
478             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
479         }
480     }
481 }
482
483 fn check_single_match_single_pattern(
484     cx: &LateContext<'_, '_>,
485     ex: &Expr<'_>,
486     arms: &[Arm<'_>],
487     expr: &Expr<'_>,
488     els: Option<&Expr<'_>>,
489 ) {
490     if is_wild(&arms[1].pat) {
491         report_single_match_single_pattern(cx, ex, arms, expr, els);
492     }
493 }
494
495 fn report_single_match_single_pattern(
496     cx: &LateContext<'_, '_>,
497     ex: &Expr<'_>,
498     arms: &[Arm<'_>],
499     expr: &Expr<'_>,
500     els: Option<&Expr<'_>>,
501 ) {
502     let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
503     let els_str = els.map_or(String::new(), |els| {
504         format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
505     });
506     span_lint_and_sugg(
507         cx,
508         lint,
509         expr.span,
510         "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
511          let`",
512         "try this",
513         format!(
514             "if let {} = {} {}{}",
515             snippet(cx, arms[0].pat.span, ".."),
516             snippet(cx, ex.span, ".."),
517             expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
518             els_str,
519         ),
520         Applicability::HasPlaceholders,
521     );
522 }
523
524 fn check_single_match_opt_like(
525     cx: &LateContext<'_, '_>,
526     ex: &Expr<'_>,
527     arms: &[Arm<'_>],
528     expr: &Expr<'_>,
529     ty: Ty<'_>,
530     els: Option<&Expr<'_>>,
531 ) {
532     // list of candidate `Enum`s we know will never get any more members
533     let candidates = &[
534         (&paths::COW, "Borrowed"),
535         (&paths::COW, "Cow::Borrowed"),
536         (&paths::COW, "Cow::Owned"),
537         (&paths::COW, "Owned"),
538         (&paths::OPTION, "None"),
539         (&paths::RESULT, "Err"),
540         (&paths::RESULT, "Ok"),
541     ];
542
543     let path = match arms[1].pat.kind {
544         PatKind::TupleStruct(ref path, ref inner, _) => {
545             // Contains any non wildcard patterns (e.g., `Err(err)`)?
546             if !inner.iter().all(is_wild) {
547                 return;
548             }
549             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
550         },
551         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
552         PatKind::Path(ref path) => {
553             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
554         },
555         _ => return,
556     };
557
558     for &(ty_path, pat_path) in candidates {
559         if path == *pat_path && match_type(cx, ty, ty_path) {
560             report_single_match_single_pattern(cx, ex, arms, expr, els);
561         }
562     }
563 }
564
565 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
566     // Type of expression is `bool`.
567     if cx.tables.expr_ty(ex).kind == ty::Bool {
568         span_lint_and_then(
569             cx,
570             MATCH_BOOL,
571             expr.span,
572             "you seem to be trying to match on a boolean expression",
573             move |diag| {
574                 if arms.len() == 2 {
575                     // no guards
576                     let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
577                         if let ExprKind::Lit(ref lit) = arm_bool.kind {
578                             match lit.node {
579                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
580                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
581                                 _ => None,
582                             }
583                         } else {
584                             None
585                         }
586                     } else {
587                         None
588                     };
589
590                     if let Some((true_expr, false_expr)) = exprs {
591                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
592                             (false, false) => Some(format!(
593                                 "if {} {} else {}",
594                                 snippet(cx, ex.span, "b"),
595                                 expr_block(cx, true_expr, None, "..", Some(expr.span)),
596                                 expr_block(cx, false_expr, None, "..", Some(expr.span))
597                             )),
598                             (false, true) => Some(format!(
599                                 "if {} {}",
600                                 snippet(cx, ex.span, "b"),
601                                 expr_block(cx, true_expr, None, "..", Some(expr.span))
602                             )),
603                             (true, false) => {
604                                 let test = Sugg::hir(cx, ex, "..");
605                                 Some(format!(
606                                     "if {} {}",
607                                     !test,
608                                     expr_block(cx, false_expr, None, "..", Some(expr.span))
609                                 ))
610                             },
611                             (true, true) => None,
612                         };
613
614                         if let Some(sugg) = sugg {
615                             diag.span_suggestion(
616                                 expr.span,
617                                 "consider using an `if`/`else` expression",
618                                 sugg,
619                                 Applicability::HasPlaceholders,
620                             );
621                         }
622                     }
623                 }
624             },
625         );
626     }
627 }
628
629 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
630     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
631         let ranges = all_ranges(cx, arms, cx.tables.expr_ty(ex));
632         let type_ranges = type_ranges(&ranges);
633         if !type_ranges.is_empty() {
634             if let Some((start, end)) = overlapping(&type_ranges) {
635                 span_lint_and_note(
636                     cx,
637                     MATCH_OVERLAPPING_ARM,
638                     start.span,
639                     "some ranges overlap",
640                     Some(end.span),
641                     "overlaps with this",
642                 );
643             }
644         }
645     }
646 }
647
648 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
649     let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
650     if is_type_diagnostic_item(cx, ex_ty, sym!(result_type)) {
651         for arm in arms {
652             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
653                 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
654                 if path_str == "Err" {
655                     let mut matching_wild = inner.iter().any(is_wild);
656                     let mut ident_bind_name = String::from("_");
657                     if !matching_wild {
658                         // Looking for unused bindings (i.e.: `_e`)
659                         inner.iter().for_each(|pat| {
660                             if let PatKind::Binding(.., ident, None) = &pat.kind {
661                                 if ident.as_str().starts_with('_') && is_unused(ident, arm.body) {
662                                     ident_bind_name = (&ident.name.as_str()).to_string();
663                                     matching_wild = true;
664                                 }
665                             }
666                         });
667                     }
668                     if_chain! {
669                         if matching_wild;
670                         if let ExprKind::Block(ref block, _) = arm.body.kind;
671                         if is_panic_block(block);
672                         then {
673                             // `Err(_)` or `Err(_e)` arm with `panic!` found
674                             span_lint_and_note(cx,
675                                 MATCH_WILD_ERR_ARM,
676                                 arm.pat.span,
677                                 &format!("`Err({})` matches all errors", &ident_bind_name),
678                                 None,
679                                 "match each error separately or use the error output",
680                             );
681                         }
682                     }
683                 }
684             }
685         }
686     }
687 }
688
689 fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
690     let ty = cx.tables.expr_ty(ex);
691     if !ty.is_enum() {
692         // If there isn't a nice closed set of possible values that can be conveniently enumerated,
693         // don't complain about not enumerating the mall.
694         return;
695     }
696
697     // First pass - check for violation, but don't do much book-keeping because this is hopefully
698     // the uncommon case, and the book-keeping is slightly expensive.
699     let mut wildcard_span = None;
700     let mut wildcard_ident = None;
701     for arm in arms {
702         if let PatKind::Wild = arm.pat.kind {
703             wildcard_span = Some(arm.pat.span);
704         } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
705             wildcard_span = Some(arm.pat.span);
706             wildcard_ident = Some(ident);
707         }
708     }
709
710     if let Some(wildcard_span) = wildcard_span {
711         // Accumulate the variants which should be put in place of the wildcard because they're not
712         // already covered.
713
714         let mut missing_variants = vec![];
715         if let ty::Adt(def, _) = ty.kind {
716             for variant in &def.variants {
717                 missing_variants.push(variant);
718             }
719         }
720
721         for arm in arms {
722             if arm.guard.is_some() {
723                 // Guards mean that this case probably isn't exhaustively covered. Technically
724                 // this is incorrect, as we should really check whether each variant is exhaustively
725                 // covered by the set of guards that cover it, but that's really hard to do.
726                 continue;
727             }
728             if let PatKind::Path(ref path) = arm.pat.kind {
729                 if let QPath::Resolved(_, p) = path {
730                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
731                 }
732             } else if let PatKind::TupleStruct(ref path, ..) = arm.pat.kind {
733                 if let QPath::Resolved(_, p) = path {
734                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
735                 }
736             }
737         }
738
739         let mut suggestion: Vec<String> = missing_variants
740             .iter()
741             .map(|v| {
742                 let suffix = match v.ctor_kind {
743                     CtorKind::Fn => "(..)",
744                     CtorKind::Const | CtorKind::Fictive => "",
745                 };
746                 let ident_str = if let Some(ident) = wildcard_ident {
747                     format!("{} @ ", ident.name)
748                 } else {
749                     String::new()
750                 };
751                 // This path assumes that the enum type is imported into scope.
752                 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
753             })
754             .collect();
755
756         if suggestion.is_empty() {
757             return;
758         }
759
760         let mut message = "wildcard match will miss any future added variants";
761
762         if let ty::Adt(def, _) = ty.kind {
763             if def.is_variant_list_non_exhaustive() {
764                 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
765                 suggestion.push(String::from("_"));
766             }
767         }
768
769         span_lint_and_sugg(
770             cx,
771             WILDCARD_ENUM_MATCH_ARM,
772             wildcard_span,
773             message,
774             "try this",
775             suggestion.join(" | "),
776             Applicability::MachineApplicable,
777         )
778     }
779 }
780
781 // If the block contains only a `panic!` macro (as expression or statement)
782 fn is_panic_block(block: &Block<'_>) -> bool {
783     match (&block.expr, block.stmts.len(), block.stmts.first()) {
784         (&Some(ref exp), 0, _) => {
785             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
786         },
787         (&None, 1, Some(stmt)) => {
788             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
789         },
790         _ => false,
791     }
792 }
793
794 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
795     if has_only_ref_pats(arms) {
796         let mut suggs = Vec::with_capacity(arms.len() + 1);
797         let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
798             let span = ex.span.source_callsite();
799             suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
800             (
801                 "you don't need to add `&` to both the expression and the patterns",
802                 "try",
803             )
804         } else {
805             let span = ex.span.source_callsite();
806             suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
807             (
808                 "you don't need to add `&` to all patterns",
809                 "instead of prefixing all patterns with `&`, you can dereference the expression",
810             )
811         };
812
813         suggs.extend(arms.iter().filter_map(|a| {
814             if let PatKind::Ref(ref refp, _) = a.pat.kind {
815                 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
816             } else {
817                 None
818             }
819         }));
820
821         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
822             if !expr.span.from_expansion() {
823                 multispan_sugg(diag, msg.to_owned(), suggs);
824             }
825         });
826     }
827 }
828
829 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
830     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
831         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
832             is_ref_some_arm(&arms[1])
833         } else if is_none_arm(&arms[1]) {
834             is_ref_some_arm(&arms[0])
835         } else {
836             None
837         };
838         if let Some(rb) = arm_ref {
839             let suggestion = if rb == BindingAnnotation::Ref {
840                 "as_ref"
841             } else {
842                 "as_mut"
843             };
844
845             let output_ty = cx.tables.expr_ty(expr);
846             let input_ty = cx.tables.expr_ty(ex);
847
848             let cast = if_chain! {
849                 if let ty::Adt(_, substs) = input_ty.kind;
850                 let input_ty = substs.type_at(0);
851                 if let ty::Adt(_, substs) = output_ty.kind;
852                 let output_ty = substs.type_at(0);
853                 if let ty::Ref(_, output_ty, _) = output_ty.kind;
854                 if input_ty != output_ty;
855                 then {
856                     ".map(|x| x as _)"
857                 } else {
858                     ""
859                 }
860             };
861
862             let mut applicability = Applicability::MachineApplicable;
863             span_lint_and_sugg(
864                 cx,
865                 MATCH_AS_REF,
866                 expr.span,
867                 &format!("use `{}()` instead", suggestion),
868                 "try this",
869                 format!(
870                     "{}.{}(){}",
871                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
872                     suggestion,
873                     cast,
874                 ),
875                 applicability,
876             )
877         }
878     }
879 }
880
881 fn check_wild_in_or_pats(cx: &LateContext<'_, '_>, arms: &[Arm<'_>]) {
882     for arm in arms {
883         if let PatKind::Or(ref fields) = arm.pat.kind {
884             // look for multiple fields in this arm that contains at least one Wild pattern
885             if fields.len() > 1 && fields.iter().any(is_wild) {
886                 span_lint_and_help(
887                     cx,
888                     WILDCARD_IN_OR_PATTERNS,
889                     arm.pat.span,
890                     "wildcard pattern covers any other pattern as it will match anyway.",
891                     None,
892                     "Consider handling `_` separately.",
893                 );
894             }
895         }
896     }
897 }
898
899 fn check_match_single_binding<'a>(cx: &LateContext<'_, 'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
900     if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
901         return;
902     }
903     let matched_vars = ex.span;
904     let bind_names = arms[0].pat.span;
905     let match_body = remove_blocks(&arms[0].body);
906     let mut snippet_body = if match_body.span.from_expansion() {
907         Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
908     } else {
909         snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
910     };
911
912     // Do we need to add ';' to suggestion ?
913     match match_body.kind {
914         ExprKind::Block(block, _) => {
915             // macro + expr_ty(body) == ()
916             if block.span.from_expansion() && cx.tables.expr_ty(&match_body).is_unit() {
917                 snippet_body.push(';');
918             }
919         },
920         _ => {
921             // expr_ty(body) == ()
922             if cx.tables.expr_ty(&match_body).is_unit() {
923                 snippet_body.push(';');
924             }
925         },
926     }
927
928     let mut applicability = Applicability::MaybeIncorrect;
929     match arms[0].pat.kind {
930         PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
931             // If this match is in a local (`let`) stmt
932             let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
933                 (
934                     parent_let_node.span,
935                     format!(
936                         "let {} = {};\n{}let {} = {};",
937                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
938                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
939                         " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
940                         snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
941                         snippet_body
942                     ),
943                 )
944             } else {
945                 // If we are in closure, we need curly braces around suggestion
946                 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
947                 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
948                 if let Some(parent_expr) = get_parent_expr(cx, expr) {
949                     if let ExprKind::Closure(..) = parent_expr.kind {
950                         cbrace_end = format!("\n{}}}", indent);
951                         // Fix body indent due to the closure
952                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
953                         cbrace_start = format!("{{\n{}", indent);
954                     }
955                 };
956                 (
957                     expr.span,
958                     format!(
959                         "{}let {} = {};\n{}{}{}",
960                         cbrace_start,
961                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
962                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
963                         indent,
964                         snippet_body,
965                         cbrace_end
966                     ),
967                 )
968             };
969             span_lint_and_sugg(
970                 cx,
971                 MATCH_SINGLE_BINDING,
972                 target_span,
973                 "this match could be written as a `let` statement",
974                 "consider using `let` statement",
975                 sugg,
976                 applicability,
977             );
978         },
979         PatKind::Wild => {
980             span_lint_and_sugg(
981                 cx,
982                 MATCH_SINGLE_BINDING,
983                 expr.span,
984                 "this match could be replaced by its body itself",
985                 "consider using the match body instead",
986                 snippet_body,
987                 Applicability::MachineApplicable,
988             );
989         },
990         _ => (),
991     }
992 }
993
994 /// Returns true if the `ex` match expression is in a local (`let`) statement
995 fn opt_parent_let<'a>(cx: &LateContext<'_, 'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
996     if_chain! {
997         let map = &cx.tcx.hir();
998         if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
999         if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1000         then {
1001             return Some(parent_let_expr);
1002         }
1003     }
1004     None
1005 }
1006
1007 /// Gets all arms that are unbounded `PatRange`s.
1008 fn all_ranges<'a, 'tcx>(
1009     cx: &LateContext<'a, 'tcx>,
1010     arms: &'tcx [Arm<'_>],
1011     ty: Ty<'tcx>,
1012 ) -> Vec<SpannedRange<Constant>> {
1013     arms.iter()
1014         .flat_map(|arm| {
1015             if let Arm {
1016                 ref pat, guard: None, ..
1017             } = *arm
1018             {
1019                 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1020                     let lhs = match lhs {
1021                         Some(lhs) => constant(cx, cx.tables, lhs)?.0,
1022                         None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1023                     };
1024                     let rhs = match rhs {
1025                         Some(rhs) => constant(cx, cx.tables, rhs)?.0,
1026                         None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1027                     };
1028                     let rhs = match range_end {
1029                         RangeEnd::Included => Bound::Included(rhs),
1030                         RangeEnd::Excluded => Bound::Excluded(rhs),
1031                     };
1032                     return Some(SpannedRange {
1033                         span: pat.span,
1034                         node: (lhs, rhs),
1035                     });
1036                 }
1037
1038                 if let PatKind::Lit(ref value) = pat.kind {
1039                     let value = constant(cx, cx.tables, value)?.0;
1040                     return Some(SpannedRange {
1041                         span: pat.span,
1042                         node: (value.clone(), Bound::Included(value)),
1043                     });
1044                 }
1045             }
1046             None
1047         })
1048         .collect()
1049 }
1050
1051 #[derive(Debug, Eq, PartialEq)]
1052 pub struct SpannedRange<T> {
1053     pub span: Span,
1054     pub node: (T, Bound<T>),
1055 }
1056
1057 type TypedRanges = Vec<SpannedRange<u128>>;
1058
1059 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1060 /// and other types than
1061 /// `Uint` and `Int` probably don't make sense.
1062 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1063     ranges
1064         .iter()
1065         .filter_map(|range| match range.node {
1066             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1067                 span: range.span,
1068                 node: (start, Bound::Included(end)),
1069             }),
1070             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1071                 span: range.span,
1072                 node: (start, Bound::Excluded(end)),
1073             }),
1074             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1075                 span: range.span,
1076                 node: (start, Bound::Unbounded),
1077             }),
1078             _ => None,
1079         })
1080         .collect()
1081 }
1082
1083 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1084     match expr.kind {
1085         ExprKind::Tup(ref v) if v.is_empty() => true,
1086         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1087         _ => false,
1088     }
1089 }
1090
1091 // Checks if arm has the form `None => None`
1092 fn is_none_arm(arm: &Arm<'_>) -> bool {
1093     match arm.pat.kind {
1094         PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
1095         _ => false,
1096     }
1097 }
1098
1099 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1100 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
1101     if_chain! {
1102         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
1103         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
1104         if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1105         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1106         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
1107         if let ExprKind::Path(ref some_path) = e.kind;
1108         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
1109         if let ExprKind::Path(ref qpath) = args[0].kind;
1110         if let &QPath::Resolved(_, ref path2) = qpath;
1111         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1112         then {
1113             return Some(rb)
1114         }
1115     }
1116     None
1117 }
1118
1119 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1120     let mapped = arms
1121         .iter()
1122         .map(|a| {
1123             match a.pat.kind {
1124                 PatKind::Ref(..) => Some(true), // &-patterns
1125                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
1126                 _ => None,                      // any other pattern is not fine
1127             }
1128         })
1129         .collect::<Option<Vec<bool>>>();
1130     // look for Some(v) where there's at least one true element
1131     mapped.map_or(false, |v| v.iter().any(|el| *el))
1132 }
1133
1134 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1135 where
1136     T: Copy + Ord,
1137 {
1138     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1139     enum Kind<'a, T> {
1140         Start(T, &'a SpannedRange<T>),
1141         End(Bound<T>, &'a SpannedRange<T>),
1142     }
1143
1144     impl<'a, T: Copy> Kind<'a, T> {
1145         fn range(&self) -> &'a SpannedRange<T> {
1146             match *self {
1147                 Kind::Start(_, r) | Kind::End(_, r) => r,
1148             }
1149         }
1150
1151         fn value(self) -> Bound<T> {
1152             match self {
1153                 Kind::Start(t, _) => Bound::Included(t),
1154                 Kind::End(t, _) => t,
1155             }
1156         }
1157     }
1158
1159     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1160         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1161             Some(self.cmp(other))
1162         }
1163     }
1164
1165     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1166         fn cmp(&self, other: &Self) -> Ordering {
1167             match (self.value(), other.value()) {
1168                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1169                 // Range patterns cannot be unbounded (yet)
1170                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1171                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1172                     Ordering::Equal => Ordering::Greater,
1173                     other => other,
1174                 },
1175                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1176                     Ordering::Equal => Ordering::Less,
1177                     other => other,
1178                 },
1179             }
1180         }
1181     }
1182
1183     let mut values = Vec::with_capacity(2 * ranges.len());
1184
1185     for r in ranges {
1186         values.push(Kind::Start(r.node.0, r));
1187         values.push(Kind::End(r.node.1, r));
1188     }
1189
1190     values.sort();
1191
1192     for (a, b) in values.iter().zip(values.iter().skip(1)) {
1193         match (a, b) {
1194             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1195                 if ra.node != rb.node {
1196                     return Some((ra, rb));
1197                 }
1198             },
1199             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1200             _ => return Some((a.range(), b.range())),
1201         }
1202     }
1203
1204     None
1205 }
1206
1207 #[test]
1208 fn test_overlapping() {
1209     use rustc_span::source_map::DUMMY_SP;
1210
1211     let sp = |s, e| SpannedRange {
1212         span: DUMMY_SP,
1213         node: (s, e),
1214     };
1215
1216     assert_eq!(None, overlapping::<u8>(&[]));
1217     assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
1218     assert_eq!(
1219         None,
1220         overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
1221     );
1222     assert_eq!(
1223         None,
1224         overlapping(&[
1225             sp(1, Bound::Included(4)),
1226             sp(5, Bound::Included(6)),
1227             sp(10, Bound::Included(11))
1228         ],)
1229     );
1230     assert_eq!(
1231         Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
1232         overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
1233     );
1234     assert_eq!(
1235         Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
1236         overlapping(&[
1237             sp(1, Bound::Included(4)),
1238             sp(5, Bound::Included(6)),
1239             sp(6, Bound::Included(11))
1240         ],)
1241     );
1242 }