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