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