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