]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
08c23ca6d32bb00c58c68c44fdf260911c12362a
[rust.git] / clippy_lints / src / matches.rs
1 use clippy_utils::consts::{constant, constant_full_int, miri_to_const, FullInt};
2 use clippy_utils::diagnostics::{
3     multispan_sugg, span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then,
4 };
5 use clippy_utils::higher;
6 use clippy_utils::source::{expr_block, indent_of, snippet, snippet_block, snippet_opt, snippet_with_applicability};
7 use clippy_utils::sugg::Sugg;
8 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, match_type, peel_mid_ty_refs};
9 use clippy_utils::visitors::is_local_used;
10 use clippy_utils::{
11     get_parent_expr, is_expn_of, is_lang_ctor, is_lint_allowed, is_refutable, is_unit_expr, is_wild, meets_msrv, msrvs,
12     path_to_local, path_to_local_id, peel_hir_pat_refs, peel_n_hir_expr_refs, recurse_or_patterns, remove_blocks,
13     strip_pat_refs,
14 };
15 use clippy_utils::{paths, search_same, SpanlessEq, SpanlessHash};
16 use core::array;
17 use core::iter::{once, ExactSizeIterator};
18 use if_chain::if_chain;
19 use rustc_ast::ast::{Attribute, LitKind};
20 use rustc_errors::Applicability;
21 use rustc_hir::def::{CtorKind, DefKind, Res};
22 use rustc_hir::LangItem::{OptionNone, OptionSome};
23 use rustc_hir::{
24     self as hir, Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, HirId, Local, MatchSource,
25     Mutability, Node, Pat, PatKind, PathSegment, QPath, RangeEnd, TyKind,
26 };
27 use rustc_hir::{HirIdMap, HirIdSet};
28 use rustc_lint::{LateContext, LateLintPass, LintContext};
29 use rustc_middle::ty::{self, Ty, TyS, VariantDef};
30 use rustc_semver::RustcVersion;
31 use rustc_session::{declare_tool_lint, impl_lint_pass};
32 use rustc_span::source_map::{Span, Spanned};
33 use rustc_span::sym;
34 use std::cmp::Ordering;
35 use std::collections::hash_map::Entry;
36
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 = remove_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(remove_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(
834     cx: &LateContext<'_>,
835     ex: &Expr<'_>,
836     arms: &[Arm<'_>],
837     expr: &Expr<'_>,
838     ty: Ty<'_>,
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     let path = match arms[1].pat.kind {
853         PatKind::TupleStruct(ref path, inner, _) => {
854             // Contains any non wildcard patterns (e.g., `Err(err)`)?
855             if !inner.iter().all(is_wild) {
856                 return;
857             }
858             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
859         },
860         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
861         PatKind::Path(ref path) => {
862             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
863         },
864         _ => return,
865     };
866
867     for &(ty_path, pat_path) in candidates {
868         if path == *pat_path && match_type(cx, ty, ty_path) {
869             report_single_match_single_pattern(cx, ex, arms, expr, els);
870         }
871     }
872 }
873
874 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
875     // Type of expression is `bool`.
876     if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
877         span_lint_and_then(
878             cx,
879             MATCH_BOOL,
880             expr.span,
881             "you seem to be trying to match on a boolean expression",
882             move |diag| {
883                 if arms.len() == 2 {
884                     // no guards
885                     let exprs = if let PatKind::Lit(arm_bool) = arms[0].pat.kind {
886                         if let ExprKind::Lit(ref lit) = arm_bool.kind {
887                             match lit.node {
888                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
889                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
890                                 _ => None,
891                             }
892                         } else {
893                             None
894                         }
895                     } else {
896                         None
897                     };
898
899                     if let Some((true_expr, false_expr)) = exprs {
900                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
901                             (false, false) => Some(format!(
902                                 "if {} {} else {}",
903                                 snippet(cx, ex.span, "b"),
904                                 expr_block(cx, true_expr, None, "..", Some(expr.span)),
905                                 expr_block(cx, false_expr, None, "..", Some(expr.span))
906                             )),
907                             (false, true) => Some(format!(
908                                 "if {} {}",
909                                 snippet(cx, ex.span, "b"),
910                                 expr_block(cx, true_expr, None, "..", Some(expr.span))
911                             )),
912                             (true, false) => {
913                                 let test = Sugg::hir(cx, ex, "..");
914                                 Some(format!(
915                                     "if {} {}",
916                                     !test,
917                                     expr_block(cx, false_expr, None, "..", Some(expr.span))
918                                 ))
919                             },
920                             (true, true) => None,
921                         };
922
923                         if let Some(sugg) = sugg {
924                             diag.span_suggestion(
925                                 expr.span,
926                                 "consider using an `if`/`else` expression",
927                                 sugg,
928                                 Applicability::HasPlaceholders,
929                             );
930                         }
931                     }
932                 }
933             },
934         );
935     }
936 }
937
938 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
939     if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
940         let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
941         if !ranges.is_empty() {
942             if let Some((start, end)) = overlapping(&ranges) {
943                 span_lint_and_note(
944                     cx,
945                     MATCH_OVERLAPPING_ARM,
946                     start.span,
947                     "some ranges overlap",
948                     Some(end.span),
949                     "overlaps with this",
950                 );
951             }
952         }
953     }
954 }
955
956 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
957     let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
958     if is_type_diagnostic_item(cx, ex_ty, sym::Result) {
959         for arm in arms {
960             if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
961                 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
962                 if path_str == "Err" {
963                     let mut matching_wild = inner.iter().any(is_wild);
964                     let mut ident_bind_name = String::from("_");
965                     if !matching_wild {
966                         // Looking for unused bindings (i.e.: `_e`)
967                         for pat in inner.iter() {
968                             if let PatKind::Binding(_, id, ident, None) = pat.kind {
969                                 if ident.as_str().starts_with('_') && !is_local_used(cx, arm.body, id) {
970                                     ident_bind_name = (&ident.name.as_str()).to_string();
971                                     matching_wild = true;
972                                 }
973                             }
974                         }
975                     }
976                     if_chain! {
977                         if matching_wild;
978                         if is_panic_call(arm.body);
979                         then {
980                             // `Err(_)` or `Err(_e)` arm with `panic!` found
981                             span_lint_and_note(cx,
982                                 MATCH_WILD_ERR_ARM,
983                                 arm.pat.span,
984                                 &format!("`Err({})` matches all errors", &ident_bind_name),
985                                 None,
986                                 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
987                             );
988                         }
989                     }
990                 }
991             }
992         }
993     }
994 }
995
996 enum CommonPrefixSearcher<'a> {
997     None,
998     Path(&'a [PathSegment<'a>]),
999     Mixed,
1000 }
1001 impl CommonPrefixSearcher<'a> {
1002     fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
1003         match path {
1004             [path @ .., _] => self.with_prefix(path),
1005             [] => (),
1006         }
1007     }
1008
1009     fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
1010         match self {
1011             Self::None => *self = Self::Path(path),
1012             Self::Path(self_path)
1013                 if path
1014                     .iter()
1015                     .map(|p| p.ident.name)
1016                     .eq(self_path.iter().map(|p| p.ident.name)) => {},
1017             Self::Path(_) => *self = Self::Mixed,
1018             Self::Mixed => (),
1019         }
1020     }
1021 }
1022
1023 fn is_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
1024     let attrs = cx.tcx.get_attrs(variant_def.def_id);
1025     clippy_utils::attrs::is_doc_hidden(attrs) || clippy_utils::attrs::is_unstable(attrs)
1026 }
1027
1028 #[allow(clippy::too_many_lines)]
1029 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
1030     let ty = cx.typeck_results().expr_ty(ex).peel_refs();
1031     let adt_def = match ty.kind() {
1032         ty::Adt(adt_def, _)
1033             if adt_def.is_enum()
1034                 && !(is_type_diagnostic_item(cx, ty, sym::Option) || is_type_diagnostic_item(cx, ty, sym::Result)) =>
1035         {
1036             adt_def
1037         },
1038         _ => return,
1039     };
1040
1041     // First pass - check for violation, but don't do much book-keeping because this is hopefully
1042     // the uncommon case, and the book-keeping is slightly expensive.
1043     let mut wildcard_span = None;
1044     let mut wildcard_ident = None;
1045     let mut has_non_wild = false;
1046     for arm in arms {
1047         match peel_hir_pat_refs(arm.pat).0.kind {
1048             PatKind::Wild => wildcard_span = Some(arm.pat.span),
1049             PatKind::Binding(_, _, ident, None) => {
1050                 wildcard_span = Some(arm.pat.span);
1051                 wildcard_ident = Some(ident);
1052             },
1053             _ => has_non_wild = true,
1054         }
1055     }
1056     let wildcard_span = match wildcard_span {
1057         Some(x) if has_non_wild => x,
1058         _ => return,
1059     };
1060
1061     // Accumulate the variants which should be put in place of the wildcard because they're not
1062     // already covered.
1063     let has_hidden = adt_def.variants.iter().any(|x| is_hidden(cx, x));
1064     let mut missing_variants: Vec<_> = adt_def.variants.iter().filter(|x| !is_hidden(cx, x)).collect();
1065
1066     let mut path_prefix = CommonPrefixSearcher::None;
1067     for arm in arms {
1068         // Guards mean that this case probably isn't exhaustively covered. Technically
1069         // this is incorrect, as we should really check whether each variant is exhaustively
1070         // covered by the set of guards that cover it, but that's really hard to do.
1071         recurse_or_patterns(arm.pat, |pat| {
1072             let path = match &peel_hir_pat_refs(pat).0.kind {
1073                 PatKind::Path(path) => {
1074                     #[allow(clippy::match_same_arms)]
1075                     let id = match cx.qpath_res(path, pat.hir_id) {
1076                         Res::Def(
1077                             DefKind::Const | DefKind::ConstParam | DefKind::AnonConst | DefKind::InlineConst,
1078                             _,
1079                         ) => return,
1080                         Res::Def(_, id) => id,
1081                         _ => return,
1082                     };
1083                     if arm.guard.is_none() {
1084                         missing_variants.retain(|e| e.ctor_def_id != Some(id));
1085                     }
1086                     path
1087                 },
1088                 PatKind::TupleStruct(path, patterns, ..) => {
1089                     if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1090                         if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
1091                             missing_variants.retain(|e| e.ctor_def_id != Some(id));
1092                         }
1093                     }
1094                     path
1095                 },
1096                 PatKind::Struct(path, patterns, ..) => {
1097                     if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1098                         if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
1099                             missing_variants.retain(|e| e.def_id != id);
1100                         }
1101                     }
1102                     path
1103                 },
1104                 _ => return,
1105             };
1106             match path {
1107                 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
1108                 QPath::TypeRelative(
1109                     hir::Ty {
1110                         kind: TyKind::Path(QPath::Resolved(_, path)),
1111                         ..
1112                     },
1113                     _,
1114                 ) => path_prefix.with_prefix(path.segments),
1115                 _ => (),
1116             }
1117         });
1118     }
1119
1120     let format_suggestion = |variant: &VariantDef| {
1121         format!(
1122             "{}{}{}{}",
1123             if let Some(ident) = wildcard_ident {
1124                 format!("{} @ ", ident.name)
1125             } else {
1126                 String::new()
1127             },
1128             if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
1129                 let mut s = String::new();
1130                 for seg in path_prefix {
1131                     s.push_str(&seg.ident.as_str());
1132                     s.push_str("::");
1133                 }
1134                 s
1135             } else {
1136                 let mut s = cx.tcx.def_path_str(adt_def.did);
1137                 s.push_str("::");
1138                 s
1139             },
1140             variant.ident.name,
1141             match variant.ctor_kind {
1142                 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
1143                 CtorKind::Fn => "(..)",
1144                 CtorKind::Const => "",
1145                 CtorKind::Fictive => "{ .. }",
1146             }
1147         )
1148     };
1149
1150     match missing_variants.as_slice() {
1151         [] => (),
1152         [x] if !adt_def.is_variant_list_non_exhaustive() && !has_hidden => span_lint_and_sugg(
1153             cx,
1154             MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1155             wildcard_span,
1156             "wildcard matches only a single variant and will also match any future added variants",
1157             "try this",
1158             format_suggestion(x),
1159             Applicability::MaybeIncorrect,
1160         ),
1161         variants => {
1162             let mut suggestions: Vec<_> = variants.iter().copied().map(format_suggestion).collect();
1163             let message = if adt_def.is_variant_list_non_exhaustive() || has_hidden {
1164                 suggestions.push("_".into());
1165                 "wildcard matches known variants and will also match future added variants"
1166             } else {
1167                 "wildcard match will also match any future added variants"
1168             };
1169
1170             span_lint_and_sugg(
1171                 cx,
1172                 WILDCARD_ENUM_MATCH_ARM,
1173                 wildcard_span,
1174                 message,
1175                 "try this",
1176                 suggestions.join(" | "),
1177                 Applicability::MaybeIncorrect,
1178             );
1179         },
1180     };
1181 }
1182
1183 // If the block contains only a `panic!` macro (as expression or statement)
1184 fn is_panic_call(expr: &Expr<'_>) -> bool {
1185     // Unwrap any wrapping blocks
1186     let span = if let ExprKind::Block(block, _) = expr.kind {
1187         match (&block.expr, block.stmts.len(), block.stmts.first()) {
1188             (&Some(exp), 0, _) => exp.span,
1189             (&None, 1, Some(stmt)) => stmt.span,
1190             _ => return false,
1191         }
1192     } else {
1193         expr.span
1194     };
1195
1196     is_expn_of(span, "panic").is_some() && is_expn_of(span, "unreachable").is_none()
1197 }
1198
1199 fn check_match_ref_pats<'a, 'b, I>(cx: &LateContext<'_>, ex: &Expr<'_>, pats: I, expr: &Expr<'_>)
1200 where
1201     'b: 'a,
1202     I: Clone + Iterator<Item = &'a Pat<'b>>,
1203 {
1204     if !has_multiple_ref_pats(pats.clone()) {
1205         return;
1206     }
1207
1208     let (first_sugg, msg, title);
1209     let span = ex.span.source_callsite();
1210     if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = ex.kind {
1211         first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1212         msg = "try";
1213         title = "you don't need to add `&` to both the expression and the patterns";
1214     } else {
1215         first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1216         msg = "instead of prefixing all patterns with `&`, you can dereference the expression";
1217         title = "you don't need to add `&` to all patterns";
1218     }
1219
1220     let remaining_suggs = pats.filter_map(|pat| {
1221         if let PatKind::Ref(refp, _) = pat.kind {
1222             Some((pat.span, snippet(cx, refp.span, "..").to_string()))
1223         } else {
1224             None
1225         }
1226     });
1227
1228     span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1229         if !expr.span.from_expansion() {
1230             multispan_sugg(diag, msg, first_sugg.chain(remaining_suggs));
1231         }
1232     });
1233 }
1234
1235 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1236     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1237         let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
1238             is_ref_some_arm(cx, &arms[1])
1239         } else if is_none_arm(cx, &arms[1]) {
1240             is_ref_some_arm(cx, &arms[0])
1241         } else {
1242             None
1243         };
1244         if let Some(rb) = arm_ref {
1245             let suggestion = if rb == BindingAnnotation::Ref {
1246                 "as_ref"
1247             } else {
1248                 "as_mut"
1249             };
1250
1251             let output_ty = cx.typeck_results().expr_ty(expr);
1252             let input_ty = cx.typeck_results().expr_ty(ex);
1253
1254             let cast = if_chain! {
1255                 if let ty::Adt(_, substs) = input_ty.kind();
1256                 let input_ty = substs.type_at(0);
1257                 if let ty::Adt(_, substs) = output_ty.kind();
1258                 let output_ty = substs.type_at(0);
1259                 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1260                 if input_ty != output_ty;
1261                 then {
1262                     ".map(|x| x as _)"
1263                 } else {
1264                     ""
1265                 }
1266             };
1267
1268             let mut applicability = Applicability::MachineApplicable;
1269             span_lint_and_sugg(
1270                 cx,
1271                 MATCH_AS_REF,
1272                 expr.span,
1273                 &format!("use `{}()` instead", suggestion),
1274                 "try this",
1275                 format!(
1276                     "{}.{}(){}",
1277                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1278                     suggestion,
1279                     cast,
1280                 ),
1281                 applicability,
1282             );
1283         }
1284     }
1285 }
1286
1287 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1288     for arm in arms {
1289         if let PatKind::Or(fields) = arm.pat.kind {
1290             // look for multiple fields in this arm that contains at least one Wild pattern
1291             if fields.len() > 1 && fields.iter().any(is_wild) {
1292                 span_lint_and_help(
1293                     cx,
1294                     WILDCARD_IN_OR_PATTERNS,
1295                     arm.pat.span,
1296                     "wildcard pattern covers any other pattern as it will match anyway",
1297                     None,
1298                     "consider handling `_` separately",
1299                 );
1300             }
1301         }
1302     }
1303 }
1304
1305 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1306 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1307     if let Some(higher::IfLet {
1308         let_pat,
1309         let_expr,
1310         if_then,
1311         if_else: Some(if_else),
1312     }) = higher::IfLet::hir(cx, expr)
1313     {
1314         return find_matches_sugg(
1315             cx,
1316             let_expr,
1317             array::IntoIter::new([(&[][..], Some(let_pat), if_then, None), (&[][..], None, if_else, None)]),
1318             expr,
1319             true,
1320         );
1321     }
1322
1323     if let ExprKind::Match(scrut, arms, MatchSource::Normal) = expr.kind {
1324         return find_matches_sugg(
1325             cx,
1326             scrut,
1327             arms.iter().map(|arm| {
1328                 (
1329                     cx.tcx.hir().attrs(arm.hir_id),
1330                     Some(arm.pat),
1331                     arm.body,
1332                     arm.guard.as_ref(),
1333                 )
1334             }),
1335             expr,
1336             false,
1337         );
1338     }
1339
1340     false
1341 }
1342
1343 /// Lint a `match` or `if let` for replacement by `matches!`
1344 fn find_matches_sugg<'a, 'b, I>(
1345     cx: &LateContext<'_>,
1346     ex: &Expr<'_>,
1347     mut iter: I,
1348     expr: &Expr<'_>,
1349     is_if_let: bool,
1350 ) -> bool
1351 where
1352     'b: 'a,
1353     I: Clone
1354         + DoubleEndedIterator
1355         + ExactSizeIterator
1356         + Iterator<
1357             Item = (
1358                 &'a [Attribute],
1359                 Option<&'a Pat<'b>>,
1360                 &'a Expr<'b>,
1361                 Option<&'a Guard<'b>>,
1362             ),
1363         >,
1364 {
1365     if_chain! {
1366         if iter.len() >= 2;
1367         if cx.typeck_results().expr_ty(expr).is_bool();
1368         if let Some((_, last_pat_opt, last_expr, _)) = iter.next_back();
1369         let iter_without_last = iter.clone();
1370         if let Some((first_attrs, _, first_expr, first_guard)) = iter.next();
1371         if let Some(b0) = find_bool_lit(&first_expr.kind, is_if_let);
1372         if let Some(b1) = find_bool_lit(&last_expr.kind, is_if_let);
1373         if b0 != b1;
1374         if first_guard.is_none() || iter.len() == 0;
1375         if first_attrs.is_empty();
1376         if iter
1377             .all(|arm| {
1378                 find_bool_lit(&arm.2.kind, is_if_let).map_or(false, |b| b == b0) && arm.3.is_none() && arm.0.is_empty()
1379             });
1380         then {
1381             if let Some(last_pat) = last_pat_opt {
1382                 if !is_wild(last_pat) {
1383                     return false;
1384                 }
1385             }
1386
1387             // The suggestion may be incorrect, because some arms can have `cfg` attributes
1388             // evaluated into `false` and so such arms will be stripped before.
1389             let mut applicability = Applicability::MaybeIncorrect;
1390             let pat = {
1391                 use itertools::Itertools as _;
1392                 iter_without_last
1393                     .filter_map(|arm| {
1394                         let pat_span = arm.1?.span;
1395                         Some(snippet_with_applicability(cx, pat_span, "..", &mut applicability))
1396                     })
1397                     .join(" | ")
1398             };
1399             let pat_and_guard = if let Some(Guard::If(g)) = first_guard {
1400                 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1401             } else {
1402                 pat
1403             };
1404
1405             // strip potential borrows (#6503), but only if the type is a reference
1406             let mut ex_new = ex;
1407             if let ExprKind::AddrOf(BorrowKind::Ref, .., ex_inner) = ex.kind {
1408                 if let ty::Ref(..) = cx.typeck_results().expr_ty(ex_inner).kind() {
1409                     ex_new = ex_inner;
1410                 }
1411             };
1412             span_lint_and_sugg(
1413                 cx,
1414                 MATCH_LIKE_MATCHES_MACRO,
1415                 expr.span,
1416                 &format!("{} expression looks like `matches!` macro", if is_if_let { "if let .. else" } else { "match" }),
1417                 "try this",
1418                 format!(
1419                     "{}matches!({}, {})",
1420                     if b0 { "" } else { "!" },
1421                     snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
1422                     pat_and_guard,
1423                 ),
1424                 applicability,
1425             );
1426             true
1427         } else {
1428             false
1429         }
1430     }
1431 }
1432
1433 /// Extract a `bool` or `{ bool }`
1434 fn find_bool_lit(ex: &ExprKind<'_>, is_if_let: bool) -> Option<bool> {
1435     match ex {
1436         ExprKind::Lit(Spanned {
1437             node: LitKind::Bool(b), ..
1438         }) => Some(*b),
1439         ExprKind::Block(
1440             rustc_hir::Block {
1441                 stmts: &[],
1442                 expr: Some(exp),
1443                 ..
1444             },
1445             _,
1446         ) if is_if_let => {
1447             if let ExprKind::Lit(Spanned {
1448                 node: LitKind::Bool(b), ..
1449             }) = exp.kind
1450             {
1451                 Some(b)
1452             } else {
1453                 None
1454             }
1455         },
1456         _ => None,
1457     }
1458 }
1459
1460 #[allow(clippy::too_many_lines)]
1461 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1462     if expr.span.from_expansion() || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1463         return;
1464     }
1465
1466     // HACK:
1467     // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1468     // to prevent false positives as there is currently no better way to detect if code was excluded by
1469     // a macro. See PR #6435
1470     if_chain! {
1471         if let Some(match_snippet) = snippet_opt(cx, expr.span);
1472         if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1473         if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1474         let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1475         if rest_snippet.contains("=>");
1476         then {
1477             // The code it self contains another thick arrow "=>"
1478             // -> Either another arm or a comment
1479             return;
1480         }
1481     }
1482
1483     let matched_vars = ex.span;
1484     let bind_names = arms[0].pat.span;
1485     let match_body = remove_blocks(arms[0].body);
1486     let mut snippet_body = if match_body.span.from_expansion() {
1487         Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1488     } else {
1489         snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1490     };
1491
1492     // Do we need to add ';' to suggestion ?
1493     match match_body.kind {
1494         ExprKind::Block(block, _) => {
1495             // macro + expr_ty(body) == ()
1496             if block.span.from_expansion() && cx.typeck_results().expr_ty(match_body).is_unit() {
1497                 snippet_body.push(';');
1498             }
1499         },
1500         _ => {
1501             // expr_ty(body) == ()
1502             if cx.typeck_results().expr_ty(match_body).is_unit() {
1503                 snippet_body.push(';');
1504             }
1505         },
1506     }
1507
1508     let mut applicability = Applicability::MaybeIncorrect;
1509     match arms[0].pat.kind {
1510         PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1511             // If this match is in a local (`let`) stmt
1512             let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1513                 (
1514                     parent_let_node.span,
1515                     format!(
1516                         "let {} = {};\n{}let {} = {};",
1517                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1518                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1519                         " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1520                         snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1521                         snippet_body
1522                     ),
1523                 )
1524             } else {
1525                 // If we are in closure, we need curly braces around suggestion
1526                 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1527                 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1528                 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1529                     if let ExprKind::Closure(..) = parent_expr.kind {
1530                         cbrace_end = format!("\n{}}}", indent);
1531                         // Fix body indent due to the closure
1532                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1533                         cbrace_start = format!("{{\n{}", indent);
1534                     }
1535                 }
1536                 // If the parent is already an arm, and the body is another match statement,
1537                 // we need curly braces around suggestion
1538                 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1539                 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1540                     if let ExprKind::Match(..) = arm.body.kind {
1541                         cbrace_end = format!("\n{}}}", indent);
1542                         // Fix body indent due to the match
1543                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1544                         cbrace_start = format!("{{\n{}", indent);
1545                     }
1546                 }
1547                 (
1548                     expr.span,
1549                     format!(
1550                         "{}let {} = {};\n{}{}{}",
1551                         cbrace_start,
1552                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1553                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1554                         indent,
1555                         snippet_body,
1556                         cbrace_end
1557                     ),
1558                 )
1559             };
1560             span_lint_and_sugg(
1561                 cx,
1562                 MATCH_SINGLE_BINDING,
1563                 target_span,
1564                 "this match could be written as a `let` statement",
1565                 "consider using `let` statement",
1566                 sugg,
1567                 applicability,
1568             );
1569         },
1570         PatKind::Wild => {
1571             if ex.can_have_side_effects() {
1572                 let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0));
1573                 let sugg = format!(
1574                     "{};\n{}{}",
1575                     snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1576                     indent,
1577                     snippet_body
1578                 );
1579                 span_lint_and_sugg(
1580                     cx,
1581                     MATCH_SINGLE_BINDING,
1582                     expr.span,
1583                     "this match could be replaced by its scrutinee and body",
1584                     "consider using the scrutinee and body instead",
1585                     sugg,
1586                     applicability,
1587                 );
1588             } else {
1589                 span_lint_and_sugg(
1590                     cx,
1591                     MATCH_SINGLE_BINDING,
1592                     expr.span,
1593                     "this match could be replaced by its body itself",
1594                     "consider using the match body instead",
1595                     snippet_body,
1596                     Applicability::MachineApplicable,
1597                 );
1598             }
1599         },
1600         _ => (),
1601     }
1602 }
1603
1604 /// Returns true if the `ex` match expression is in a local (`let`) statement
1605 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1606     let map = &cx.tcx.hir();
1607     if_chain! {
1608         if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1609         if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1610         then {
1611             return Some(parent_let_expr);
1612         }
1613     }
1614     None
1615 }
1616
1617 /// Gets the ranges for each range pattern arm. Applies `ty` bounds for open ranges.
1618 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<FullInt>> {
1619     arms.iter()
1620         .filter_map(|arm| {
1621             if let Arm { pat, guard: None, .. } = *arm {
1622                 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1623                     let lhs_const = match lhs {
1624                         Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1625                         None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1626                     };
1627                     let rhs_const = match rhs {
1628                         Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1629                         None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1630                     };
1631
1632                     let lhs_val = lhs_const.int_value(cx, ty)?;
1633                     let rhs_val = rhs_const.int_value(cx, ty)?;
1634
1635                     let rhs_bound = match range_end {
1636                         RangeEnd::Included => EndBound::Included(rhs_val),
1637                         RangeEnd::Excluded => EndBound::Excluded(rhs_val),
1638                     };
1639                     return Some(SpannedRange {
1640                         span: pat.span,
1641                         node: (lhs_val, rhs_bound),
1642                     });
1643                 }
1644
1645                 if let PatKind::Lit(value) = pat.kind {
1646                     let value = constant_full_int(cx, cx.typeck_results(), value)?;
1647                     return Some(SpannedRange {
1648                         span: pat.span,
1649                         node: (value, EndBound::Included(value)),
1650                     });
1651                 }
1652             }
1653             None
1654         })
1655         .collect()
1656 }
1657
1658 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1659 pub enum EndBound<T> {
1660     Included(T),
1661     Excluded(T),
1662 }
1663
1664 #[derive(Debug, Eq, PartialEq)]
1665 struct SpannedRange<T> {
1666     pub span: Span,
1667     pub node: (T, EndBound<T>),
1668 }
1669
1670 // Checks if arm has the form `None => None`
1671 fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1672     matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
1673 }
1674
1675 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1676 fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotation> {
1677     if_chain! {
1678         if let PatKind::TupleStruct(ref qpath, [first_pat, ..], _) = arm.pat.kind;
1679         if is_lang_ctor(cx, qpath, OptionSome);
1680         if let PatKind::Binding(rb, .., ident, _) = first_pat.kind;
1681         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1682         if let ExprKind::Call(e, args) = remove_blocks(arm.body).kind;
1683         if let ExprKind::Path(ref some_path) = e.kind;
1684         if is_lang_ctor(cx, some_path, OptionSome) && args.len() == 1;
1685         if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
1686         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1687         then {
1688             return Some(rb)
1689         }
1690     }
1691     None
1692 }
1693
1694 fn has_multiple_ref_pats<'a, 'b, I>(pats: I) -> bool
1695 where
1696     'b: 'a,
1697     I: Iterator<Item = &'a Pat<'b>>,
1698 {
1699     let mut ref_count = 0;
1700     for opt in pats.map(|pat| match pat.kind {
1701         PatKind::Ref(..) => Some(true), // &-patterns
1702         PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
1703         _ => None,                      // any other pattern is not fine
1704     }) {
1705         if let Some(inner) = opt {
1706             if inner {
1707                 ref_count += 1;
1708             }
1709         } else {
1710             return false;
1711         }
1712     }
1713     ref_count > 1
1714 }
1715
1716 fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1717 where
1718     T: Copy + Ord,
1719 {
1720     #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
1721     enum BoundKind {
1722         EndExcluded,
1723         Start,
1724         EndIncluded,
1725     }
1726
1727     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1728     struct RangeBound<'a, T>(T, BoundKind, &'a SpannedRange<T>);
1729
1730     impl<'a, T: Copy + Ord> PartialOrd for RangeBound<'a, T> {
1731         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1732             Some(self.cmp(other))
1733         }
1734     }
1735
1736     impl<'a, T: Copy + Ord> Ord for RangeBound<'a, T> {
1737         fn cmp(&self, RangeBound(other_value, other_kind, _): &Self) -> Ordering {
1738             let RangeBound(self_value, self_kind, _) = *self;
1739             (self_value, self_kind).cmp(&(*other_value, *other_kind))
1740         }
1741     }
1742
1743     let mut values = Vec::with_capacity(2 * ranges.len());
1744
1745     for r @ SpannedRange { node: (start, end), .. } in ranges {
1746         values.push(RangeBound(*start, BoundKind::Start, r));
1747         values.push(match end {
1748             EndBound::Excluded(val) => RangeBound(*val, BoundKind::EndExcluded, r),
1749             EndBound::Included(val) => RangeBound(*val, BoundKind::EndIncluded, r),
1750         });
1751     }
1752
1753     values.sort();
1754
1755     let mut started = vec![];
1756
1757     for RangeBound(_, kind, range) in values {
1758         match kind {
1759             BoundKind::Start => started.push(range),
1760             BoundKind::EndExcluded | BoundKind::EndIncluded => {
1761                 let mut overlap = None;
1762
1763                 while let Some(last_started) = started.pop() {
1764                     if last_started == range {
1765                         break;
1766                     }
1767                     overlap = Some(last_started);
1768                 }
1769
1770                 if let Some(first_overlapping) = overlap {
1771                     return Some((range, first_overlapping));
1772                 }
1773             },
1774         }
1775     }
1776
1777     None
1778 }
1779
1780 mod redundant_pattern_match {
1781     use super::REDUNDANT_PATTERN_MATCHING;
1782     use clippy_utils::diagnostics::span_lint_and_then;
1783     use clippy_utils::higher;
1784     use clippy_utils::source::snippet;
1785     use clippy_utils::sugg::Sugg;
1786     use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, is_type_lang_item, match_type};
1787     use clippy_utils::{is_lang_ctor, is_qpath_def_path, is_trait_method, paths};
1788     use if_chain::if_chain;
1789     use rustc_ast::ast::LitKind;
1790     use rustc_data_structures::fx::FxHashSet;
1791     use rustc_errors::Applicability;
1792     use rustc_hir::LangItem::{OptionNone, OptionSome, PollPending, PollReady, ResultErr, ResultOk};
1793     use rustc_hir::{
1794         intravisit::{walk_expr, ErasedMap, NestedVisitorMap, Visitor},
1795         Arm, Block, Expr, ExprKind, LangItem, MatchSource, Node, Pat, PatKind, QPath, UnOp,
1796     };
1797     use rustc_lint::LateContext;
1798     use rustc_middle::ty::{self, subst::GenericArgKind, Ty};
1799     use rustc_span::sym;
1800
1801     pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1802         if let Some(higher::IfLet {
1803             if_else,
1804             let_pat,
1805             let_expr,
1806             ..
1807         }) = higher::IfLet::hir(cx, expr)
1808         {
1809             find_sugg_for_if_let(cx, expr, let_pat, let_expr, "if", if_else.is_some());
1810         }
1811         if let ExprKind::Match(op, arms, MatchSource::Normal) = &expr.kind {
1812             find_sugg_for_match(cx, expr, op, arms);
1813         }
1814         if let Some(higher::WhileLet { let_pat, let_expr, .. }) = higher::WhileLet::hir(expr) {
1815             find_sugg_for_if_let(cx, expr, let_pat, let_expr, "while", false);
1816         }
1817     }
1818
1819     /// Checks if the drop order for a type matters. Some std types implement drop solely to
1820     /// deallocate memory. For these types, and composites containing them, changing the drop order
1821     /// won't result in any observable side effects.
1822     fn type_needs_ordered_drop(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1823         type_needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
1824     }
1825
1826     fn type_needs_ordered_drop_inner(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet<Ty<'tcx>>) -> bool {
1827         if !seen.insert(ty) {
1828             return false;
1829         }
1830         if !ty.needs_drop(cx.tcx, cx.param_env) {
1831             false
1832         } else if !cx
1833             .tcx
1834             .lang_items()
1835             .drop_trait()
1836             .map_or(false, |id| implements_trait(cx, ty, id, &[]))
1837         {
1838             // This type doesn't implement drop, so no side effects here.
1839             // Check if any component type has any.
1840             match ty.kind() {
1841                 ty::Tuple(_) => ty.tuple_fields().any(|ty| type_needs_ordered_drop_inner(cx, ty, seen)),
1842                 ty::Array(ty, _) => type_needs_ordered_drop_inner(cx, ty, seen),
1843                 ty::Adt(adt, subs) => adt
1844                     .all_fields()
1845                     .map(|f| f.ty(cx.tcx, subs))
1846                     .any(|ty| type_needs_ordered_drop_inner(cx, ty, seen)),
1847                 _ => true,
1848             }
1849         }
1850         // Check for std types which implement drop, but only for memory allocation.
1851         else if is_type_diagnostic_item(cx, ty, sym::Vec)
1852             || is_type_lang_item(cx, ty, LangItem::OwnedBox)
1853             || is_type_diagnostic_item(cx, ty, sym::Rc)
1854             || is_type_diagnostic_item(cx, ty, sym::Arc)
1855             || is_type_diagnostic_item(cx, ty, sym::cstring_type)
1856             || is_type_diagnostic_item(cx, ty, sym::BTreeMap)
1857             || is_type_diagnostic_item(cx, ty, sym::LinkedList)
1858             || match_type(cx, ty, &paths::WEAK_RC)
1859             || match_type(cx, ty, &paths::WEAK_ARC)
1860         {
1861             // Check all of the generic arguments.
1862             if let ty::Adt(_, subs) = ty.kind() {
1863                 subs.types().any(|ty| type_needs_ordered_drop_inner(cx, ty, seen))
1864             } else {
1865                 true
1866             }
1867         } else {
1868             true
1869         }
1870     }
1871
1872     // Extract the generic arguments out of a type
1873     fn try_get_generic_ty(ty: Ty<'_>, index: usize) -> Option<Ty<'_>> {
1874         if_chain! {
1875             if let ty::Adt(_, subs) = ty.kind();
1876             if let Some(sub) = subs.get(index);
1877             if let GenericArgKind::Type(sub_ty) = sub.unpack();
1878             then {
1879                 Some(sub_ty)
1880             } else {
1881                 None
1882             }
1883         }
1884     }
1885
1886     // Checks if there are any temporaries created in the given expression for which drop order
1887     // matters.
1888     fn temporaries_need_ordered_drop(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1889         struct V<'a, 'tcx> {
1890             cx: &'a LateContext<'tcx>,
1891             res: bool,
1892         }
1893         impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> {
1894             type Map = ErasedMap<'tcx>;
1895             fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1896                 NestedVisitorMap::None
1897             }
1898
1899             fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1900                 match expr.kind {
1901                     // Taking the reference of a value leaves a temporary
1902                     // e.g. In `&String::new()` the string is a temporary value.
1903                     // Remaining fields are temporary values
1904                     // e.g. In `(String::new(), 0).1` the string is a temporary value.
1905                     ExprKind::AddrOf(_, _, expr) | ExprKind::Field(expr, _) => {
1906                         if !matches!(expr.kind, ExprKind::Path(_)) {
1907                             if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(expr)) {
1908                                 self.res = true;
1909                             } else {
1910                                 self.visit_expr(expr);
1911                             }
1912                         }
1913                     },
1914                     // the base type is alway taken by reference.
1915                     // e.g. In `(vec![0])[0]` the vector is a temporary value.
1916                     ExprKind::Index(base, index) => {
1917                         if !matches!(base.kind, ExprKind::Path(_)) {
1918                             if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(base)) {
1919                                 self.res = true;
1920                             } else {
1921                                 self.visit_expr(base);
1922                             }
1923                         }
1924                         self.visit_expr(index);
1925                     },
1926                     // Method calls can take self by reference.
1927                     // e.g. In `String::new().len()` the string is a temporary value.
1928                     ExprKind::MethodCall(_, _, [self_arg, args @ ..], _) => {
1929                         if !matches!(self_arg.kind, ExprKind::Path(_)) {
1930                             let self_by_ref = self
1931                                 .cx
1932                                 .typeck_results()
1933                                 .type_dependent_def_id(expr.hir_id)
1934                                 .map_or(false, |id| self.cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref());
1935                             if self_by_ref
1936                                 && type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(self_arg))
1937                             {
1938                                 self.res = true;
1939                             } else {
1940                                 self.visit_expr(self_arg);
1941                             }
1942                         }
1943                         args.iter().for_each(|arg| self.visit_expr(arg));
1944                     },
1945                     // Either explicitly drops values, or changes control flow.
1946                     ExprKind::DropTemps(_)
1947                     | ExprKind::Ret(_)
1948                     | ExprKind::Break(..)
1949                     | ExprKind::Yield(..)
1950                     | ExprKind::Block(Block { expr: None, .. }, _)
1951                     | ExprKind::Loop(..) => (),
1952
1953                     // Only consider the final expression.
1954                     ExprKind::Block(Block { expr: Some(expr), .. }, _) => self.visit_expr(expr),
1955
1956                     _ => walk_expr(self, expr),
1957                 }
1958             }
1959         }
1960
1961         let mut v = V { cx, res: false };
1962         v.visit_expr(expr);
1963         v.res
1964     }
1965
1966     fn find_sugg_for_if_let<'tcx>(
1967         cx: &LateContext<'tcx>,
1968         expr: &'tcx Expr<'_>,
1969         let_pat: &Pat<'_>,
1970         let_expr: &'tcx Expr<'_>,
1971         keyword: &'static str,
1972         has_else: bool,
1973     ) {
1974         // also look inside refs
1975         let mut kind = &let_pat.kind;
1976         // if we have &None for example, peel it so we can detect "if let None = x"
1977         if let PatKind::Ref(inner, _mutability) = kind {
1978             kind = &inner.kind;
1979         }
1980         let op_ty = cx.typeck_results().expr_ty(let_expr);
1981         // Determine which function should be used, and the type contained by the corresponding
1982         // variant.
1983         let (good_method, inner_ty) = match kind {
1984             PatKind::TupleStruct(ref path, [sub_pat], _) => {
1985                 if let PatKind::Wild = sub_pat.kind {
1986                     if is_lang_ctor(cx, path, ResultOk) {
1987                         ("is_ok()", try_get_generic_ty(op_ty, 0).unwrap_or(op_ty))
1988                     } else if is_lang_ctor(cx, path, ResultErr) {
1989                         ("is_err()", try_get_generic_ty(op_ty, 1).unwrap_or(op_ty))
1990                     } else if is_lang_ctor(cx, path, OptionSome) {
1991                         ("is_some()", op_ty)
1992                     } else if is_lang_ctor(cx, path, PollReady) {
1993                         ("is_ready()", op_ty)
1994                     } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V4) {
1995                         ("is_ipv4()", op_ty)
1996                     } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V6) {
1997                         ("is_ipv6()", op_ty)
1998                     } else {
1999                         return;
2000                     }
2001                 } else {
2002                     return;
2003                 }
2004             },
2005             PatKind::Path(ref path) => {
2006                 let method = if is_lang_ctor(cx, path, OptionNone) {
2007                     "is_none()"
2008                 } else if is_lang_ctor(cx, path, PollPending) {
2009                     "is_pending()"
2010                 } else {
2011                     return;
2012                 };
2013                 // `None` and `Pending` don't have an inner type.
2014                 (method, cx.tcx.types.unit)
2015             },
2016             _ => return,
2017         };
2018
2019         // If this is the last expression in a block or there is an else clause then the whole
2020         // type needs to be considered, not just the inner type of the branch being matched on.
2021         // Note the last expression in a block is dropped after all local bindings.
2022         let check_ty = if has_else
2023             || (keyword == "if" && matches!(cx.tcx.hir().parent_iter(expr.hir_id).next(), Some((_, Node::Block(..)))))
2024         {
2025             op_ty
2026         } else {
2027             inner_ty
2028         };
2029
2030         // All temporaries created in the scrutinee expression are dropped at the same time as the
2031         // scrutinee would be, so they have to be considered as well.
2032         // e.g. in `if let Some(x) = foo.lock().unwrap().baz.as_ref() { .. }` the lock will be held
2033         // for the duration if body.
2034         let needs_drop = type_needs_ordered_drop(cx, check_ty) || temporaries_need_ordered_drop(cx, let_expr);
2035
2036         // check that `while_let_on_iterator` lint does not trigger
2037         if_chain! {
2038             if keyword == "while";
2039             if let ExprKind::MethodCall(method_path, _, _, _) = let_expr.kind;
2040             if method_path.ident.name == sym::next;
2041             if is_trait_method(cx, let_expr, sym::Iterator);
2042             then {
2043                 return;
2044             }
2045         }
2046
2047         let result_expr = match &let_expr.kind {
2048             ExprKind::AddrOf(_, _, borrowed) => borrowed,
2049             ExprKind::Unary(UnOp::Deref, deref) => deref,
2050             _ => let_expr,
2051         };
2052
2053         span_lint_and_then(
2054             cx,
2055             REDUNDANT_PATTERN_MATCHING,
2056             let_pat.span,
2057             &format!("redundant pattern matching, consider using `{}`", good_method),
2058             |diag| {
2059                 // if/while let ... = ... { ... }
2060                 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
2061                 let expr_span = expr.span;
2062
2063                 // if/while let ... = ... { ... }
2064                 //                 ^^^
2065                 let op_span = result_expr.span.source_callsite();
2066
2067                 // if/while let ... = ... { ... }
2068                 // ^^^^^^^^^^^^^^^^^^^
2069                 let span = expr_span.until(op_span.shrink_to_hi());
2070
2071                 let app = if needs_drop {
2072                     Applicability::MaybeIncorrect
2073                 } else {
2074                     Applicability::MachineApplicable
2075                 };
2076
2077                 let sugg = Sugg::hir_with_macro_callsite(cx, result_expr, "_")
2078                     .maybe_par()
2079                     .to_string();
2080
2081                 diag.span_suggestion(span, "try this", format!("{} {}.{}", keyword, sugg, good_method), app);
2082
2083                 if needs_drop {
2084                     diag.note("this will change drop order of the result, as well as all temporaries");
2085                     diag.note("add `#[allow(clippy::redundant_pattern_matching)]` if this is important");
2086                 }
2087             },
2088         );
2089     }
2090
2091     fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
2092         if arms.len() == 2 {
2093             let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
2094
2095             let found_good_method = match node_pair {
2096                 (
2097                     PatKind::TupleStruct(ref path_left, patterns_left, _),
2098                     PatKind::TupleStruct(ref path_right, patterns_right, _),
2099                 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
2100                     if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
2101                         find_good_method_for_match(
2102                             cx,
2103                             arms,
2104                             path_left,
2105                             path_right,
2106                             &paths::RESULT_OK,
2107                             &paths::RESULT_ERR,
2108                             "is_ok()",
2109                             "is_err()",
2110                         )
2111                         .or_else(|| {
2112                             find_good_method_for_match(
2113                                 cx,
2114                                 arms,
2115                                 path_left,
2116                                 path_right,
2117                                 &paths::IPADDR_V4,
2118                                 &paths::IPADDR_V6,
2119                                 "is_ipv4()",
2120                                 "is_ipv6()",
2121                             )
2122                         })
2123                     } else {
2124                         None
2125                     }
2126                 },
2127                 (PatKind::TupleStruct(ref path_left, patterns, _), PatKind::Path(ref path_right))
2128                 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, patterns, _))
2129                     if patterns.len() == 1 =>
2130                 {
2131                     if let PatKind::Wild = patterns[0].kind {
2132                         find_good_method_for_match(
2133                             cx,
2134                             arms,
2135                             path_left,
2136                             path_right,
2137                             &paths::OPTION_SOME,
2138                             &paths::OPTION_NONE,
2139                             "is_some()",
2140                             "is_none()",
2141                         )
2142                         .or_else(|| {
2143                             find_good_method_for_match(
2144                                 cx,
2145                                 arms,
2146                                 path_left,
2147                                 path_right,
2148                                 &paths::POLL_READY,
2149                                 &paths::POLL_PENDING,
2150                                 "is_ready()",
2151                                 "is_pending()",
2152                             )
2153                         })
2154                     } else {
2155                         None
2156                     }
2157                 },
2158                 _ => None,
2159             };
2160
2161             if let Some(good_method) = found_good_method {
2162                 let span = expr.span.to(op.span);
2163                 let result_expr = match &op.kind {
2164                     ExprKind::AddrOf(_, _, borrowed) => borrowed,
2165                     _ => op,
2166                 };
2167                 span_lint_and_then(
2168                     cx,
2169                     REDUNDANT_PATTERN_MATCHING,
2170                     expr.span,
2171                     &format!("redundant pattern matching, consider using `{}`", good_method),
2172                     |diag| {
2173                         diag.span_suggestion(
2174                             span,
2175                             "try this",
2176                             format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
2177                             Applicability::MaybeIncorrect, // snippet
2178                         );
2179                     },
2180                 );
2181             }
2182         }
2183     }
2184
2185     #[allow(clippy::too_many_arguments)]
2186     fn find_good_method_for_match<'a>(
2187         cx: &LateContext<'_>,
2188         arms: &[Arm<'_>],
2189         path_left: &QPath<'_>,
2190         path_right: &QPath<'_>,
2191         expected_left: &[&str],
2192         expected_right: &[&str],
2193         should_be_left: &'a str,
2194         should_be_right: &'a str,
2195     ) -> Option<&'a str> {
2196         let body_node_pair = if is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_left)
2197             && is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_right)
2198         {
2199             (&(*arms[0].body).kind, &(*arms[1].body).kind)
2200         } else if is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_left)
2201             && is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_right)
2202         {
2203             (&(*arms[1].body).kind, &(*arms[0].body).kind)
2204         } else {
2205             return None;
2206         };
2207
2208         match body_node_pair {
2209             (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
2210                 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
2211                 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
2212                 _ => None,
2213             },
2214             _ => None,
2215         }
2216     }
2217 }
2218
2219 #[test]
2220 fn test_overlapping() {
2221     use rustc_span::source_map::DUMMY_SP;
2222
2223     let sp = |s, e| SpannedRange {
2224         span: DUMMY_SP,
2225         node: (s, e),
2226     };
2227
2228     assert_eq!(None, overlapping::<u8>(&[]));
2229     assert_eq!(None, overlapping(&[sp(1, EndBound::Included(4))]));
2230     assert_eq!(
2231         None,
2232         overlapping(&[sp(1, EndBound::Included(4)), sp(5, EndBound::Included(6))])
2233     );
2234     assert_eq!(
2235         None,
2236         overlapping(&[
2237             sp(1, EndBound::Included(4)),
2238             sp(5, EndBound::Included(6)),
2239             sp(10, EndBound::Included(11))
2240         ],)
2241     );
2242     assert_eq!(
2243         Some((&sp(1, EndBound::Included(4)), &sp(3, EndBound::Included(6)))),
2244         overlapping(&[sp(1, EndBound::Included(4)), sp(3, EndBound::Included(6))])
2245     );
2246     assert_eq!(
2247         Some((&sp(5, EndBound::Included(6)), &sp(6, EndBound::Included(11)))),
2248         overlapping(&[
2249             sp(1, EndBound::Included(4)),
2250             sp(5, EndBound::Included(6)),
2251             sp(6, EndBound::Included(11))
2252         ],)
2253     );
2254 }
2255
2256 /// Implementation of `MATCH_SAME_ARMS`.
2257 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
2258     if let ExprKind::Match(_, arms, MatchSource::Normal) = expr.kind {
2259         let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
2260             let mut h = SpanlessHash::new(cx);
2261             h.hash_expr(arm.body);
2262             h.finish()
2263         };
2264
2265         let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
2266             let min_index = usize::min(lindex, rindex);
2267             let max_index = usize::max(lindex, rindex);
2268
2269             let mut local_map: HirIdMap<HirId> = HirIdMap::default();
2270             let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
2271                 if_chain! {
2272                     if let Some(a_id) = path_to_local(a);
2273                     if let Some(b_id) = path_to_local(b);
2274                     let entry = match local_map.entry(a_id) {
2275                         Entry::Vacant(entry) => entry,
2276                         // check if using the same bindings as before
2277                         Entry::Occupied(entry) => return *entry.get() == b_id,
2278                     };
2279                     // the names technically don't have to match; this makes the lint more conservative
2280                     if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id);
2281                     if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b));
2282                     if pat_contains_local(lhs.pat, a_id);
2283                     if pat_contains_local(rhs.pat, b_id);
2284                     then {
2285                         entry.insert(b_id);
2286                         true
2287                     } else {
2288                         false
2289                     }
2290                 }
2291             };
2292             // Arms with a guard are ignored, those can’t always be merged together
2293             // This is also the case for arms in-between each there is an arm with a guard
2294             (min_index..=max_index).all(|index| arms[index].guard.is_none())
2295                 && SpanlessEq::new(cx)
2296                     .expr_fallback(eq_fallback)
2297                     .eq_expr(lhs.body, rhs.body)
2298                 // these checks could be removed to allow unused bindings
2299                 && bindings_eq(lhs.pat, local_map.keys().copied().collect())
2300                 && bindings_eq(rhs.pat, local_map.values().copied().collect())
2301         };
2302
2303         let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
2304         for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
2305             span_lint_and_then(
2306                 cx,
2307                 MATCH_SAME_ARMS,
2308                 j.body.span,
2309                 "this `match` has identical arm bodies",
2310                 |diag| {
2311                     diag.span_note(i.body.span, "same as this");
2312
2313                     // Note: this does not use `span_suggestion` on purpose:
2314                     // there is no clean way
2315                     // to remove the other arm. Building a span and suggest to replace it to ""
2316                     // makes an even more confusing error message. Also in order not to make up a
2317                     // span for the whole pattern, the suggestion is only shown when there is only
2318                     // one pattern. The user should know about `|` if they are already using it…
2319
2320                     let lhs = snippet(cx, i.pat.span, "<pat1>");
2321                     let rhs = snippet(cx, j.pat.span, "<pat2>");
2322
2323                     if let PatKind::Wild = j.pat.kind {
2324                         // if the last arm is _, then i could be integrated into _
2325                         // note that i.pat cannot be _, because that would mean that we're
2326                         // hiding all the subsequent arms, and rust won't compile
2327                         diag.span_note(
2328                             i.body.span,
2329                             &format!(
2330                                 "`{}` has the same arm body as the `_` wildcard, consider removing it",
2331                                 lhs
2332                             ),
2333                         );
2334                     } else {
2335                         diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs,))
2336                             .help("...or consider changing the match arm bodies");
2337                     }
2338                 },
2339             );
2340         }
2341     }
2342 }
2343
2344 fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool {
2345     let mut result = false;
2346     pat.walk_short(|p| {
2347         result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id);
2348         !result
2349     });
2350     result
2351 }
2352
2353 /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa
2354 fn bindings_eq(pat: &Pat<'_>, mut ids: HirIdSet) -> bool {
2355     let mut result = true;
2356     pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id));
2357     result && ids.is_empty()
2358 }