]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
02021b873695f9dfc858e8a67955e7e2c809f775
[rust.git] / clippy_lints / src / matches.rs
1 use crate::consts::{constant, miri_to_const, Constant};
2 use crate::utils::sugg::Sugg;
3 use crate::utils::usage::is_unused;
4 use crate::utils::{
5     expr_block, get_arg_name, get_parent_expr, implements_trait, in_macro, indent_of, is_allowed, is_expn_of,
6     is_refutable, is_type_diagnostic_item, is_wild, match_qpath, match_type, match_var, meets_msrv, multispan_sugg,
7     peel_hir_pat_refs, peel_mid_ty_refs, peel_n_hir_expr_refs, remove_blocks, snippet, snippet_block, snippet_opt,
8     snippet_with_applicability, span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then,
9 };
10 use crate::utils::{paths, search_same, SpanlessEq, SpanlessHash};
11 use if_chain::if_chain;
12 use rustc_ast::ast::LitKind;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_errors::Applicability;
15 use rustc_hir::def::CtorKind;
16 use rustc_hir::{
17     Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, Local, MatchSource, Mutability, Node, Pat,
18     PatKind, QPath, RangeEnd,
19 };
20 use rustc_lint::{LateContext, LateLintPass, LintContext};
21 use rustc_middle::lint::in_external_macro;
22 use rustc_middle::ty::{self, Ty, TyS};
23 use rustc_semver::RustcVersion;
24 use rustc_session::{declare_tool_lint, impl_lint_pass};
25 use rustc_span::source_map::{Span, Spanned};
26 use rustc_span::{sym, Symbol};
27 use std::cmp::Ordering;
28 use std::collections::hash_map::Entry;
29 use std::collections::Bound;
30
31 declare_clippy_lint! {
32     /// **What it does:** Checks for matches with a single arm where an `if let`
33     /// will usually suffice.
34     ///
35     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
36     ///
37     /// **Known problems:** None.
38     ///
39     /// **Example:**
40     /// ```rust
41     /// # fn bar(stool: &str) {}
42     /// # let x = Some("abc");
43     /// // Bad
44     /// match x {
45     ///     Some(ref foo) => bar(foo),
46     ///     _ => (),
47     /// }
48     ///
49     /// // Good
50     /// if let Some(ref foo) = x {
51     ///     bar(foo);
52     /// }
53     /// ```
54     pub SINGLE_MATCH,
55     style,
56     "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
57 }
58
59 declare_clippy_lint! {
60     /// **What it does:** Checks for matches with two arms where an `if let else` will
61     /// usually suffice.
62     ///
63     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
64     ///
65     /// **Known problems:** Personal style preferences may differ.
66     ///
67     /// **Example:**
68     ///
69     /// Using `match`:
70     ///
71     /// ```rust
72     /// # fn bar(foo: &usize) {}
73     /// # let other_ref: usize = 1;
74     /// # let x: Option<&usize> = Some(&1);
75     /// match x {
76     ///     Some(ref foo) => bar(foo),
77     ///     _ => bar(&other_ref),
78     /// }
79     /// ```
80     ///
81     /// Using `if let` with `else`:
82     ///
83     /// ```rust
84     /// # fn bar(foo: &usize) {}
85     /// # let other_ref: usize = 1;
86     /// # let x: Option<&usize> = Some(&1);
87     /// if let Some(ref foo) = x {
88     ///     bar(foo);
89     /// } else {
90     ///     bar(&other_ref);
91     /// }
92     /// ```
93     pub SINGLE_MATCH_ELSE,
94     pedantic,
95     "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
96 }
97
98 declare_clippy_lint! {
99     /// **What it does:** Checks for matches where all arms match a reference,
100     /// suggesting to remove the reference and deref the matched expression
101     /// instead. It also checks for `if let &foo = bar` blocks.
102     ///
103     /// **Why is this bad?** It just makes the code less readable. That reference
104     /// destructuring adds nothing to the code.
105     ///
106     /// **Known problems:** None.
107     ///
108     /// **Example:**
109     /// ```rust,ignore
110     /// // Bad
111     /// match x {
112     ///     &A(ref y) => foo(y),
113     ///     &B => bar(),
114     ///     _ => frob(&x),
115     /// }
116     ///
117     /// // Good
118     /// match *x {
119     ///     A(ref y) => foo(y),
120     ///     B => bar(),
121     ///     _ => frob(x),
122     /// }
123     /// ```
124     pub MATCH_REF_PATS,
125     style,
126     "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
127 }
128
129 declare_clippy_lint! {
130     /// **What it does:** Checks for matches where match expression is a `bool`. It
131     /// suggests to replace the expression with an `if...else` block.
132     ///
133     /// **Why is this bad?** It makes the code less readable.
134     ///
135     /// **Known problems:** None.
136     ///
137     /// **Example:**
138     /// ```rust
139     /// # fn foo() {}
140     /// # fn bar() {}
141     /// let condition: bool = true;
142     /// match condition {
143     ///     true => foo(),
144     ///     false => bar(),
145     /// }
146     /// ```
147     /// Use if/else instead:
148     /// ```rust
149     /// # fn foo() {}
150     /// # fn bar() {}
151     /// let condition: bool = true;
152     /// if condition {
153     ///     foo();
154     /// } else {
155     ///     bar();
156     /// }
157     /// ```
158     pub MATCH_BOOL,
159     pedantic,
160     "a `match` on a boolean expression instead of an `if..else` block"
161 }
162
163 declare_clippy_lint! {
164     /// **What it does:** Checks for overlapping match arms.
165     ///
166     /// **Why is this bad?** It is likely to be an error and if not, makes the code
167     /// less obvious.
168     ///
169     /// **Known problems:** None.
170     ///
171     /// **Example:**
172     /// ```rust
173     /// let x = 5;
174     /// match x {
175     ///     1...10 => println!("1 ... 10"),
176     ///     5...15 => println!("5 ... 15"),
177     ///     _ => (),
178     /// }
179     /// ```
180     pub MATCH_OVERLAPPING_ARM,
181     style,
182     "a `match` with overlapping arms"
183 }
184
185 declare_clippy_lint! {
186     /// **What it does:** Checks for arm which matches all errors with `Err(_)`
187     /// and take drastic actions like `panic!`.
188     ///
189     /// **Why is this bad?** It is generally a bad practice, similar to
190     /// catching all exceptions in java with `catch(Exception)`
191     ///
192     /// **Known problems:** None.
193     ///
194     /// **Example:**
195     /// ```rust
196     /// let x: Result<i32, &str> = Ok(3);
197     /// match x {
198     ///     Ok(_) => println!("ok"),
199     ///     Err(_) => panic!("err"),
200     /// }
201     /// ```
202     pub MATCH_WILD_ERR_ARM,
203     pedantic,
204     "a `match` with `Err(_)` arm and take drastic actions"
205 }
206
207 declare_clippy_lint! {
208     /// **What it does:** Checks for match which is used to add a reference to an
209     /// `Option` value.
210     ///
211     /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
212     ///
213     /// **Known problems:** None.
214     ///
215     /// **Example:**
216     /// ```rust
217     /// let x: Option<()> = None;
218     ///
219     /// // Bad
220     /// let r: Option<&()> = match x {
221     ///     None => None,
222     ///     Some(ref v) => Some(v),
223     /// };
224     ///
225     /// // Good
226     /// let r: Option<&()> = x.as_ref();
227     /// ```
228     pub MATCH_AS_REF,
229     complexity,
230     "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
231 }
232
233 declare_clippy_lint! {
234     /// **What it does:** Checks for wildcard enum matches using `_`.
235     ///
236     /// **Why is this bad?** New enum variants added by library updates can be missed.
237     ///
238     /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
239     /// variants, and also may not use correct path to enum if it's not present in the current scope.
240     ///
241     /// **Example:**
242     /// ```rust
243     /// # enum Foo { A(usize), B(usize) }
244     /// # let x = Foo::B(1);
245     /// // Bad
246     /// match x {
247     ///     Foo::A(_) => {},
248     ///     _ => {},
249     /// }
250     ///
251     /// // Good
252     /// match x {
253     ///     Foo::A(_) => {},
254     ///     Foo::B(_) => {},
255     /// }
256     /// ```
257     pub WILDCARD_ENUM_MATCH_ARM,
258     restriction,
259     "a wildcard enum match arm using `_`"
260 }
261
262 declare_clippy_lint! {
263     /// **What it does:** Checks for wildcard enum matches for a single variant.
264     ///
265     /// **Why is this bad?** New enum variants added by library updates can be missed.
266     ///
267     /// **Known problems:** Suggested replacements may not use correct path to enum
268     /// if it's not present in the current scope.
269     ///
270     /// **Example:**
271     ///
272     /// ```rust
273     /// # enum Foo { A, B, C }
274     /// # let x = Foo::B;
275     /// // Bad
276     /// match x {
277     ///     Foo::A => {},
278     ///     Foo::B => {},
279     ///     _ => {},
280     /// }
281     ///
282     /// // Good
283     /// match x {
284     ///     Foo::A => {},
285     ///     Foo::B => {},
286     ///     Foo::C => {},
287     /// }
288     /// ```
289     pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
290     pedantic,
291     "a wildcard enum match for a single variant"
292 }
293
294 declare_clippy_lint! {
295     /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
296     ///
297     /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
298     /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
299     ///
300     /// **Known problems:** None.
301     ///
302     /// **Example:**
303     /// ```rust
304     /// // Bad
305     /// match "foo" {
306     ///     "a" => {},
307     ///     "bar" | _ => {},
308     /// }
309     ///
310     /// // Good
311     /// match "foo" {
312     ///     "a" => {},
313     ///     _ => {},
314     /// }
315     /// ```
316     pub WILDCARD_IN_OR_PATTERNS,
317     complexity,
318     "a wildcard pattern used with others patterns in same match arm"
319 }
320
321 declare_clippy_lint! {
322     /// **What it does:** Checks for matches being used to destructure a single-variant enum
323     /// or tuple struct where a `let` will suffice.
324     ///
325     /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
326     ///
327     /// **Known problems:** None.
328     ///
329     /// **Example:**
330     /// ```rust
331     /// enum Wrapper {
332     ///     Data(i32),
333     /// }
334     ///
335     /// let wrapper = Wrapper::Data(42);
336     ///
337     /// let data = match wrapper {
338     ///     Wrapper::Data(i) => i,
339     /// };
340     /// ```
341     ///
342     /// The correct use would be:
343     /// ```rust
344     /// enum Wrapper {
345     ///     Data(i32),
346     /// }
347     ///
348     /// let wrapper = Wrapper::Data(42);
349     /// let Wrapper::Data(data) = wrapper;
350     /// ```
351     pub INFALLIBLE_DESTRUCTURING_MATCH,
352     style,
353     "a `match` statement with a single infallible arm instead of a `let`"
354 }
355
356 declare_clippy_lint! {
357     /// **What it does:** Checks for useless match that binds to only one value.
358     ///
359     /// **Why is this bad?** Readability and needless complexity.
360     ///
361     /// **Known problems:**  Suggested replacements may be incorrect when `match`
362     /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
363     ///
364     /// **Example:**
365     /// ```rust
366     /// # let a = 1;
367     /// # let b = 2;
368     ///
369     /// // Bad
370     /// match (a, b) {
371     ///     (c, d) => {
372     ///         // useless match
373     ///     }
374     /// }
375     ///
376     /// // Good
377     /// let (c, d) = (a, b);
378     /// ```
379     pub MATCH_SINGLE_BINDING,
380     complexity,
381     "a match with a single binding instead of using `let` statement"
382 }
383
384 declare_clippy_lint! {
385     /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
386     ///
387     /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
388     /// matching all enum variants explicitly.
389     ///
390     /// **Known problems:** None.
391     ///
392     /// **Example:**
393     /// ```rust
394     /// # struct A { a: i32 }
395     /// let a = A { a: 5 };
396     ///
397     /// // Bad
398     /// match a {
399     ///     A { a: 5, .. } => {},
400     ///     _ => {},
401     /// }
402     ///
403     /// // Good
404     /// match a {
405     ///     A { a: 5 } => {},
406     ///     _ => {},
407     /// }
408     /// ```
409     pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
410     restriction,
411     "a match on a struct that binds all fields but still uses the wildcard pattern"
412 }
413
414 declare_clippy_lint! {
415     /// **What it does:** Lint for redundant pattern matching over `Result`, `Option`,
416     /// `std::task::Poll` or `std::net::IpAddr`
417     ///
418     /// **Why is this bad?** It's more concise and clear to just use the proper
419     /// utility function
420     ///
421     /// **Known problems:** None.
422     ///
423     /// **Example:**
424     ///
425     /// ```rust
426     /// # use std::task::Poll;
427     /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
428     /// if let Ok(_) = Ok::<i32, i32>(42) {}
429     /// if let Err(_) = Err::<i32, i32>(42) {}
430     /// if let None = None::<()> {}
431     /// if let Some(_) = Some(42) {}
432     /// if let Poll::Pending = Poll::Pending::<()> {}
433     /// if let Poll::Ready(_) = Poll::Ready(42) {}
434     /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
435     /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
436     /// match Ok::<i32, i32>(42) {
437     ///     Ok(_) => true,
438     ///     Err(_) => false,
439     /// };
440     /// ```
441     ///
442     /// The more idiomatic use would be:
443     ///
444     /// ```rust
445     /// # use std::task::Poll;
446     /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
447     /// if Ok::<i32, i32>(42).is_ok() {}
448     /// if Err::<i32, i32>(42).is_err() {}
449     /// if None::<()>.is_none() {}
450     /// if Some(42).is_some() {}
451     /// if Poll::Pending::<()>.is_pending() {}
452     /// if Poll::Ready(42).is_ready() {}
453     /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
454     /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
455     /// Ok::<i32, i32>(42).is_ok();
456     /// ```
457     pub REDUNDANT_PATTERN_MATCHING,
458     style,
459     "use the proper utility function avoiding an `if let`"
460 }
461
462 declare_clippy_lint! {
463     /// **What it does:** Checks for `match`  or `if let` expressions producing a
464     /// `bool` that could be written using `matches!`
465     ///
466     /// **Why is this bad?** Readability and needless complexity.
467     ///
468     /// **Known problems:** This lint falsely triggers, if there are arms with
469     /// `cfg` attributes that remove an arm evaluating to `false`.
470     ///
471     /// **Example:**
472     /// ```rust
473     /// let x = Some(5);
474     ///
475     /// // Bad
476     /// let a = match x {
477     ///     Some(0) => true,
478     ///     _ => false,
479     /// };
480     ///
481     /// let a = if let Some(0) = x {
482     ///     true
483     /// } else {
484     ///     false
485     /// };
486     ///
487     /// // Good
488     /// let a = matches!(x, Some(0));
489     /// ```
490     pub MATCH_LIKE_MATCHES_MACRO,
491     style,
492     "a match that could be written with the matches! macro"
493 }
494
495 declare_clippy_lint! {
496     /// **What it does:** Checks for `match` with identical arm bodies.
497     ///
498     /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
499     /// are the same on purpose, you can factor them
500     /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
501     ///
502     /// **Known problems:** False positive possible with order dependent `match`
503     /// (see issue
504     /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
505     ///
506     /// **Example:**
507     /// ```rust,ignore
508     /// match foo {
509     ///     Bar => bar(),
510     ///     Quz => quz(),
511     ///     Baz => bar(), // <= oops
512     /// }
513     /// ```
514     ///
515     /// This should probably be
516     /// ```rust,ignore
517     /// match foo {
518     ///     Bar => bar(),
519     ///     Quz => quz(),
520     ///     Baz => baz(), // <= fixed
521     /// }
522     /// ```
523     ///
524     /// or if the original code was not a typo:
525     /// ```rust,ignore
526     /// match foo {
527     ///     Bar | Baz => bar(), // <= shows the intent better
528     ///     Quz => quz(),
529     /// }
530     /// ```
531     pub MATCH_SAME_ARMS,
532     pedantic,
533     "`match` with identical arm bodies"
534 }
535
536 #[derive(Default)]
537 pub struct Matches {
538     msrv: Option<RustcVersion>,
539     infallible_destructuring_match_linted: bool,
540 }
541
542 impl Matches {
543     #[must_use]
544     pub fn new(msrv: Option<RustcVersion>) -> Self {
545         Self {
546             msrv,
547             ..Matches::default()
548         }
549     }
550 }
551
552 impl_lint_pass!(Matches => [
553     SINGLE_MATCH,
554     MATCH_REF_PATS,
555     MATCH_BOOL,
556     SINGLE_MATCH_ELSE,
557     MATCH_OVERLAPPING_ARM,
558     MATCH_WILD_ERR_ARM,
559     MATCH_AS_REF,
560     WILDCARD_ENUM_MATCH_ARM,
561     MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
562     WILDCARD_IN_OR_PATTERNS,
563     MATCH_SINGLE_BINDING,
564     INFALLIBLE_DESTRUCTURING_MATCH,
565     REST_PAT_IN_FULLY_BOUND_STRUCTS,
566     REDUNDANT_PATTERN_MATCHING,
567     MATCH_LIKE_MATCHES_MACRO,
568     MATCH_SAME_ARMS,
569 ]);
570
571 const MATCH_LIKE_MATCHES_MACRO_MSRV: RustcVersion = RustcVersion::new(1, 42, 0);
572
573 impl<'tcx> LateLintPass<'tcx> for Matches {
574     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
575         if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) {
576             return;
577         }
578
579         redundant_pattern_match::check(cx, expr);
580
581         if meets_msrv(self.msrv.as_ref(), &MATCH_LIKE_MATCHES_MACRO_MSRV) {
582             if !check_match_like_matches(cx, expr) {
583                 lint_match_arms(cx, expr);
584             }
585         } else {
586             lint_match_arms(cx, expr);
587         }
588
589         if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
590             check_single_match(cx, ex, arms, expr);
591             check_match_bool(cx, ex, arms, expr);
592             check_overlapping_arms(cx, ex, arms);
593             check_wild_err_arm(cx, ex, arms);
594             check_wild_enum_match(cx, ex, arms);
595             check_match_as_ref(cx, ex, arms, expr);
596             check_wild_in_or_pats(cx, arms);
597
598             if self.infallible_destructuring_match_linted {
599                 self.infallible_destructuring_match_linted = false;
600             } else {
601                 check_match_single_binding(cx, ex, arms, expr);
602             }
603         }
604         if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
605             check_match_ref_pats(cx, ex, arms, expr);
606         }
607     }
608
609     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
610         if_chain! {
611             if !in_external_macro(cx.sess(), local.span);
612             if !in_macro(local.span);
613             if let Some(ref expr) = local.init;
614             if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind;
615             if arms.len() == 1 && arms[0].guard.is_none();
616             if let PatKind::TupleStruct(
617                 QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pat.kind;
618             if args.len() == 1;
619             if let Some(arg) = get_arg_name(&args[0]);
620             let body = remove_blocks(&arms[0].body);
621             if match_var(body, arg);
622
623             then {
624                 let mut applicability = Applicability::MachineApplicable;
625                 self.infallible_destructuring_match_linted = true;
626                 span_lint_and_sugg(
627                     cx,
628                     INFALLIBLE_DESTRUCTURING_MATCH,
629                     local.span,
630                     "you seem to be trying to use `match` to destructure a single infallible pattern. \
631                     Consider using `let`",
632                     "try this",
633                     format!(
634                         "let {}({}) = {};",
635                         snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
636                         snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
637                         snippet_with_applicability(cx, target.span, "..", &mut applicability),
638                     ),
639                     applicability,
640                 );
641             }
642         }
643     }
644
645     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
646         if_chain! {
647             if !in_external_macro(cx.sess(), pat.span);
648             if !in_macro(pat.span);
649             if let PatKind::Struct(QPath::Resolved(_, ref path), fields, true) = pat.kind;
650             if let Some(def_id) = path.res.opt_def_id();
651             let ty = cx.tcx.type_of(def_id);
652             if let ty::Adt(def, _) = ty.kind();
653             if def.is_struct() || def.is_union();
654             if fields.len() == def.non_enum_variant().fields.len();
655
656             then {
657                 span_lint_and_help(
658                     cx,
659                     REST_PAT_IN_FULLY_BOUND_STRUCTS,
660                     pat.span,
661                     "unnecessary use of `..` pattern in struct binding. All fields were already bound",
662                     None,
663                     "consider removing `..` from this binding",
664                 );
665             }
666         }
667     }
668
669     extract_msrv_attr!(LateContext);
670 }
671
672 #[rustfmt::skip]
673 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
674     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
675         if in_macro(expr.span) {
676             // Don't lint match expressions present in
677             // macro_rules! block
678             return;
679         }
680         if let PatKind::Or(..) = arms[0].pat.kind {
681             // don't lint for or patterns for now, this makes
682             // the lint noisy in unnecessary situations
683             return;
684         }
685         let els = arms[1].body;
686         let els = if is_unit_expr(remove_blocks(els)) {
687             None
688         } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
689             if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
690                 // single statement/expr "else" block, don't lint
691                 return;
692             }
693             // block with 2+ statements or 1 expr and 1+ statement
694             Some(els)
695         } else {
696             // not a block, don't lint
697             return;
698         };
699
700         let ty = cx.typeck_results().expr_ty(ex);
701         if *ty.kind() != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
702             check_single_match_single_pattern(cx, ex, arms, expr, els);
703             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
704         }
705     }
706 }
707
708 fn check_single_match_single_pattern(
709     cx: &LateContext<'_>,
710     ex: &Expr<'_>,
711     arms: &[Arm<'_>],
712     expr: &Expr<'_>,
713     els: Option<&Expr<'_>>,
714 ) {
715     if is_wild(&arms[1].pat) {
716         report_single_match_single_pattern(cx, ex, arms, expr, els);
717     }
718 }
719
720 fn report_single_match_single_pattern(
721     cx: &LateContext<'_>,
722     ex: &Expr<'_>,
723     arms: &[Arm<'_>],
724     expr: &Expr<'_>,
725     els: Option<&Expr<'_>>,
726 ) {
727     let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
728     let els_str = els.map_or(String::new(), |els| {
729         format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
730     });
731
732     let (msg, sugg) = if_chain! {
733         let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
734         if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind;
735         let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex));
736         if let Some(trait_id) = cx.tcx.lang_items().structural_peq_trait();
737         if ty.is_integral() || ty.is_char() || ty.is_str() || implements_trait(cx, ty, trait_id, &[]);
738         then {
739             // scrutinee derives PartialEq and the pattern is a constant.
740             let pat_ref_count = match pat.kind {
741                 // string literals are already a reference.
742                 PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1,
743                 _ => pat_ref_count,
744             };
745             // References are only implicitly added to the pattern, so no overflow here.
746             // e.g. will work: match &Some(_) { Some(_) => () }
747             // will not: match Some(_) { &Some(_) => () }
748             let ref_count_diff = ty_ref_count - pat_ref_count;
749
750             // Try to remove address of expressions first.
751             let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff);
752             let ref_count_diff = ref_count_diff - removed;
753
754             let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
755             let sugg = format!(
756                 "if {} == {}{} {}{}",
757                 snippet(cx, ex.span, ".."),
758                 // PartialEq for different reference counts may not exist.
759                 "&".repeat(ref_count_diff),
760                 snippet(cx, arms[0].pat.span, ".."),
761                 expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
762                 els_str,
763             );
764             (msg, sugg)
765         } else {
766             let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
767             let sugg = format!(
768                 "if let {} = {} {}{}",
769                 snippet(cx, arms[0].pat.span, ".."),
770                 snippet(cx, ex.span, ".."),
771                 expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
772                 els_str,
773             );
774             (msg, sugg)
775         }
776     };
777
778     span_lint_and_sugg(
779         cx,
780         lint,
781         expr.span,
782         msg,
783         "try this",
784         sugg,
785         Applicability::HasPlaceholders,
786     );
787 }
788
789 fn check_single_match_opt_like(
790     cx: &LateContext<'_>,
791     ex: &Expr<'_>,
792     arms: &[Arm<'_>],
793     expr: &Expr<'_>,
794     ty: Ty<'_>,
795     els: Option<&Expr<'_>>,
796 ) {
797     // list of candidate `Enum`s we know will never get any more members
798     let candidates = &[
799         (&paths::COW, "Borrowed"),
800         (&paths::COW, "Cow::Borrowed"),
801         (&paths::COW, "Cow::Owned"),
802         (&paths::COW, "Owned"),
803         (&paths::OPTION, "None"),
804         (&paths::RESULT, "Err"),
805         (&paths::RESULT, "Ok"),
806     ];
807
808     let path = match arms[1].pat.kind {
809         PatKind::TupleStruct(ref path, ref inner, _) => {
810             // Contains any non wildcard patterns (e.g., `Err(err)`)?
811             if !inner.iter().all(is_wild) {
812                 return;
813             }
814             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
815         },
816         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
817         PatKind::Path(ref path) => {
818             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
819         },
820         _ => return,
821     };
822
823     for &(ty_path, pat_path) in candidates {
824         if path == *pat_path && match_type(cx, ty, ty_path) {
825             report_single_match_single_pattern(cx, ex, arms, expr, els);
826         }
827     }
828 }
829
830 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
831     // Type of expression is `bool`.
832     if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
833         span_lint_and_then(
834             cx,
835             MATCH_BOOL,
836             expr.span,
837             "you seem to be trying to match on a boolean expression",
838             move |diag| {
839                 if arms.len() == 2 {
840                     // no guards
841                     let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
842                         if let ExprKind::Lit(ref lit) = arm_bool.kind {
843                             match lit.node {
844                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
845                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
846                                 _ => None,
847                             }
848                         } else {
849                             None
850                         }
851                     } else {
852                         None
853                     };
854
855                     if let Some((true_expr, false_expr)) = exprs {
856                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
857                             (false, false) => Some(format!(
858                                 "if {} {} else {}",
859                                 snippet(cx, ex.span, "b"),
860                                 expr_block(cx, true_expr, None, "..", Some(expr.span)),
861                                 expr_block(cx, false_expr, None, "..", Some(expr.span))
862                             )),
863                             (false, true) => Some(format!(
864                                 "if {} {}",
865                                 snippet(cx, ex.span, "b"),
866                                 expr_block(cx, true_expr, None, "..", Some(expr.span))
867                             )),
868                             (true, false) => {
869                                 let test = Sugg::hir(cx, ex, "..");
870                                 Some(format!(
871                                     "if {} {}",
872                                     !test,
873                                     expr_block(cx, false_expr, None, "..", Some(expr.span))
874                                 ))
875                             },
876                             (true, true) => None,
877                         };
878
879                         if let Some(sugg) = sugg {
880                             diag.span_suggestion(
881                                 expr.span,
882                                 "consider using an `if`/`else` expression",
883                                 sugg,
884                                 Applicability::HasPlaceholders,
885                             );
886                         }
887                     }
888                 }
889             },
890         );
891     }
892 }
893
894 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
895     if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
896         let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
897         let type_ranges = type_ranges(&ranges);
898         if !type_ranges.is_empty() {
899             if let Some((start, end)) = overlapping(&type_ranges) {
900                 span_lint_and_note(
901                     cx,
902                     MATCH_OVERLAPPING_ARM,
903                     start.span,
904                     "some ranges overlap",
905                     Some(end.span),
906                     "overlaps with this",
907                 );
908             }
909         }
910     }
911 }
912
913 fn check_wild_err_arm(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
914     let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
915     if is_type_diagnostic_item(cx, ex_ty, sym::result_type) {
916         for arm in arms {
917             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
918                 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
919                 if path_str == "Err" {
920                     let mut matching_wild = inner.iter().any(is_wild);
921                     let mut ident_bind_name = String::from("_");
922                     if !matching_wild {
923                         // Looking for unused bindings (i.e.: `_e`)
924                         inner.iter().for_each(|pat| {
925                             if let PatKind::Binding(.., ident, None) = &pat.kind {
926                                 if ident.as_str().starts_with('_') && is_unused(ident, arm.body) {
927                                     ident_bind_name = (&ident.name.as_str()).to_string();
928                                     matching_wild = true;
929                                 }
930                             }
931                         });
932                     }
933                     if_chain! {
934                         if matching_wild;
935                         if let ExprKind::Block(ref block, _) = arm.body.kind;
936                         if is_panic_block(block);
937                         then {
938                             // `Err(_)` or `Err(_e)` arm with `panic!` found
939                             span_lint_and_note(cx,
940                                 MATCH_WILD_ERR_ARM,
941                                 arm.pat.span,
942                                 &format!("`Err({})` matches all errors", &ident_bind_name),
943                                 None,
944                                 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
945                             );
946                         }
947                     }
948                 }
949             }
950         }
951     }
952 }
953
954 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
955     let ty = cx.typeck_results().expr_ty(ex);
956     if !ty.is_enum() {
957         // If there isn't a nice closed set of possible values that can be conveniently enumerated,
958         // don't complain about not enumerating the mall.
959         return;
960     }
961
962     // First pass - check for violation, but don't do much book-keeping because this is hopefully
963     // the uncommon case, and the book-keeping is slightly expensive.
964     let mut wildcard_span = None;
965     let mut wildcard_ident = None;
966     for arm in arms {
967         if let PatKind::Wild = arm.pat.kind {
968             wildcard_span = Some(arm.pat.span);
969         } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
970             wildcard_span = Some(arm.pat.span);
971             wildcard_ident = Some(ident);
972         }
973     }
974
975     if let Some(wildcard_span) = wildcard_span {
976         // Accumulate the variants which should be put in place of the wildcard because they're not
977         // already covered.
978
979         let mut missing_variants = vec![];
980         if let ty::Adt(def, _) = ty.kind() {
981             for variant in &def.variants {
982                 missing_variants.push(variant);
983             }
984         }
985
986         for arm in arms {
987             if arm.guard.is_some() {
988                 // Guards mean that this case probably isn't exhaustively covered. Technically
989                 // this is incorrect, as we should really check whether each variant is exhaustively
990                 // covered by the set of guards that cover it, but that's really hard to do.
991                 continue;
992             }
993             if let PatKind::Path(ref path) = arm.pat.kind {
994                 if let QPath::Resolved(_, p) = path {
995                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
996                 }
997             } else if let PatKind::TupleStruct(QPath::Resolved(_, p), ref patterns, ..) = arm.pat.kind {
998                 // Some simple checks for exhaustive patterns.
999                 // There is a room for improvements to detect more cases,
1000                 // but it can be more expensive to do so.
1001                 let is_pattern_exhaustive =
1002                     |pat: &&Pat<'_>| matches!(pat.kind, PatKind::Wild | PatKind::Binding(.., None));
1003                 if patterns.iter().all(is_pattern_exhaustive) {
1004                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
1005                 }
1006             }
1007         }
1008
1009         let mut suggestion: Vec<String> = missing_variants
1010             .iter()
1011             .map(|v| {
1012                 let suffix = match v.ctor_kind {
1013                     CtorKind::Fn => "(..)",
1014                     CtorKind::Const | CtorKind::Fictive => "",
1015                 };
1016                 let ident_str = if let Some(ident) = wildcard_ident {
1017                     format!("{} @ ", ident.name)
1018                 } else {
1019                     String::new()
1020                 };
1021                 // This path assumes that the enum type is imported into scope.
1022                 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
1023             })
1024             .collect();
1025
1026         if suggestion.is_empty() {
1027             return;
1028         }
1029
1030         let mut message = "wildcard match will miss any future added variants";
1031
1032         if let ty::Adt(def, _) = ty.kind() {
1033             if def.is_variant_list_non_exhaustive() {
1034                 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
1035                 suggestion.push(String::from("_"));
1036             }
1037         }
1038
1039         if suggestion.len() == 1 {
1040             // No need to check for non-exhaustive enum as in that case len would be greater than 1
1041             span_lint_and_sugg(
1042                 cx,
1043                 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1044                 wildcard_span,
1045                 message,
1046                 "try this",
1047                 suggestion[0].clone(),
1048                 Applicability::MaybeIncorrect,
1049             )
1050         };
1051
1052         span_lint_and_sugg(
1053             cx,
1054             WILDCARD_ENUM_MATCH_ARM,
1055             wildcard_span,
1056             message,
1057             "try this",
1058             suggestion.join(" | "),
1059             Applicability::MaybeIncorrect,
1060         )
1061     }
1062 }
1063
1064 // If the block contains only a `panic!` macro (as expression or statement)
1065 fn is_panic_block(block: &Block<'_>) -> bool {
1066     match (&block.expr, block.stmts.len(), block.stmts.first()) {
1067         (&Some(ref exp), 0, _) => {
1068             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
1069         },
1070         (&None, 1, Some(stmt)) => {
1071             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
1072         },
1073         _ => false,
1074     }
1075 }
1076
1077 fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1078     if has_only_ref_pats(arms) {
1079         let mut suggs = Vec::with_capacity(arms.len() + 1);
1080         let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
1081             let span = ex.span.source_callsite();
1082             suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1083             (
1084                 "you don't need to add `&` to both the expression and the patterns",
1085                 "try",
1086             )
1087         } else {
1088             let span = ex.span.source_callsite();
1089             suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1090             (
1091                 "you don't need to add `&` to all patterns",
1092                 "instead of prefixing all patterns with `&`, you can dereference the expression",
1093             )
1094         };
1095
1096         suggs.extend(arms.iter().filter_map(|a| {
1097             if let PatKind::Ref(ref refp, _) = a.pat.kind {
1098                 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
1099             } else {
1100                 None
1101             }
1102         }));
1103
1104         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1105             if !expr.span.from_expansion() {
1106                 multispan_sugg(diag, msg, suggs);
1107             }
1108         });
1109     }
1110 }
1111
1112 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1113     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1114         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
1115             is_ref_some_arm(&arms[1])
1116         } else if is_none_arm(&arms[1]) {
1117             is_ref_some_arm(&arms[0])
1118         } else {
1119             None
1120         };
1121         if let Some(rb) = arm_ref {
1122             let suggestion = if rb == BindingAnnotation::Ref {
1123                 "as_ref"
1124             } else {
1125                 "as_mut"
1126             };
1127
1128             let output_ty = cx.typeck_results().expr_ty(expr);
1129             let input_ty = cx.typeck_results().expr_ty(ex);
1130
1131             let cast = if_chain! {
1132                 if let ty::Adt(_, substs) = input_ty.kind();
1133                 let input_ty = substs.type_at(0);
1134                 if let ty::Adt(_, substs) = output_ty.kind();
1135                 let output_ty = substs.type_at(0);
1136                 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1137                 if input_ty != output_ty;
1138                 then {
1139                     ".map(|x| x as _)"
1140                 } else {
1141                     ""
1142                 }
1143             };
1144
1145             let mut applicability = Applicability::MachineApplicable;
1146             span_lint_and_sugg(
1147                 cx,
1148                 MATCH_AS_REF,
1149                 expr.span,
1150                 &format!("use `{}()` instead", suggestion),
1151                 "try this",
1152                 format!(
1153                     "{}.{}(){}",
1154                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1155                     suggestion,
1156                     cast,
1157                 ),
1158                 applicability,
1159             )
1160         }
1161     }
1162 }
1163
1164 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1165     for arm in arms {
1166         if let PatKind::Or(ref fields) = arm.pat.kind {
1167             // look for multiple fields in this arm that contains at least one Wild pattern
1168             if fields.len() > 1 && fields.iter().any(is_wild) {
1169                 span_lint_and_help(
1170                     cx,
1171                     WILDCARD_IN_OR_PATTERNS,
1172                     arm.pat.span,
1173                     "wildcard pattern covers any other pattern as it will match anyway.",
1174                     None,
1175                     "Consider handling `_` separately.",
1176                 );
1177             }
1178         }
1179     }
1180 }
1181
1182 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1183 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1184     if let ExprKind::Match(ex, arms, ref match_source) = &expr.kind {
1185         match match_source {
1186             MatchSource::Normal => find_matches_sugg(cx, ex, arms, expr, false),
1187             MatchSource::IfLetDesugar { .. } => find_matches_sugg(cx, ex, arms, expr, true),
1188             _ => false,
1189         }
1190     } else {
1191         false
1192     }
1193 }
1194
1195 /// Lint a `match` or desugared `if let` for replacement by `matches!`
1196 fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>, desugared: bool) -> bool {
1197     if_chain! {
1198         if arms.len() >= 2;
1199         if cx.typeck_results().expr_ty(expr).is_bool();
1200         if let Some((b1_arm, b0_arms)) = arms.split_last();
1201         if let Some(b0) = find_bool_lit(&b0_arms[0].body.kind, desugared);
1202         if let Some(b1) = find_bool_lit(&b1_arm.body.kind, desugared);
1203         if is_wild(&b1_arm.pat);
1204         if b0 != b1;
1205         let if_guard = &b0_arms[0].guard;
1206         if if_guard.is_none() || b0_arms.len() == 1;
1207         if b0_arms[0].attrs.is_empty();
1208         if b0_arms[1..].iter()
1209             .all(|arm| {
1210                 find_bool_lit(&arm.body.kind, desugared).map_or(false, |b| b == b0) &&
1211                 arm.guard.is_none() && arm.attrs.is_empty()
1212             });
1213         then {
1214             // The suggestion may be incorrect, because some arms can have `cfg` attributes
1215             // evaluated into `false` and so such arms will be stripped before.
1216             let mut applicability = Applicability::MaybeIncorrect;
1217             let pat = {
1218                 use itertools::Itertools as _;
1219                 b0_arms.iter()
1220                     .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability))
1221                     .join(" | ")
1222             };
1223             let pat_and_guard = if let Some(Guard::If(g)) = if_guard {
1224                 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1225             } else {
1226                 pat
1227             };
1228             span_lint_and_sugg(
1229                 cx,
1230                 MATCH_LIKE_MATCHES_MACRO,
1231                 expr.span,
1232                 &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }),
1233                 "try this",
1234                 format!(
1235                     "{}matches!({}, {})",
1236                     if b0 { "" } else { "!" },
1237                     snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1238                     pat_and_guard,
1239                 ),
1240                 applicability,
1241             );
1242             true
1243         } else {
1244             false
1245         }
1246     }
1247 }
1248
1249 /// Extract a `bool` or `{ bool }`
1250 fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option<bool> {
1251     match ex {
1252         ExprKind::Lit(Spanned {
1253             node: LitKind::Bool(b), ..
1254         }) => Some(*b),
1255         ExprKind::Block(
1256             rustc_hir::Block {
1257                 stmts: &[],
1258                 expr: Some(exp),
1259                 ..
1260             },
1261             _,
1262         ) if desugared => {
1263             if let ExprKind::Lit(Spanned {
1264                 node: LitKind::Bool(b), ..
1265             }) = exp.kind
1266             {
1267                 Some(b)
1268             } else {
1269                 None
1270             }
1271         },
1272         _ => None,
1273     }
1274 }
1275
1276 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1277     if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1278         return;
1279     }
1280
1281     // HACK:
1282     // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1283     // to prevent false positives as there is currently no better way to detect if code was excluded by
1284     // a macro. See PR #6435
1285     if_chain! {
1286         if let Some(match_snippet) = snippet_opt(cx, expr.span);
1287         if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1288         if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1289         let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1290         if rest_snippet.contains("=>");
1291         then {
1292             // The code it self contains another thick arrow "=>"
1293             // -> Either another arm or a comment
1294             return;
1295         }
1296     }
1297
1298     let matched_vars = ex.span;
1299     let bind_names = arms[0].pat.span;
1300     let match_body = remove_blocks(&arms[0].body);
1301     let mut snippet_body = if match_body.span.from_expansion() {
1302         Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1303     } else {
1304         snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1305     };
1306
1307     // Do we need to add ';' to suggestion ?
1308     match match_body.kind {
1309         ExprKind::Block(block, _) => {
1310             // macro + expr_ty(body) == ()
1311             if block.span.from_expansion() && cx.typeck_results().expr_ty(&match_body).is_unit() {
1312                 snippet_body.push(';');
1313             }
1314         },
1315         _ => {
1316             // expr_ty(body) == ()
1317             if cx.typeck_results().expr_ty(&match_body).is_unit() {
1318                 snippet_body.push(';');
1319             }
1320         },
1321     }
1322
1323     let mut applicability = Applicability::MaybeIncorrect;
1324     match arms[0].pat.kind {
1325         PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1326             // If this match is in a local (`let`) stmt
1327             let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1328                 (
1329                     parent_let_node.span,
1330                     format!(
1331                         "let {} = {};\n{}let {} = {};",
1332                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1333                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1334                         " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1335                         snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1336                         snippet_body
1337                     ),
1338                 )
1339             } else {
1340                 // If we are in closure, we need curly braces around suggestion
1341                 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1342                 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1343                 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1344                     if let ExprKind::Closure(..) = parent_expr.kind {
1345                         cbrace_end = format!("\n{}}}", indent);
1346                         // Fix body indent due to the closure
1347                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1348                         cbrace_start = format!("{{\n{}", indent);
1349                     }
1350                 };
1351                 (
1352                     expr.span,
1353                     format!(
1354                         "{}let {} = {};\n{}{}{}",
1355                         cbrace_start,
1356                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1357                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1358                         indent,
1359                         snippet_body,
1360                         cbrace_end
1361                     ),
1362                 )
1363             };
1364             span_lint_and_sugg(
1365                 cx,
1366                 MATCH_SINGLE_BINDING,
1367                 target_span,
1368                 "this match could be written as a `let` statement",
1369                 "consider using `let` statement",
1370                 sugg,
1371                 applicability,
1372             );
1373         },
1374         PatKind::Wild => {
1375             span_lint_and_sugg(
1376                 cx,
1377                 MATCH_SINGLE_BINDING,
1378                 expr.span,
1379                 "this match could be replaced by its body itself",
1380                 "consider using the match body instead",
1381                 snippet_body,
1382                 Applicability::MachineApplicable,
1383             );
1384         },
1385         _ => (),
1386     }
1387 }
1388
1389 /// Returns true if the `ex` match expression is in a local (`let`) statement
1390 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1391     if_chain! {
1392         let map = &cx.tcx.hir();
1393         if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1394         if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1395         then {
1396             return Some(parent_let_expr);
1397         }
1398     }
1399     None
1400 }
1401
1402 /// Gets all arms that are unbounded `PatRange`s.
1403 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> {
1404     arms.iter()
1405         .flat_map(|arm| {
1406             if let Arm {
1407                 ref pat, guard: None, ..
1408             } = *arm
1409             {
1410                 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1411                     let lhs = match lhs {
1412                         Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1413                         None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1414                     };
1415                     let rhs = match rhs {
1416                         Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1417                         None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1418                     };
1419                     let rhs = match range_end {
1420                         RangeEnd::Included => Bound::Included(rhs),
1421                         RangeEnd::Excluded => Bound::Excluded(rhs),
1422                     };
1423                     return Some(SpannedRange {
1424                         span: pat.span,
1425                         node: (lhs, rhs),
1426                     });
1427                 }
1428
1429                 if let PatKind::Lit(ref value) = pat.kind {
1430                     let value = constant(cx, cx.typeck_results(), value)?.0;
1431                     return Some(SpannedRange {
1432                         span: pat.span,
1433                         node: (value.clone(), Bound::Included(value)),
1434                     });
1435                 }
1436             }
1437             None
1438         })
1439         .collect()
1440 }
1441
1442 #[derive(Debug, Eq, PartialEq)]
1443 pub struct SpannedRange<T> {
1444     pub span: Span,
1445     pub node: (T, Bound<T>),
1446 }
1447
1448 type TypedRanges = Vec<SpannedRange<u128>>;
1449
1450 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1451 /// and other types than
1452 /// `Uint` and `Int` probably don't make sense.
1453 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1454     ranges
1455         .iter()
1456         .filter_map(|range| match range.node {
1457             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1458                 span: range.span,
1459                 node: (start, Bound::Included(end)),
1460             }),
1461             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1462                 span: range.span,
1463                 node: (start, Bound::Excluded(end)),
1464             }),
1465             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1466                 span: range.span,
1467                 node: (start, Bound::Unbounded),
1468             }),
1469             _ => None,
1470         })
1471         .collect()
1472 }
1473
1474 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1475     match expr.kind {
1476         ExprKind::Tup(ref v) if v.is_empty() => true,
1477         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1478         _ => false,
1479     }
1480 }
1481
1482 // Checks if arm has the form `None => None`
1483 fn is_none_arm(arm: &Arm<'_>) -> bool {
1484     matches!(arm.pat.kind, PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE))
1485 }
1486
1487 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1488 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
1489     if_chain! {
1490         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
1491         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
1492         if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1493         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1494         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
1495         if let ExprKind::Path(ref some_path) = e.kind;
1496         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
1497         if let ExprKind::Path(QPath::Resolved(_, ref path2)) = args[0].kind;
1498         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1499         then {
1500             return Some(rb)
1501         }
1502     }
1503     None
1504 }
1505
1506 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1507     let mapped = arms
1508         .iter()
1509         .map(|a| {
1510             match a.pat.kind {
1511                 PatKind::Ref(..) => Some(true), // &-patterns
1512                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
1513                 _ => None,                      // any other pattern is not fine
1514             }
1515         })
1516         .collect::<Option<Vec<bool>>>();
1517     // look for Some(v) where there's at least one true element
1518     mapped.map_or(false, |v| v.iter().any(|el| *el))
1519 }
1520
1521 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1522 where
1523     T: Copy + Ord,
1524 {
1525     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1526     enum Kind<'a, T> {
1527         Start(T, &'a SpannedRange<T>),
1528         End(Bound<T>, &'a SpannedRange<T>),
1529     }
1530
1531     impl<'a, T: Copy> Kind<'a, T> {
1532         fn range(&self) -> &'a SpannedRange<T> {
1533             match *self {
1534                 Kind::Start(_, r) | Kind::End(_, r) => r,
1535             }
1536         }
1537
1538         fn value(self) -> Bound<T> {
1539             match self {
1540                 Kind::Start(t, _) => Bound::Included(t),
1541                 Kind::End(t, _) => t,
1542             }
1543         }
1544     }
1545
1546     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1547         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1548             Some(self.cmp(other))
1549         }
1550     }
1551
1552     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1553         fn cmp(&self, other: &Self) -> Ordering {
1554             match (self.value(), other.value()) {
1555                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1556                 // Range patterns cannot be unbounded (yet)
1557                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1558                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1559                     Ordering::Equal => Ordering::Greater,
1560                     other => other,
1561                 },
1562                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1563                     Ordering::Equal => Ordering::Less,
1564                     other => other,
1565                 },
1566             }
1567         }
1568     }
1569
1570     let mut values = Vec::with_capacity(2 * ranges.len());
1571
1572     for r in ranges {
1573         values.push(Kind::Start(r.node.0, r));
1574         values.push(Kind::End(r.node.1, r));
1575     }
1576
1577     values.sort();
1578
1579     for (a, b) in values.iter().zip(values.iter().skip(1)) {
1580         match (a, b) {
1581             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1582                 if ra.node != rb.node {
1583                     return Some((ra, rb));
1584                 }
1585             },
1586             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1587             _ => return Some((a.range(), b.range())),
1588         }
1589     }
1590
1591     None
1592 }
1593
1594 mod redundant_pattern_match {
1595     use super::REDUNDANT_PATTERN_MATCHING;
1596     use crate::utils::{match_qpath, match_trait_method, paths, snippet, span_lint_and_then};
1597     use if_chain::if_chain;
1598     use rustc_ast::ast::LitKind;
1599     use rustc_errors::Applicability;
1600     use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind, QPath};
1601     use rustc_lint::LateContext;
1602     use rustc_span::sym;
1603
1604     pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1605         if let ExprKind::Match(op, arms, ref match_source) = &expr.kind {
1606             match match_source {
1607                 MatchSource::Normal => find_sugg_for_match(cx, expr, op, arms),
1608                 MatchSource::IfLetDesugar { .. } => find_sugg_for_if_let(cx, expr, op, arms, "if"),
1609                 MatchSource::WhileLetDesugar => find_sugg_for_if_let(cx, expr, op, arms, "while"),
1610                 _ => {},
1611             }
1612         }
1613     }
1614
1615     fn find_sugg_for_if_let<'tcx>(
1616         cx: &LateContext<'tcx>,
1617         expr: &'tcx Expr<'_>,
1618         op: &Expr<'_>,
1619         arms: &[Arm<'_>],
1620         keyword: &'static str,
1621     ) {
1622         let good_method = match arms[0].pat.kind {
1623             PatKind::TupleStruct(ref path, ref patterns, _) if patterns.len() == 1 => {
1624                 if let PatKind::Wild = patterns[0].kind {
1625                     if match_qpath(path, &paths::RESULT_OK) {
1626                         "is_ok()"
1627                     } else if match_qpath(path, &paths::RESULT_ERR) {
1628                         "is_err()"
1629                     } else if match_qpath(path, &paths::OPTION_SOME) {
1630                         "is_some()"
1631                     } else if match_qpath(path, &paths::POLL_READY) {
1632                         "is_ready()"
1633                     } else if match_qpath(path, &paths::IPADDR_V4) {
1634                         "is_ipv4()"
1635                     } else if match_qpath(path, &paths::IPADDR_V6) {
1636                         "is_ipv6()"
1637                     } else {
1638                         return;
1639                     }
1640                 } else {
1641                     return;
1642                 }
1643             },
1644             PatKind::Path(ref path) => {
1645                 if match_qpath(path, &paths::OPTION_NONE) {
1646                     "is_none()"
1647                 } else if match_qpath(path, &paths::POLL_PENDING) {
1648                     "is_pending()"
1649                 } else {
1650                     return;
1651                 }
1652             },
1653             _ => return,
1654         };
1655
1656         // check that `while_let_on_iterator` lint does not trigger
1657         if_chain! {
1658             if keyword == "while";
1659             if let ExprKind::MethodCall(method_path, _, _, _) = op.kind;
1660             if method_path.ident.name == sym::next;
1661             if match_trait_method(cx, op, &paths::ITERATOR);
1662             then {
1663                 return;
1664             }
1665         }
1666
1667         let result_expr = match &op.kind {
1668             ExprKind::AddrOf(_, _, borrowed) => borrowed,
1669             _ => op,
1670         };
1671         span_lint_and_then(
1672             cx,
1673             REDUNDANT_PATTERN_MATCHING,
1674             arms[0].pat.span,
1675             &format!("redundant pattern matching, consider using `{}`", good_method),
1676             |diag| {
1677                 // while let ... = ... { ... }
1678                 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1679                 let expr_span = expr.span;
1680
1681                 // while let ... = ... { ... }
1682                 //                 ^^^
1683                 let op_span = result_expr.span.source_callsite();
1684
1685                 // while let ... = ... { ... }
1686                 // ^^^^^^^^^^^^^^^^^^^
1687                 let span = expr_span.until(op_span.shrink_to_hi());
1688                 diag.span_suggestion(
1689                     span,
1690                     "try this",
1691                     format!("{} {}.{}", keyword, snippet(cx, op_span, "_"), good_method),
1692                     Applicability::MachineApplicable, // snippet
1693                 );
1694             },
1695         );
1696     }
1697
1698     fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
1699         if arms.len() == 2 {
1700             let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
1701
1702             let found_good_method = match node_pair {
1703                 (
1704                     PatKind::TupleStruct(ref path_left, ref patterns_left, _),
1705                     PatKind::TupleStruct(ref path_right, ref patterns_right, _),
1706                 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
1707                     if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
1708                         find_good_method_for_match(
1709                             arms,
1710                             path_left,
1711                             path_right,
1712                             &paths::RESULT_OK,
1713                             &paths::RESULT_ERR,
1714                             "is_ok()",
1715                             "is_err()",
1716                         )
1717                         .or_else(|| {
1718                             find_good_method_for_match(
1719                                 arms,
1720                                 path_left,
1721                                 path_right,
1722                                 &paths::IPADDR_V4,
1723                                 &paths::IPADDR_V6,
1724                                 "is_ipv4()",
1725                                 "is_ipv6()",
1726                             )
1727                         })
1728                     } else {
1729                         None
1730                     }
1731                 },
1732                 (PatKind::TupleStruct(ref path_left, ref patterns, _), PatKind::Path(ref path_right))
1733                 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, ref patterns, _))
1734                     if patterns.len() == 1 =>
1735                 {
1736                     if let PatKind::Wild = patterns[0].kind {
1737                         find_good_method_for_match(
1738                             arms,
1739                             path_left,
1740                             path_right,
1741                             &paths::OPTION_SOME,
1742                             &paths::OPTION_NONE,
1743                             "is_some()",
1744                             "is_none()",
1745                         )
1746                         .or_else(|| {
1747                             find_good_method_for_match(
1748                                 arms,
1749                                 path_left,
1750                                 path_right,
1751                                 &paths::POLL_READY,
1752                                 &paths::POLL_PENDING,
1753                                 "is_ready()",
1754                                 "is_pending()",
1755                             )
1756                         })
1757                     } else {
1758                         None
1759                     }
1760                 },
1761                 _ => None,
1762             };
1763
1764             if let Some(good_method) = found_good_method {
1765                 let span = expr.span.to(op.span);
1766                 let result_expr = match &op.kind {
1767                     ExprKind::AddrOf(_, _, borrowed) => borrowed,
1768                     _ => op,
1769                 };
1770                 span_lint_and_then(
1771                     cx,
1772                     REDUNDANT_PATTERN_MATCHING,
1773                     expr.span,
1774                     &format!("redundant pattern matching, consider using `{}`", good_method),
1775                     |diag| {
1776                         diag.span_suggestion(
1777                             span,
1778                             "try this",
1779                             format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
1780                             Applicability::MaybeIncorrect, // snippet
1781                         );
1782                     },
1783                 );
1784             }
1785         }
1786     }
1787
1788     fn find_good_method_for_match<'a>(
1789         arms: &[Arm<'_>],
1790         path_left: &QPath<'_>,
1791         path_right: &QPath<'_>,
1792         expected_left: &[&str],
1793         expected_right: &[&str],
1794         should_be_left: &'a str,
1795         should_be_right: &'a str,
1796     ) -> Option<&'a str> {
1797         let body_node_pair = if match_qpath(path_left, expected_left) && match_qpath(path_right, expected_right) {
1798             (&(*arms[0].body).kind, &(*arms[1].body).kind)
1799         } else if match_qpath(path_right, expected_left) && match_qpath(path_left, expected_right) {
1800             (&(*arms[1].body).kind, &(*arms[0].body).kind)
1801         } else {
1802             return None;
1803         };
1804
1805         match body_node_pair {
1806             (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
1807                 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
1808                 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
1809                 _ => None,
1810             },
1811             _ => None,
1812         }
1813     }
1814 }
1815
1816 #[test]
1817 fn test_overlapping() {
1818     use rustc_span::source_map::DUMMY_SP;
1819
1820     let sp = |s, e| SpannedRange {
1821         span: DUMMY_SP,
1822         node: (s, e),
1823     };
1824
1825     assert_eq!(None, overlapping::<u8>(&[]));
1826     assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
1827     assert_eq!(
1828         None,
1829         overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
1830     );
1831     assert_eq!(
1832         None,
1833         overlapping(&[
1834             sp(1, Bound::Included(4)),
1835             sp(5, Bound::Included(6)),
1836             sp(10, Bound::Included(11))
1837         ],)
1838     );
1839     assert_eq!(
1840         Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
1841         overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
1842     );
1843     assert_eq!(
1844         Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
1845         overlapping(&[
1846             sp(1, Bound::Included(4)),
1847             sp(5, Bound::Included(6)),
1848             sp(6, Bound::Included(11))
1849         ],)
1850     );
1851 }
1852
1853 /// Implementation of `MATCH_SAME_ARMS`.
1854 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
1855     fn same_bindings<'tcx>(lhs: &FxHashMap<Symbol, Ty<'tcx>>, rhs: &FxHashMap<Symbol, Ty<'tcx>>) -> bool {
1856         lhs.len() == rhs.len()
1857             && lhs
1858                 .iter()
1859                 .all(|(name, l_ty)| rhs.get(name).map_or(false, |r_ty| TyS::same_type(l_ty, r_ty)))
1860     }
1861
1862     if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
1863         let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
1864             let mut h = SpanlessHash::new(cx);
1865             h.hash_expr(&arm.body);
1866             h.finish()
1867         };
1868
1869         let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
1870             let min_index = usize::min(lindex, rindex);
1871             let max_index = usize::max(lindex, rindex);
1872
1873             // Arms with a guard are ignored, those can’t always be merged together
1874             // This is also the case for arms in-between each there is an arm with a guard
1875             (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
1876                 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
1877                 // all patterns should have the same bindings
1878                 same_bindings(&bindings(cx, &lhs.pat), &bindings(cx, &rhs.pat))
1879         };
1880
1881         let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
1882         for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
1883             span_lint_and_then(
1884                 cx,
1885                 MATCH_SAME_ARMS,
1886                 j.body.span,
1887                 "this `match` has identical arm bodies",
1888                 |diag| {
1889                     diag.span_note(i.body.span, "same as this");
1890
1891                     // Note: this does not use `span_suggestion` on purpose:
1892                     // there is no clean way
1893                     // to remove the other arm. Building a span and suggest to replace it to ""
1894                     // makes an even more confusing error message. Also in order not to make up a
1895                     // span for the whole pattern, the suggestion is only shown when there is only
1896                     // one pattern. The user should know about `|` if they are already using it…
1897
1898                     let lhs = snippet(cx, i.pat.span, "<pat1>");
1899                     let rhs = snippet(cx, j.pat.span, "<pat2>");
1900
1901                     if let PatKind::Wild = j.pat.kind {
1902                         // if the last arm is _, then i could be integrated into _
1903                         // note that i.pat cannot be _, because that would mean that we're
1904                         // hiding all the subsequent arms, and rust won't compile
1905                         diag.span_note(
1906                             i.body.span,
1907                             &format!(
1908                                 "`{}` has the same arm body as the `_` wildcard, consider removing it",
1909                                 lhs
1910                             ),
1911                         );
1912                     } else {
1913                         diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
1914                     }
1915                 },
1916             );
1917         }
1918     }
1919 }
1920
1921 /// Returns the list of bindings in a pattern.
1922 fn bindings<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>) -> FxHashMap<Symbol, Ty<'tcx>> {
1923     fn bindings_impl<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>, map: &mut FxHashMap<Symbol, Ty<'tcx>>) {
1924         match pat.kind {
1925             PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
1926             PatKind::TupleStruct(_, pats, _) => {
1927                 for pat in pats {
1928                     bindings_impl(cx, pat, map);
1929                 }
1930             },
1931             PatKind::Binding(.., ident, ref as_pat) => {
1932                 if let Entry::Vacant(v) = map.entry(ident.name) {
1933                     v.insert(cx.typeck_results().pat_ty(pat));
1934                 }
1935                 if let Some(ref as_pat) = *as_pat {
1936                     bindings_impl(cx, as_pat, map);
1937                 }
1938             },
1939             PatKind::Or(fields) | PatKind::Tuple(fields, _) => {
1940                 for pat in fields {
1941                     bindings_impl(cx, pat, map);
1942                 }
1943             },
1944             PatKind::Struct(_, fields, _) => {
1945                 for pat in fields {
1946                     bindings_impl(cx, &pat.pat, map);
1947                 }
1948             },
1949             PatKind::Slice(lhs, ref mid, rhs) => {
1950                 for pat in lhs {
1951                     bindings_impl(cx, pat, map);
1952                 }
1953                 if let Some(ref mid) = *mid {
1954                     bindings_impl(cx, mid, map);
1955                 }
1956                 for pat in rhs {
1957                     bindings_impl(cx, pat, map);
1958                 }
1959             },
1960             PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
1961         }
1962     }
1963
1964     let mut result = FxHashMap::default();
1965     bindings_impl(cx, pat, &mut result);
1966     result
1967 }