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