]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches/mod.rs
56f1031f9b93a565a0a4bfd104ce72705acb4c69
[rust.git] / clippy_lints / src / matches / mod.rs
1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::{is_wild, meets_msrv, msrvs, path_to_local_id, peel_blocks, strip_pat_refs};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Arm, Expr, ExprKind, Local, MatchSource, Pat, PatKind, QPath};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty;
9 use rustc_semver::RustcVersion;
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
11
12 mod match_as_ref;
13 mod match_bool;
14 mod match_like_matches;
15 mod match_ref_pats;
16 mod match_same_arms;
17 mod match_single_binding;
18 mod match_wild_enum;
19 mod match_wild_err_arm;
20 mod overlapping_arms;
21 mod redundant_pattern_match;
22 mod single_match;
23
24 declare_clippy_lint! {
25     /// ### What it does
26     /// Checks for matches with a single arm where an `if let`
27     /// will usually suffice.
28     ///
29     /// ### Why is this bad?
30     /// Just readability – `if let` nests less than a `match`.
31     ///
32     /// ### Example
33     /// ```rust
34     /// # fn bar(stool: &str) {}
35     /// # let x = Some("abc");
36     /// // Bad
37     /// match x {
38     ///     Some(ref foo) => bar(foo),
39     ///     _ => (),
40     /// }
41     ///
42     /// // Good
43     /// if let Some(ref foo) = x {
44     ///     bar(foo);
45     /// }
46     /// ```
47     #[clippy::version = "pre 1.29.0"]
48     pub SINGLE_MATCH,
49     style,
50     "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
51 }
52
53 declare_clippy_lint! {
54     /// ### What it does
55     /// Checks for matches with two arms where an `if let else` will
56     /// usually suffice.
57     ///
58     /// ### Why is this bad?
59     /// Just readability – `if let` nests less than a `match`.
60     ///
61     /// ### Known problems
62     /// Personal style preferences may differ.
63     ///
64     /// ### Example
65     /// Using `match`:
66     ///
67     /// ```rust
68     /// # fn bar(foo: &usize) {}
69     /// # let other_ref: usize = 1;
70     /// # let x: Option<&usize> = Some(&1);
71     /// match x {
72     ///     Some(ref foo) => bar(foo),
73     ///     _ => bar(&other_ref),
74     /// }
75     /// ```
76     ///
77     /// Using `if let` with `else`:
78     ///
79     /// ```rust
80     /// # fn bar(foo: &usize) {}
81     /// # let other_ref: usize = 1;
82     /// # let x: Option<&usize> = Some(&1);
83     /// if let Some(ref foo) = x {
84     ///     bar(foo);
85     /// } else {
86     ///     bar(&other_ref);
87     /// }
88     /// ```
89     #[clippy::version = "pre 1.29.0"]
90     pub SINGLE_MATCH_ELSE,
91     pedantic,
92     "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
93 }
94
95 declare_clippy_lint! {
96     /// ### What it does
97     /// Checks for matches where all arms match a reference,
98     /// suggesting to remove the reference and deref the matched expression
99     /// instead. It also checks for `if let &foo = bar` blocks.
100     ///
101     /// ### Why is this bad?
102     /// It just makes the code less readable. That reference
103     /// destructuring adds nothing to the code.
104     ///
105     /// ### Example
106     /// ```rust,ignore
107     /// // Bad
108     /// match x {
109     ///     &A(ref y) => foo(y),
110     ///     &B => bar(),
111     ///     _ => frob(&x),
112     /// }
113     ///
114     /// // Good
115     /// match *x {
116     ///     A(ref y) => foo(y),
117     ///     B => bar(),
118     ///     _ => frob(x),
119     /// }
120     /// ```
121     #[clippy::version = "pre 1.29.0"]
122     pub MATCH_REF_PATS,
123     style,
124     "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
125 }
126
127 declare_clippy_lint! {
128     /// ### What it does
129     /// Checks for matches where match expression is a `bool`. It
130     /// suggests to replace the expression with an `if...else` block.
131     ///
132     /// ### Why is this bad?
133     /// It makes the code less readable.
134     ///
135     /// ### Example
136     /// ```rust
137     /// # fn foo() {}
138     /// # fn bar() {}
139     /// let condition: bool = true;
140     /// match condition {
141     ///     true => foo(),
142     ///     false => bar(),
143     /// }
144     /// ```
145     /// Use if/else instead:
146     /// ```rust
147     /// # fn foo() {}
148     /// # fn bar() {}
149     /// let condition: bool = true;
150     /// if condition {
151     ///     foo();
152     /// } else {
153     ///     bar();
154     /// }
155     /// ```
156     #[clippy::version = "pre 1.29.0"]
157     pub MATCH_BOOL,
158     pedantic,
159     "a `match` on a boolean expression instead of an `if..else` block"
160 }
161
162 declare_clippy_lint! {
163     /// ### What it does
164     /// Checks for overlapping match arms.
165     ///
166     /// ### Why is this bad?
167     /// It is likely to be an error and if not, makes the code
168     /// less obvious.
169     ///
170     /// ### Example
171     /// ```rust
172     /// let x = 5;
173     /// match x {
174     ///     1..=10 => println!("1 ... 10"),
175     ///     5..=15 => println!("5 ... 15"),
176     ///     _ => (),
177     /// }
178     /// ```
179     #[clippy::version = "pre 1.29.0"]
180     pub MATCH_OVERLAPPING_ARM,
181     style,
182     "a `match` with overlapping arms"
183 }
184
185 declare_clippy_lint! {
186     /// ### What it does
187     /// Checks for arm which matches all errors with `Err(_)`
188     /// and take drastic actions like `panic!`.
189     ///
190     /// ### Why is this bad?
191     /// It is generally a bad practice, similar to
192     /// catching all exceptions in java with `catch(Exception)`
193     ///
194     /// ### Example
195     /// ```rust
196     /// let x: Result<i32, &str> = Ok(3);
197     /// match x {
198     ///     Ok(_) => println!("ok"),
199     ///     Err(_) => panic!("err"),
200     /// }
201     /// ```
202     #[clippy::version = "pre 1.29.0"]
203     pub MATCH_WILD_ERR_ARM,
204     pedantic,
205     "a `match` with `Err(_)` arm and take drastic actions"
206 }
207
208 declare_clippy_lint! {
209     /// ### What it does
210     /// Checks for match which is used to add a reference to an
211     /// `Option` value.
212     ///
213     /// ### Why is this bad?
214     /// Using `as_ref()` or `as_mut()` instead is shorter.
215     ///
216     /// ### Example
217     /// ```rust
218     /// let x: Option<()> = None;
219     ///
220     /// // Bad
221     /// let r: Option<&()> = match x {
222     ///     None => None,
223     ///     Some(ref v) => Some(v),
224     /// };
225     ///
226     /// // Good
227     /// let r: Option<&()> = x.as_ref();
228     /// ```
229     #[clippy::version = "pre 1.29.0"]
230     pub MATCH_AS_REF,
231     complexity,
232     "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
233 }
234
235 declare_clippy_lint! {
236     /// ### What it does
237     /// Checks for wildcard enum matches using `_`.
238     ///
239     /// ### Why is this bad?
240     /// New enum variants added by library updates can be missed.
241     ///
242     /// ### Known problems
243     /// Suggested replacements may be incorrect if guards exhaustively cover some
244     /// variants, and also may not use correct path to enum if it's not present in the current scope.
245     ///
246     /// ### Example
247     /// ```rust
248     /// # enum Foo { A(usize), B(usize) }
249     /// # let x = Foo::B(1);
250     /// // Bad
251     /// match x {
252     ///     Foo::A(_) => {},
253     ///     _ => {},
254     /// }
255     ///
256     /// // Good
257     /// match x {
258     ///     Foo::A(_) => {},
259     ///     Foo::B(_) => {},
260     /// }
261     /// ```
262     #[clippy::version = "1.34.0"]
263     pub WILDCARD_ENUM_MATCH_ARM,
264     restriction,
265     "a wildcard enum match arm using `_`"
266 }
267
268 declare_clippy_lint! {
269     /// ### What it does
270     /// Checks for wildcard enum matches for a single variant.
271     ///
272     /// ### Why is this bad?
273     /// New enum variants added by library updates can be missed.
274     ///
275     /// ### Known problems
276     /// Suggested replacements may not use correct path to enum
277     /// if it's not present in the current scope.
278     ///
279     /// ### Example
280     /// ```rust
281     /// # enum Foo { A, B, C }
282     /// # let x = Foo::B;
283     /// // Bad
284     /// match x {
285     ///     Foo::A => {},
286     ///     Foo::B => {},
287     ///     _ => {},
288     /// }
289     ///
290     /// // Good
291     /// match x {
292     ///     Foo::A => {},
293     ///     Foo::B => {},
294     ///     Foo::C => {},
295     /// }
296     /// ```
297     #[clippy::version = "1.45.0"]
298     pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
299     pedantic,
300     "a wildcard enum match for a single variant"
301 }
302
303 declare_clippy_lint! {
304     /// ### What it does
305     /// Checks for wildcard pattern used with others patterns in same match arm.
306     ///
307     /// ### Why is this bad?
308     /// Wildcard pattern already covers any other pattern as it will match anyway.
309     /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
310     ///
311     /// ### Example
312     /// ```rust
313     /// // Bad
314     /// match "foo" {
315     ///     "a" => {},
316     ///     "bar" | _ => {},
317     /// }
318     ///
319     /// // Good
320     /// match "foo" {
321     ///     "a" => {},
322     ///     _ => {},
323     /// }
324     /// ```
325     #[clippy::version = "1.42.0"]
326     pub WILDCARD_IN_OR_PATTERNS,
327     complexity,
328     "a wildcard pattern used with others patterns in same match arm"
329 }
330
331 declare_clippy_lint! {
332     /// ### What it does
333     /// Checks for matches being used to destructure a single-variant enum
334     /// or tuple struct where a `let` will suffice.
335     ///
336     /// ### Why is this bad?
337     /// Just readability – `let` doesn't nest, whereas a `match` does.
338     ///
339     /// ### Example
340     /// ```rust
341     /// enum Wrapper {
342     ///     Data(i32),
343     /// }
344     ///
345     /// let wrapper = Wrapper::Data(42);
346     ///
347     /// let data = match wrapper {
348     ///     Wrapper::Data(i) => i,
349     /// };
350     /// ```
351     ///
352     /// The correct use would be:
353     /// ```rust
354     /// enum Wrapper {
355     ///     Data(i32),
356     /// }
357     ///
358     /// let wrapper = Wrapper::Data(42);
359     /// let Wrapper::Data(data) = wrapper;
360     /// ```
361     #[clippy::version = "pre 1.29.0"]
362     pub INFALLIBLE_DESTRUCTURING_MATCH,
363     style,
364     "a `match` statement with a single infallible arm instead of a `let`"
365 }
366
367 declare_clippy_lint! {
368     /// ### What it does
369     /// Checks for useless match that binds to only one value.
370     ///
371     /// ### Why is this bad?
372     /// Readability and needless complexity.
373     ///
374     /// ### Known problems
375     ///  Suggested replacements may be incorrect when `match`
376     /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
377     ///
378     /// ### Example
379     /// ```rust
380     /// # let a = 1;
381     /// # let b = 2;
382     ///
383     /// // Bad
384     /// match (a, b) {
385     ///     (c, d) => {
386     ///         // useless match
387     ///     }
388     /// }
389     ///
390     /// // Good
391     /// let (c, d) = (a, b);
392     /// ```
393     #[clippy::version = "1.43.0"]
394     pub MATCH_SINGLE_BINDING,
395     complexity,
396     "a match with a single binding instead of using `let` statement"
397 }
398
399 declare_clippy_lint! {
400     /// ### What it does
401     /// Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
402     ///
403     /// ### Why is this bad?
404     /// Correctness and readability. It's like having a wildcard pattern after
405     /// matching all enum variants explicitly.
406     ///
407     /// ### Example
408     /// ```rust
409     /// # struct A { a: i32 }
410     /// let a = A { a: 5 };
411     ///
412     /// // Bad
413     /// match a {
414     ///     A { a: 5, .. } => {},
415     ///     _ => {},
416     /// }
417     ///
418     /// // Good
419     /// match a {
420     ///     A { a: 5 } => {},
421     ///     _ => {},
422     /// }
423     /// ```
424     #[clippy::version = "1.43.0"]
425     pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
426     restriction,
427     "a match on a struct that binds all fields but still uses the wildcard pattern"
428 }
429
430 declare_clippy_lint! {
431     /// ### What it does
432     /// Lint for redundant pattern matching over `Result`, `Option`,
433     /// `std::task::Poll` or `std::net::IpAddr`
434     ///
435     /// ### Why is this bad?
436     /// It's more concise and clear to just use the proper
437     /// utility function
438     ///
439     /// ### Known problems
440     /// This will change the drop order for the matched type. Both `if let` and
441     /// `while let` will drop the value at the end of the block, both `if` and `while` will drop the
442     /// value before entering the block. For most types this change will not matter, but for a few
443     /// types this will not be an acceptable change (e.g. locks). See the
444     /// [reference](https://doc.rust-lang.org/reference/destructors.html#drop-scopes) for more about
445     /// drop order.
446     ///
447     /// ### Example
448     /// ```rust
449     /// # use std::task::Poll;
450     /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
451     /// if let Ok(_) = Ok::<i32, i32>(42) {}
452     /// if let Err(_) = Err::<i32, i32>(42) {}
453     /// if let None = None::<()> {}
454     /// if let Some(_) = Some(42) {}
455     /// if let Poll::Pending = Poll::Pending::<()> {}
456     /// if let Poll::Ready(_) = Poll::Ready(42) {}
457     /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
458     /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
459     /// match Ok::<i32, i32>(42) {
460     ///     Ok(_) => true,
461     ///     Err(_) => false,
462     /// };
463     /// ```
464     ///
465     /// The more idiomatic use would be:
466     ///
467     /// ```rust
468     /// # use std::task::Poll;
469     /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
470     /// if Ok::<i32, i32>(42).is_ok() {}
471     /// if Err::<i32, i32>(42).is_err() {}
472     /// if None::<()>.is_none() {}
473     /// if Some(42).is_some() {}
474     /// if Poll::Pending::<()>.is_pending() {}
475     /// if Poll::Ready(42).is_ready() {}
476     /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
477     /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
478     /// Ok::<i32, i32>(42).is_ok();
479     /// ```
480     #[clippy::version = "1.31.0"]
481     pub REDUNDANT_PATTERN_MATCHING,
482     style,
483     "use the proper utility function avoiding an `if let`"
484 }
485
486 declare_clippy_lint! {
487     /// ### What it does
488     /// Checks for `match`  or `if let` expressions producing a
489     /// `bool` that could be written using `matches!`
490     ///
491     /// ### Why is this bad?
492     /// Readability and needless complexity.
493     ///
494     /// ### Known problems
495     /// This lint falsely triggers, if there are arms with
496     /// `cfg` attributes that remove an arm evaluating to `false`.
497     ///
498     /// ### Example
499     /// ```rust
500     /// let x = Some(5);
501     ///
502     /// // Bad
503     /// let a = match x {
504     ///     Some(0) => true,
505     ///     _ => false,
506     /// };
507     ///
508     /// let a = if let Some(0) = x {
509     ///     true
510     /// } else {
511     ///     false
512     /// };
513     ///
514     /// // Good
515     /// let a = matches!(x, Some(0));
516     /// ```
517     #[clippy::version = "1.47.0"]
518     pub MATCH_LIKE_MATCHES_MACRO,
519     style,
520     "a match that could be written with the matches! macro"
521 }
522
523 declare_clippy_lint! {
524     /// ### What it does
525     /// Checks for `match` with identical arm bodies.
526     ///
527     /// ### Why is this bad?
528     /// This is probably a copy & paste error. If arm bodies
529     /// are the same on purpose, you can factor them
530     /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
531     ///
532     /// ### Known problems
533     /// False positive possible with order dependent `match`
534     /// (see issue
535     /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
536     ///
537     /// ### Example
538     /// ```rust,ignore
539     /// match foo {
540     ///     Bar => bar(),
541     ///     Quz => quz(),
542     ///     Baz => bar(), // <= oops
543     /// }
544     /// ```
545     ///
546     /// This should probably be
547     /// ```rust,ignore
548     /// match foo {
549     ///     Bar => bar(),
550     ///     Quz => quz(),
551     ///     Baz => baz(), // <= fixed
552     /// }
553     /// ```
554     ///
555     /// or if the original code was not a typo:
556     /// ```rust,ignore
557     /// match foo {
558     ///     Bar | Baz => bar(), // <= shows the intent better
559     ///     Quz => quz(),
560     /// }
561     /// ```
562     #[clippy::version = "pre 1.29.0"]
563     pub MATCH_SAME_ARMS,
564     pedantic,
565     "`match` with identical arm bodies"
566 }
567
568 #[derive(Default)]
569 pub struct Matches {
570     msrv: Option<RustcVersion>,
571     infallible_destructuring_match_linted: bool,
572 }
573
574 impl Matches {
575     #[must_use]
576     pub fn new(msrv: Option<RustcVersion>) -> Self {
577         Self {
578             msrv,
579             ..Matches::default()
580         }
581     }
582 }
583
584 impl_lint_pass!(Matches => [
585     SINGLE_MATCH,
586     MATCH_REF_PATS,
587     MATCH_BOOL,
588     SINGLE_MATCH_ELSE,
589     MATCH_OVERLAPPING_ARM,
590     MATCH_WILD_ERR_ARM,
591     MATCH_AS_REF,
592     WILDCARD_ENUM_MATCH_ARM,
593     MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
594     WILDCARD_IN_OR_PATTERNS,
595     MATCH_SINGLE_BINDING,
596     INFALLIBLE_DESTRUCTURING_MATCH,
597     REST_PAT_IN_FULLY_BOUND_STRUCTS,
598     REDUNDANT_PATTERN_MATCHING,
599     MATCH_LIKE_MATCHES_MACRO,
600     MATCH_SAME_ARMS,
601 ]);
602
603 impl<'tcx> LateLintPass<'tcx> for Matches {
604     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
605         if expr.span.from_expansion() {
606             return;
607         }
608
609         redundant_pattern_match::check(cx, expr);
610
611         if meets_msrv(self.msrv.as_ref(), &msrvs::MATCHES_MACRO) {
612             if !match_like_matches::check(cx, expr) {
613                 match_same_arms::check(cx, expr);
614             }
615         } else {
616             match_same_arms::check(cx, expr);
617         }
618
619         if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
620             single_match::check(cx, ex, arms, expr);
621             match_bool::check(cx, ex, arms, expr);
622             overlapping_arms::check(cx, ex, arms);
623             match_wild_err_arm::check(cx, ex, arms);
624             match_wild_enum::check(cx, ex, arms);
625             match_as_ref::check(cx, ex, arms, expr);
626             check_wild_in_or_pats(cx, arms);
627
628             if self.infallible_destructuring_match_linted {
629                 self.infallible_destructuring_match_linted = false;
630             } else {
631                 match_single_binding::check(cx, ex, arms, expr);
632             }
633         }
634         if let ExprKind::Match(ex, arms, _) = expr.kind {
635             match_ref_pats::check(cx, ex, arms.iter().map(|el| el.pat), expr);
636         }
637     }
638
639     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
640         if_chain! {
641             if !local.span.from_expansion();
642             if let Some(expr) = local.init;
643             if let ExprKind::Match(target, arms, MatchSource::Normal) = expr.kind;
644             if arms.len() == 1 && arms[0].guard.is_none();
645             if let PatKind::TupleStruct(
646                 QPath::Resolved(None, variant_name), args, _) = arms[0].pat.kind;
647             if args.len() == 1;
648             if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind;
649             let body = peel_blocks(arms[0].body);
650             if path_to_local_id(body, arg);
651
652             then {
653                 let mut applicability = Applicability::MachineApplicable;
654                 self.infallible_destructuring_match_linted = true;
655                 span_lint_and_sugg(
656                     cx,
657                     INFALLIBLE_DESTRUCTURING_MATCH,
658                     local.span,
659                     "you seem to be trying to use `match` to destructure a single infallible pattern. \
660                     Consider using `let`",
661                     "try this",
662                     format!(
663                         "let {}({}) = {};",
664                         snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
665                         snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
666                         snippet_with_applicability(cx, target.span, "..", &mut applicability),
667                     ),
668                     applicability,
669                 );
670             }
671         }
672     }
673
674     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
675         if_chain! {
676             if !pat.span.from_expansion();
677             if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind;
678             if let Some(def_id) = path.res.opt_def_id();
679             let ty = cx.tcx.type_of(def_id);
680             if let ty::Adt(def, _) = ty.kind();
681             if def.is_struct() || def.is_union();
682             if fields.len() == def.non_enum_variant().fields.len();
683
684             then {
685                 span_lint_and_help(
686                     cx,
687                     REST_PAT_IN_FULLY_BOUND_STRUCTS,
688                     pat.span,
689                     "unnecessary use of `..` pattern in struct binding. All fields were already bound",
690                     None,
691                     "consider removing `..` from this binding",
692                 );
693             }
694         }
695     }
696
697     extract_msrv_attr!(LateContext);
698 }
699
700 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
701     for arm in arms {
702         if let PatKind::Or(fields) = arm.pat.kind {
703             // look for multiple fields in this arm that contains at least one Wild pattern
704             if fields.len() > 1 && fields.iter().any(is_wild) {
705                 span_lint_and_help(
706                     cx,
707                     WILDCARD_IN_OR_PATTERNS,
708                     arm.pat.span,
709                     "wildcard pattern covers any other pattern as it will match anyway",
710                     None,
711                     "consider handling `_` separately",
712                 );
713             }
714         }
715     }
716 }