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