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