]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/matches.rs
Rollup merge of #83522 - pickfire:patch-6, r=JohnTitor
[rust.git] / src / tools / clippy / 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_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_errors::Applicability;
18 use rustc_hir::def::{CtorKind, DefKind, Res};
19 use rustc_hir::{
20     self as hir, Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, HirId, Local, MatchSource,
21     Mutability, Node, Pat, PatKind, PathSegment, QPath, RangeEnd, TyKind,
22 };
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(ref ex, ref 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(ref ex, ref 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(ref expr) = local.init;
618             if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind;
619             if arms.len() == 1 && arms[0].guard.is_none();
620             if let PatKind::TupleStruct(
621                 QPath::Resolved(None, ref variant_name), ref 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(_, ref 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 (msg, sugg) = if_chain! {
737         let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
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, ref 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(ref 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, ref 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                         inner.iter().for_each(|pat| {
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(ref 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 #[allow(clippy::too_many_lines)]
988 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
989     let ty = cx.typeck_results().expr_ty(ex).peel_refs();
990     let adt_def = match ty.kind() {
991         ty::Adt(adt_def, _)
992             if adt_def.is_enum()
993                 && !(is_type_diagnostic_item(cx, ty, sym::option_type)
994                     || is_type_diagnostic_item(cx, ty, sym::result_type)) =>
995         {
996             adt_def
997         },
998         _ => return,
999     };
1000
1001     // First pass - check for violation, but don't do much book-keeping because this is hopefully
1002     // the uncommon case, and the book-keeping is slightly expensive.
1003     let mut wildcard_span = None;
1004     let mut wildcard_ident = None;
1005     let mut has_non_wild = false;
1006     for arm in arms {
1007         match peel_hir_pat_refs(arm.pat).0.kind {
1008             PatKind::Wild => wildcard_span = Some(arm.pat.span),
1009             PatKind::Binding(_, _, ident, None) => {
1010                 wildcard_span = Some(arm.pat.span);
1011                 wildcard_ident = Some(ident);
1012             },
1013             _ => has_non_wild = true,
1014         }
1015     }
1016     let wildcard_span = match wildcard_span {
1017         Some(x) if has_non_wild => x,
1018         _ => return,
1019     };
1020
1021     // Accumulate the variants which should be put in place of the wildcard because they're not
1022     // already covered.
1023     let mut missing_variants: Vec<_> = adt_def.variants.iter().collect();
1024
1025     let mut path_prefix = CommonPrefixSearcher::None;
1026     for arm in arms {
1027         // Guards mean that this case probably isn't exhaustively covered. Technically
1028         // this is incorrect, as we should really check whether each variant is exhaustively
1029         // covered by the set of guards that cover it, but that's really hard to do.
1030         recurse_or_patterns(arm.pat, |pat| {
1031             let path = match &peel_hir_pat_refs(pat).0.kind {
1032                 PatKind::Path(path) => {
1033                     #[allow(clippy::match_same_arms)]
1034                     let id = match cx.qpath_res(path, pat.hir_id) {
1035                         Res::Def(DefKind::Const | DefKind::ConstParam | DefKind::AnonConst, _) => return,
1036                         Res::Def(_, id) => id,
1037                         _ => return,
1038                     };
1039                     if arm.guard.is_none() {
1040                         missing_variants.retain(|e| e.ctor_def_id != Some(id));
1041                     }
1042                     path
1043                 },
1044                 PatKind::TupleStruct(path, patterns, ..) => {
1045                     if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
1046                         let id = cx.qpath_res(path, pat.hir_id).def_id();
1047                         missing_variants.retain(|e| e.ctor_def_id != Some(id));
1048                     }
1049                     path
1050                 },
1051                 PatKind::Struct(path, patterns, ..) => {
1052                     if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
1053                         let id = cx.qpath_res(path, pat.hir_id).def_id();
1054                         missing_variants.retain(|e| e.def_id != id);
1055                     }
1056                     path
1057                 },
1058                 _ => return,
1059             };
1060             match path {
1061                 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
1062                 QPath::TypeRelative(
1063                     hir::Ty {
1064                         kind: TyKind::Path(QPath::Resolved(_, path)),
1065                         ..
1066                     },
1067                     _,
1068                 ) => path_prefix.with_prefix(path.segments),
1069                 _ => (),
1070             }
1071         });
1072     }
1073
1074     let format_suggestion = |variant: &VariantDef| {
1075         format!(
1076             "{}{}{}{}",
1077             if let Some(ident) = wildcard_ident {
1078                 format!("{} @ ", ident.name)
1079             } else {
1080                 String::new()
1081             },
1082             if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
1083                 let mut s = String::new();
1084                 for seg in path_prefix {
1085                     s.push_str(&seg.ident.as_str());
1086                     s.push_str("::");
1087                 }
1088                 s
1089             } else {
1090                 let mut s = cx.tcx.def_path_str(adt_def.did);
1091                 s.push_str("::");
1092                 s
1093             },
1094             variant.ident.name,
1095             match variant.ctor_kind {
1096                 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
1097                 CtorKind::Fn => "(..)",
1098                 CtorKind::Const => "",
1099                 CtorKind::Fictive => "{ .. }",
1100             }
1101         )
1102     };
1103
1104     match missing_variants.as_slice() {
1105         [] => (),
1106         [x] if !adt_def.is_variant_list_non_exhaustive() => span_lint_and_sugg(
1107             cx,
1108             MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1109             wildcard_span,
1110             "wildcard matches only a single variant and will also match any future added variants",
1111             "try this",
1112             format_suggestion(x),
1113             Applicability::MaybeIncorrect,
1114         ),
1115         variants => {
1116             let mut suggestions: Vec<_> = variants.iter().cloned().map(format_suggestion).collect();
1117             let message = if adt_def.is_variant_list_non_exhaustive() {
1118                 suggestions.push("_".into());
1119                 "wildcard matches known variants and will also match future added variants"
1120             } else {
1121                 "wildcard match will also match any future added variants"
1122             };
1123
1124             span_lint_and_sugg(
1125                 cx,
1126                 WILDCARD_ENUM_MATCH_ARM,
1127                 wildcard_span,
1128                 message,
1129                 "try this",
1130                 suggestions.join(" | "),
1131                 Applicability::MaybeIncorrect,
1132             )
1133         },
1134     };
1135 }
1136
1137 // If the block contains only a `panic!` macro (as expression or statement)
1138 fn is_panic_block(block: &Block<'_>) -> bool {
1139     match (&block.expr, block.stmts.len(), block.stmts.first()) {
1140         (&Some(ref exp), 0, _) => {
1141             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
1142         },
1143         (&None, 1, Some(stmt)) => {
1144             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
1145         },
1146         _ => false,
1147     }
1148 }
1149
1150 fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1151     if has_only_ref_pats(arms) {
1152         let mut suggs = Vec::with_capacity(arms.len() + 1);
1153         let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
1154             let span = ex.span.source_callsite();
1155             suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1156             (
1157                 "you don't need to add `&` to both the expression and the patterns",
1158                 "try",
1159             )
1160         } else {
1161             let span = ex.span.source_callsite();
1162             suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1163             (
1164                 "you don't need to add `&` to all patterns",
1165                 "instead of prefixing all patterns with `&`, you can dereference the expression",
1166             )
1167         };
1168
1169         suggs.extend(arms.iter().filter_map(|a| {
1170             if let PatKind::Ref(ref refp, _) = a.pat.kind {
1171                 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
1172             } else {
1173                 None
1174             }
1175         }));
1176
1177         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1178             if !expr.span.from_expansion() {
1179                 multispan_sugg(diag, msg, suggs);
1180             }
1181         });
1182     }
1183 }
1184
1185 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1186     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1187         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
1188             is_ref_some_arm(&arms[1])
1189         } else if is_none_arm(&arms[1]) {
1190             is_ref_some_arm(&arms[0])
1191         } else {
1192             None
1193         };
1194         if let Some(rb) = arm_ref {
1195             let suggestion = if rb == BindingAnnotation::Ref {
1196                 "as_ref"
1197             } else {
1198                 "as_mut"
1199             };
1200
1201             let output_ty = cx.typeck_results().expr_ty(expr);
1202             let input_ty = cx.typeck_results().expr_ty(ex);
1203
1204             let cast = if_chain! {
1205                 if let ty::Adt(_, substs) = input_ty.kind();
1206                 let input_ty = substs.type_at(0);
1207                 if let ty::Adt(_, substs) = output_ty.kind();
1208                 let output_ty = substs.type_at(0);
1209                 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1210                 if input_ty != output_ty;
1211                 then {
1212                     ".map(|x| x as _)"
1213                 } else {
1214                     ""
1215                 }
1216             };
1217
1218             let mut applicability = Applicability::MachineApplicable;
1219             span_lint_and_sugg(
1220                 cx,
1221                 MATCH_AS_REF,
1222                 expr.span,
1223                 &format!("use `{}()` instead", suggestion),
1224                 "try this",
1225                 format!(
1226                     "{}.{}(){}",
1227                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1228                     suggestion,
1229                     cast,
1230                 ),
1231                 applicability,
1232             )
1233         }
1234     }
1235 }
1236
1237 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1238     for arm in arms {
1239         if let PatKind::Or(ref fields) = arm.pat.kind {
1240             // look for multiple fields in this arm that contains at least one Wild pattern
1241             if fields.len() > 1 && fields.iter().any(is_wild) {
1242                 span_lint_and_help(
1243                     cx,
1244                     WILDCARD_IN_OR_PATTERNS,
1245                     arm.pat.span,
1246                     "wildcard pattern covers any other pattern as it will match anyway",
1247                     None,
1248                     "consider handling `_` separately",
1249                 );
1250             }
1251         }
1252     }
1253 }
1254
1255 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1256 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1257     if let ExprKind::Match(ex, arms, ref match_source) = &expr.kind {
1258         match match_source {
1259             MatchSource::Normal => find_matches_sugg(cx, ex, arms, expr, false),
1260             MatchSource::IfLetDesugar { .. } => find_matches_sugg(cx, ex, arms, expr, true),
1261             _ => false,
1262         }
1263     } else {
1264         false
1265     }
1266 }
1267
1268 /// Lint a `match` or desugared `if let` for replacement by `matches!`
1269 fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>, desugared: bool) -> bool {
1270     if_chain! {
1271         if arms.len() >= 2;
1272         if cx.typeck_results().expr_ty(expr).is_bool();
1273         if let Some((b1_arm, b0_arms)) = arms.split_last();
1274         if let Some(b0) = find_bool_lit(&b0_arms[0].body.kind, desugared);
1275         if let Some(b1) = find_bool_lit(&b1_arm.body.kind, desugared);
1276         if is_wild(&b1_arm.pat);
1277         if b0 != b1;
1278         let if_guard = &b0_arms[0].guard;
1279         if if_guard.is_none() || b0_arms.len() == 1;
1280         if cx.tcx.hir().attrs(b0_arms[0].hir_id).is_empty();
1281         if b0_arms[1..].iter()
1282             .all(|arm| {
1283                 find_bool_lit(&arm.body.kind, desugared).map_or(false, |b| b == b0) &&
1284                 arm.guard.is_none() && cx.tcx.hir().attrs(arm.hir_id).is_empty()
1285             });
1286         then {
1287             // The suggestion may be incorrect, because some arms can have `cfg` attributes
1288             // evaluated into `false` and so such arms will be stripped before.
1289             let mut applicability = Applicability::MaybeIncorrect;
1290             let pat = {
1291                 use itertools::Itertools as _;
1292                 b0_arms.iter()
1293                     .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability))
1294                     .join(" | ")
1295             };
1296             let pat_and_guard = if let Some(Guard::If(g)) = if_guard {
1297                 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1298             } else {
1299                 pat
1300             };
1301
1302             // strip potential borrows (#6503), but only if the type is a reference
1303             let mut ex_new = ex;
1304             if let ExprKind::AddrOf(BorrowKind::Ref, .., ex_inner) = ex.kind {
1305                 if let ty::Ref(..) = cx.typeck_results().expr_ty(&ex_inner).kind() {
1306                     ex_new = ex_inner;
1307                 }
1308             };
1309             span_lint_and_sugg(
1310                 cx,
1311                 MATCH_LIKE_MATCHES_MACRO,
1312                 expr.span,
1313                 &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }),
1314                 "try this",
1315                 format!(
1316                     "{}matches!({}, {})",
1317                     if b0 { "" } else { "!" },
1318                     snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
1319                     pat_and_guard,
1320                 ),
1321                 applicability,
1322             );
1323             true
1324         } else {
1325             false
1326         }
1327     }
1328 }
1329
1330 /// Extract a `bool` or `{ bool }`
1331 fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option<bool> {
1332     match ex {
1333         ExprKind::Lit(Spanned {
1334             node: LitKind::Bool(b), ..
1335         }) => Some(*b),
1336         ExprKind::Block(
1337             rustc_hir::Block {
1338                 stmts: &[],
1339                 expr: Some(exp),
1340                 ..
1341             },
1342             _,
1343         ) if desugared => {
1344             if let ExprKind::Lit(Spanned {
1345                 node: LitKind::Bool(b), ..
1346             }) = exp.kind
1347             {
1348                 Some(b)
1349             } else {
1350                 None
1351             }
1352         },
1353         _ => None,
1354     }
1355 }
1356
1357 #[allow(clippy::too_many_lines)]
1358 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1359     if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1360         return;
1361     }
1362
1363     // HACK:
1364     // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1365     // to prevent false positives as there is currently no better way to detect if code was excluded by
1366     // a macro. See PR #6435
1367     if_chain! {
1368         if let Some(match_snippet) = snippet_opt(cx, expr.span);
1369         if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1370         if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1371         let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1372         if rest_snippet.contains("=>");
1373         then {
1374             // The code it self contains another thick arrow "=>"
1375             // -> Either another arm or a comment
1376             return;
1377         }
1378     }
1379
1380     let matched_vars = ex.span;
1381     let bind_names = arms[0].pat.span;
1382     let match_body = remove_blocks(&arms[0].body);
1383     let mut snippet_body = if match_body.span.from_expansion() {
1384         Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1385     } else {
1386         snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1387     };
1388
1389     // Do we need to add ';' to suggestion ?
1390     match match_body.kind {
1391         ExprKind::Block(block, _) => {
1392             // macro + expr_ty(body) == ()
1393             if block.span.from_expansion() && cx.typeck_results().expr_ty(&match_body).is_unit() {
1394                 snippet_body.push(';');
1395             }
1396         },
1397         _ => {
1398             // expr_ty(body) == ()
1399             if cx.typeck_results().expr_ty(&match_body).is_unit() {
1400                 snippet_body.push(';');
1401             }
1402         },
1403     }
1404
1405     let mut applicability = Applicability::MaybeIncorrect;
1406     match arms[0].pat.kind {
1407         PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1408             // If this match is in a local (`let`) stmt
1409             let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1410                 (
1411                     parent_let_node.span,
1412                     format!(
1413                         "let {} = {};\n{}let {} = {};",
1414                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1415                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1416                         " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1417                         snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1418                         snippet_body
1419                     ),
1420                 )
1421             } else {
1422                 // If we are in closure, we need curly braces around suggestion
1423                 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1424                 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1425                 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1426                     if let ExprKind::Closure(..) = parent_expr.kind {
1427                         cbrace_end = format!("\n{}}}", indent);
1428                         // Fix body indent due to the closure
1429                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1430                         cbrace_start = format!("{{\n{}", indent);
1431                     }
1432                 }
1433                 // If the parent is already an arm, and the body is another match statement,
1434                 // we need curly braces around suggestion
1435                 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1436                 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1437                     if let ExprKind::Match(..) = arm.body.kind {
1438                         cbrace_end = format!("\n{}}}", indent);
1439                         // Fix body indent due to the match
1440                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1441                         cbrace_start = format!("{{\n{}", indent);
1442                     }
1443                 }
1444                 (
1445                     expr.span,
1446                     format!(
1447                         "{}let {} = {};\n{}{}{}",
1448                         cbrace_start,
1449                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1450                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1451                         indent,
1452                         snippet_body,
1453                         cbrace_end
1454                     ),
1455                 )
1456             };
1457             span_lint_and_sugg(
1458                 cx,
1459                 MATCH_SINGLE_BINDING,
1460                 target_span,
1461                 "this match could be written as a `let` statement",
1462                 "consider using `let` statement",
1463                 sugg,
1464                 applicability,
1465             );
1466         },
1467         PatKind::Wild => {
1468             span_lint_and_sugg(
1469                 cx,
1470                 MATCH_SINGLE_BINDING,
1471                 expr.span,
1472                 "this match could be replaced by its body itself",
1473                 "consider using the match body instead",
1474                 snippet_body,
1475                 Applicability::MachineApplicable,
1476             );
1477         },
1478         _ => (),
1479     }
1480 }
1481
1482 /// Returns true if the `ex` match expression is in a local (`let`) statement
1483 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1484     if_chain! {
1485         let map = &cx.tcx.hir();
1486         if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1487         if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1488         then {
1489             return Some(parent_let_expr);
1490         }
1491     }
1492     None
1493 }
1494
1495 /// Gets all arms that are unbounded `PatRange`s.
1496 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> {
1497     arms.iter()
1498         .flat_map(|arm| {
1499             if let Arm {
1500                 ref pat, guard: None, ..
1501             } = *arm
1502             {
1503                 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1504                     let lhs = match lhs {
1505                         Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1506                         None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1507                     };
1508                     let rhs = match rhs {
1509                         Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1510                         None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1511                     };
1512                     let rhs = match range_end {
1513                         RangeEnd::Included => Bound::Included(rhs),
1514                         RangeEnd::Excluded => Bound::Excluded(rhs),
1515                     };
1516                     return Some(SpannedRange {
1517                         span: pat.span,
1518                         node: (lhs, rhs),
1519                     });
1520                 }
1521
1522                 if let PatKind::Lit(ref value) = pat.kind {
1523                     let value = constant(cx, cx.typeck_results(), value)?.0;
1524                     return Some(SpannedRange {
1525                         span: pat.span,
1526                         node: (value.clone(), Bound::Included(value)),
1527                     });
1528                 }
1529             }
1530             None
1531         })
1532         .collect()
1533 }
1534
1535 #[derive(Debug, Eq, PartialEq)]
1536 pub struct SpannedRange<T> {
1537     pub span: Span,
1538     pub node: (T, Bound<T>),
1539 }
1540
1541 type TypedRanges = Vec<SpannedRange<u128>>;
1542
1543 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1544 /// and other types than
1545 /// `Uint` and `Int` probably don't make sense.
1546 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1547     ranges
1548         .iter()
1549         .filter_map(|range| match range.node {
1550             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1551                 span: range.span,
1552                 node: (start, Bound::Included(end)),
1553             }),
1554             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1555                 span: range.span,
1556                 node: (start, Bound::Excluded(end)),
1557             }),
1558             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1559                 span: range.span,
1560                 node: (start, Bound::Unbounded),
1561             }),
1562             _ => None,
1563         })
1564         .collect()
1565 }
1566
1567 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1568     match expr.kind {
1569         ExprKind::Tup(ref v) if v.is_empty() => true,
1570         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1571         _ => false,
1572     }
1573 }
1574
1575 // Checks if arm has the form `None => None`
1576 fn is_none_arm(arm: &Arm<'_>) -> bool {
1577     matches!(arm.pat.kind, PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE))
1578 }
1579
1580 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1581 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
1582     if_chain! {
1583         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
1584         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
1585         if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1586         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1587         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
1588         if let ExprKind::Path(ref some_path) = e.kind;
1589         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
1590         if let ExprKind::Path(QPath::Resolved(_, ref path2)) = args[0].kind;
1591         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1592         then {
1593             return Some(rb)
1594         }
1595     }
1596     None
1597 }
1598
1599 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1600     let mapped = arms
1601         .iter()
1602         .map(|a| {
1603             match a.pat.kind {
1604                 PatKind::Ref(..) => Some(true), // &-patterns
1605                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
1606                 _ => None,                      // any other pattern is not fine
1607             }
1608         })
1609         .collect::<Option<Vec<bool>>>();
1610     // look for Some(v) where there's at least one true element
1611     mapped.map_or(false, |v| v.iter().any(|el| *el))
1612 }
1613
1614 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1615 where
1616     T: Copy + Ord,
1617 {
1618     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1619     enum Kind<'a, T> {
1620         Start(T, &'a SpannedRange<T>),
1621         End(Bound<T>, &'a SpannedRange<T>),
1622     }
1623
1624     impl<'a, T: Copy> Kind<'a, T> {
1625         fn range(&self) -> &'a SpannedRange<T> {
1626             match *self {
1627                 Kind::Start(_, r) | Kind::End(_, r) => r,
1628             }
1629         }
1630
1631         fn value(self) -> Bound<T> {
1632             match self {
1633                 Kind::Start(t, _) => Bound::Included(t),
1634                 Kind::End(t, _) => t,
1635             }
1636         }
1637     }
1638
1639     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1640         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1641             Some(self.cmp(other))
1642         }
1643     }
1644
1645     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1646         fn cmp(&self, other: &Self) -> Ordering {
1647             match (self.value(), other.value()) {
1648                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1649                 // Range patterns cannot be unbounded (yet)
1650                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1651                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1652                     Ordering::Equal => Ordering::Greater,
1653                     other => other,
1654                 },
1655                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1656                     Ordering::Equal => Ordering::Less,
1657                     other => other,
1658                 },
1659             }
1660         }
1661     }
1662
1663     let mut values = Vec::with_capacity(2 * ranges.len());
1664
1665     for r in ranges {
1666         values.push(Kind::Start(r.node.0, r));
1667         values.push(Kind::End(r.node.1, r));
1668     }
1669
1670     values.sort();
1671
1672     for (a, b) in iter::zip(&values, &values[1..]) {
1673         match (a, b) {
1674             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1675                 if ra.node != rb.node {
1676                     return Some((ra, rb));
1677                 }
1678             },
1679             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1680             _ => {
1681                 // skip if the range `a` is completely included into the range `b`
1682                 if let Ordering::Equal | Ordering::Less = a.cmp(&b) {
1683                     let kind_a = Kind::End(a.range().node.1, a.range());
1684                     let kind_b = Kind::End(b.range().node.1, b.range());
1685                     if let Ordering::Equal | Ordering::Greater = kind_a.cmp(&kind_b) {
1686                         return None;
1687                     }
1688                 }
1689                 return Some((a.range(), b.range()));
1690             },
1691         }
1692     }
1693
1694     None
1695 }
1696
1697 mod redundant_pattern_match {
1698     use super::REDUNDANT_PATTERN_MATCHING;
1699     use clippy_utils::diagnostics::span_lint_and_then;
1700     use clippy_utils::source::snippet;
1701     use clippy_utils::{is_trait_method, match_qpath, paths};
1702     use if_chain::if_chain;
1703     use rustc_ast::ast::LitKind;
1704     use rustc_errors::Applicability;
1705     use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind, QPath};
1706     use rustc_lint::LateContext;
1707     use rustc_span::sym;
1708
1709     pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1710         if let ExprKind::Match(op, arms, ref match_source) = &expr.kind {
1711             match match_source {
1712                 MatchSource::Normal => find_sugg_for_match(cx, expr, op, arms),
1713                 MatchSource::IfLetDesugar { .. } => find_sugg_for_if_let(cx, expr, op, arms, "if"),
1714                 MatchSource::WhileLetDesugar => find_sugg_for_if_let(cx, expr, op, arms, "while"),
1715                 _ => {},
1716             }
1717         }
1718     }
1719
1720     fn find_sugg_for_if_let<'tcx>(
1721         cx: &LateContext<'tcx>,
1722         expr: &'tcx Expr<'_>,
1723         op: &Expr<'_>,
1724         arms: &[Arm<'_>],
1725         keyword: &'static str,
1726     ) {
1727         let good_method = match arms[0].pat.kind {
1728             PatKind::TupleStruct(ref path, ref patterns, _) if patterns.len() == 1 => {
1729                 if let PatKind::Wild = patterns[0].kind {
1730                     if match_qpath(path, &paths::RESULT_OK) {
1731                         "is_ok()"
1732                     } else if match_qpath(path, &paths::RESULT_ERR) {
1733                         "is_err()"
1734                     } else if match_qpath(path, &paths::OPTION_SOME) {
1735                         "is_some()"
1736                     } else if match_qpath(path, &paths::POLL_READY) {
1737                         "is_ready()"
1738                     } else if match_qpath(path, &paths::IPADDR_V4) {
1739                         "is_ipv4()"
1740                     } else if match_qpath(path, &paths::IPADDR_V6) {
1741                         "is_ipv6()"
1742                     } else {
1743                         return;
1744                     }
1745                 } else {
1746                     return;
1747                 }
1748             },
1749             PatKind::Path(ref path) => {
1750                 if match_qpath(path, &paths::OPTION_NONE) {
1751                     "is_none()"
1752                 } else if match_qpath(path, &paths::POLL_PENDING) {
1753                     "is_pending()"
1754                 } else {
1755                     return;
1756                 }
1757             },
1758             _ => return,
1759         };
1760
1761         // check that `while_let_on_iterator` lint does not trigger
1762         if_chain! {
1763             if keyword == "while";
1764             if let ExprKind::MethodCall(method_path, _, _, _) = op.kind;
1765             if method_path.ident.name == sym::next;
1766             if is_trait_method(cx, op, sym::Iterator);
1767             then {
1768                 return;
1769             }
1770         }
1771
1772         let result_expr = match &op.kind {
1773             ExprKind::AddrOf(_, _, borrowed) => borrowed,
1774             _ => op,
1775         };
1776         span_lint_and_then(
1777             cx,
1778             REDUNDANT_PATTERN_MATCHING,
1779             arms[0].pat.span,
1780             &format!("redundant pattern matching, consider using `{}`", good_method),
1781             |diag| {
1782                 // while let ... = ... { ... }
1783                 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1784                 let expr_span = expr.span;
1785
1786                 // while let ... = ... { ... }
1787                 //                 ^^^
1788                 let op_span = result_expr.span.source_callsite();
1789
1790                 // while let ... = ... { ... }
1791                 // ^^^^^^^^^^^^^^^^^^^
1792                 let span = expr_span.until(op_span.shrink_to_hi());
1793                 diag.span_suggestion(
1794                     span,
1795                     "try this",
1796                     format!("{} {}.{}", keyword, snippet(cx, op_span, "_"), good_method),
1797                     Applicability::MachineApplicable, // snippet
1798                 );
1799             },
1800         );
1801     }
1802
1803     fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
1804         if arms.len() == 2 {
1805             let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
1806
1807             let found_good_method = match node_pair {
1808                 (
1809                     PatKind::TupleStruct(ref path_left, ref patterns_left, _),
1810                     PatKind::TupleStruct(ref path_right, ref patterns_right, _),
1811                 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
1812                     if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
1813                         find_good_method_for_match(
1814                             arms,
1815                             path_left,
1816                             path_right,
1817                             &paths::RESULT_OK,
1818                             &paths::RESULT_ERR,
1819                             "is_ok()",
1820                             "is_err()",
1821                         )
1822                         .or_else(|| {
1823                             find_good_method_for_match(
1824                                 arms,
1825                                 path_left,
1826                                 path_right,
1827                                 &paths::IPADDR_V4,
1828                                 &paths::IPADDR_V6,
1829                                 "is_ipv4()",
1830                                 "is_ipv6()",
1831                             )
1832                         })
1833                     } else {
1834                         None
1835                     }
1836                 },
1837                 (PatKind::TupleStruct(ref path_left, ref patterns, _), PatKind::Path(ref path_right))
1838                 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, ref patterns, _))
1839                     if patterns.len() == 1 =>
1840                 {
1841                     if let PatKind::Wild = patterns[0].kind {
1842                         find_good_method_for_match(
1843                             arms,
1844                             path_left,
1845                             path_right,
1846                             &paths::OPTION_SOME,
1847                             &paths::OPTION_NONE,
1848                             "is_some()",
1849                             "is_none()",
1850                         )
1851                         .or_else(|| {
1852                             find_good_method_for_match(
1853                                 arms,
1854                                 path_left,
1855                                 path_right,
1856                                 &paths::POLL_READY,
1857                                 &paths::POLL_PENDING,
1858                                 "is_ready()",
1859                                 "is_pending()",
1860                             )
1861                         })
1862                     } else {
1863                         None
1864                     }
1865                 },
1866                 _ => None,
1867             };
1868
1869             if let Some(good_method) = found_good_method {
1870                 let span = expr.span.to(op.span);
1871                 let result_expr = match &op.kind {
1872                     ExprKind::AddrOf(_, _, borrowed) => borrowed,
1873                     _ => op,
1874                 };
1875                 span_lint_and_then(
1876                     cx,
1877                     REDUNDANT_PATTERN_MATCHING,
1878                     expr.span,
1879                     &format!("redundant pattern matching, consider using `{}`", good_method),
1880                     |diag| {
1881                         diag.span_suggestion(
1882                             span,
1883                             "try this",
1884                             format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
1885                             Applicability::MaybeIncorrect, // snippet
1886                         );
1887                     },
1888                 );
1889             }
1890         }
1891     }
1892
1893     fn find_good_method_for_match<'a>(
1894         arms: &[Arm<'_>],
1895         path_left: &QPath<'_>,
1896         path_right: &QPath<'_>,
1897         expected_left: &[&str],
1898         expected_right: &[&str],
1899         should_be_left: &'a str,
1900         should_be_right: &'a str,
1901     ) -> Option<&'a str> {
1902         let body_node_pair = if match_qpath(path_left, expected_left) && match_qpath(path_right, expected_right) {
1903             (&(*arms[0].body).kind, &(*arms[1].body).kind)
1904         } else if match_qpath(path_right, expected_left) && match_qpath(path_left, expected_right) {
1905             (&(*arms[1].body).kind, &(*arms[0].body).kind)
1906         } else {
1907             return None;
1908         };
1909
1910         match body_node_pair {
1911             (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
1912                 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
1913                 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
1914                 _ => None,
1915             },
1916             _ => None,
1917         }
1918     }
1919 }
1920
1921 #[test]
1922 fn test_overlapping() {
1923     use rustc_span::source_map::DUMMY_SP;
1924
1925     let sp = |s, e| SpannedRange {
1926         span: DUMMY_SP,
1927         node: (s, e),
1928     };
1929
1930     assert_eq!(None, overlapping::<u8>(&[]));
1931     assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
1932     assert_eq!(
1933         None,
1934         overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
1935     );
1936     assert_eq!(
1937         None,
1938         overlapping(&[
1939             sp(1, Bound::Included(4)),
1940             sp(5, Bound::Included(6)),
1941             sp(10, Bound::Included(11))
1942         ],)
1943     );
1944     assert_eq!(
1945         Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
1946         overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
1947     );
1948     assert_eq!(
1949         Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
1950         overlapping(&[
1951             sp(1, Bound::Included(4)),
1952             sp(5, Bound::Included(6)),
1953             sp(6, Bound::Included(11))
1954         ],)
1955     );
1956 }
1957
1958 /// Implementation of `MATCH_SAME_ARMS`.
1959 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
1960     if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
1961         let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
1962             let mut h = SpanlessHash::new(cx);
1963             h.hash_expr(&arm.body);
1964             h.finish()
1965         };
1966
1967         let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
1968             let min_index = usize::min(lindex, rindex);
1969             let max_index = usize::max(lindex, rindex);
1970
1971             let mut local_map: FxHashMap<HirId, HirId> = FxHashMap::default();
1972             let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
1973                 if_chain! {
1974                     if let Some(a_id) = path_to_local(a);
1975                     if let Some(b_id) = path_to_local(b);
1976                     let entry = match local_map.entry(a_id) {
1977                         Entry::Vacant(entry) => entry,
1978                         // check if using the same bindings as before
1979                         Entry::Occupied(entry) => return *entry.get() == b_id,
1980                     };
1981                     // the names technically don't have to match; this makes the lint more conservative
1982                     if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id);
1983                     if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b));
1984                     if pat_contains_local(lhs.pat, a_id);
1985                     if pat_contains_local(rhs.pat, b_id);
1986                     then {
1987                         entry.insert(b_id);
1988                         true
1989                     } else {
1990                         false
1991                     }
1992                 }
1993             };
1994             // Arms with a guard are ignored, those can’t always be merged together
1995             // This is also the case for arms in-between each there is an arm with a guard
1996             (min_index..=max_index).all(|index| arms[index].guard.is_none())
1997                 && SpanlessEq::new(cx)
1998                     .expr_fallback(eq_fallback)
1999                     .eq_expr(&lhs.body, &rhs.body)
2000                 // these checks could be removed to allow unused bindings
2001                 && bindings_eq(lhs.pat, local_map.keys().copied().collect())
2002                 && bindings_eq(rhs.pat, local_map.values().copied().collect())
2003         };
2004
2005         let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
2006         for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
2007             span_lint_and_then(
2008                 cx,
2009                 MATCH_SAME_ARMS,
2010                 j.body.span,
2011                 "this `match` has identical arm bodies",
2012                 |diag| {
2013                     diag.span_note(i.body.span, "same as this");
2014
2015                     // Note: this does not use `span_suggestion` on purpose:
2016                     // there is no clean way
2017                     // to remove the other arm. Building a span and suggest to replace it to ""
2018                     // makes an even more confusing error message. Also in order not to make up a
2019                     // span for the whole pattern, the suggestion is only shown when there is only
2020                     // one pattern. The user should know about `|` if they are already using it…
2021
2022                     let lhs = snippet(cx, i.pat.span, "<pat1>");
2023                     let rhs = snippet(cx, j.pat.span, "<pat2>");
2024
2025                     if let PatKind::Wild = j.pat.kind {
2026                         // if the last arm is _, then i could be integrated into _
2027                         // note that i.pat cannot be _, because that would mean that we're
2028                         // hiding all the subsequent arms, and rust won't compile
2029                         diag.span_note(
2030                             i.body.span,
2031                             &format!(
2032                                 "`{}` has the same arm body as the `_` wildcard, consider removing it",
2033                                 lhs
2034                             ),
2035                         );
2036                     } else {
2037                         diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
2038                     }
2039                 },
2040             );
2041         }
2042     }
2043 }
2044
2045 fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool {
2046     let mut result = false;
2047     pat.walk_short(|p| {
2048         result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id);
2049         !result
2050     });
2051     result
2052 }
2053
2054 /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa
2055 fn bindings_eq(pat: &Pat<'_>, mut ids: FxHashSet<HirId>) -> bool {
2056     let mut result = true;
2057     pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id));
2058     result && ids.is_empty()
2059 }