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