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