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