]>
Commit | Line | Data |
---|---|---|
f20569fa XL |
1 | use crate::consts::{constant, miri_to_const, Constant}; |
2 | use crate::utils::sugg::Sugg; | |
3 | use crate::utils::visitors::LocalUsedVisitor; | |
4 | use crate::utils::{ | |
5 | expr_block, get_parent_expr, implements_trait, in_macro, indent_of, is_allowed, is_expn_of, is_refutable, | |
6 | is_type_diagnostic_item, is_wild, match_qpath, match_type, meets_msrv, multispan_sugg, path_to_local, | |
7 | path_to_local_id, peel_hir_pat_refs, peel_mid_ty_refs, peel_n_hir_expr_refs, remove_blocks, snippet, snippet_block, | |
8 | snippet_opt, snippet_with_applicability, span_lint_and_help, span_lint_and_note, span_lint_and_sugg, | |
9 | span_lint_and_then, strip_pat_refs, | |
10 | }; | |
11 | use crate::utils::{paths, search_same, SpanlessEq, SpanlessHash}; | |
12 | use if_chain::if_chain; | |
13 | use rustc_ast::ast::LitKind; | |
14 | use rustc_data_structures::fx::{FxHashMap, FxHashSet}; | |
15 | use rustc_errors::Applicability; | |
16 | use rustc_hir::def::CtorKind; | |
17 | use rustc_hir::{ | |
18 | Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, HirId, Local, MatchSource, Mutability, Node, Pat, | |
19 | PatKind, QPath, RangeEnd, | |
20 | }; | |
21 | use rustc_lint::{LateContext, LateLintPass, LintContext}; | |
22 | use rustc_middle::lint::in_external_macro; | |
23 | use rustc_middle::ty::{self, Ty, TyS}; | |
24 | use rustc_semver::RustcVersion; | |
25 | use rustc_session::{declare_tool_lint, impl_lint_pass}; | |
26 | use rustc_span::source_map::{Span, Spanned}; | |
27 | use rustc_span::sym; | |
28 | use std::cmp::Ordering; | |
29 | use std::collections::hash_map::Entry; | |
30 | use std::ops::Bound; | |
31 | ||
32 | declare_clippy_lint! { | |
33 | /// **What it does:** Checks for matches with a single arm where an `if let` | |
34 | /// will usually suffice. | |
35 | /// | |
36 | /// **Why is this bad?** Just readability – `if let` nests less than a `match`. | |
37 | /// | |
38 | /// **Known problems:** None. | |
39 | /// | |
40 | /// **Example:** | |
41 | /// ```rust | |
42 | /// # fn bar(stool: &str) {} | |
43 | /// # let x = Some("abc"); | |
44 | /// // Bad | |
45 | /// match x { | |
46 | /// Some(ref foo) => bar(foo), | |
47 | /// _ => (), | |
48 | /// } | |
49 | /// | |
50 | /// // Good | |
51 | /// if let Some(ref foo) = x { | |
52 | /// bar(foo); | |
53 | /// } | |
54 | /// ``` | |
55 | pub SINGLE_MATCH, | |
56 | style, | |
57 | "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`" | |
58 | } | |
59 | ||
60 | declare_clippy_lint! { | |
61 | /// **What it does:** Checks for matches with two arms where an `if let else` will | |
62 | /// usually suffice. | |
63 | /// | |
64 | /// **Why is this bad?** Just readability – `if let` nests less than a `match`. | |
65 | /// | |
66 | /// **Known problems:** Personal style preferences may differ. | |
67 | /// | |
68 | /// **Example:** | |
69 | /// | |
70 | /// Using `match`: | |
71 | /// | |
72 | /// ```rust | |
73 | /// # fn bar(foo: &usize) {} | |
74 | /// # let other_ref: usize = 1; | |
75 | /// # let x: Option<&usize> = Some(&1); | |
76 | /// match x { | |
77 | /// Some(ref foo) => bar(foo), | |
78 | /// _ => bar(&other_ref), | |
79 | /// } | |
80 | /// ``` | |
81 | /// | |
82 | /// Using `if let` with `else`: | |
83 | /// | |
84 | /// ```rust | |
85 | /// # fn bar(foo: &usize) {} | |
86 | /// # let other_ref: usize = 1; | |
87 | /// # let x: Option<&usize> = Some(&1); | |
88 | /// if let Some(ref foo) = x { | |
89 | /// bar(foo); | |
90 | /// } else { | |
91 | /// bar(&other_ref); | |
92 | /// } | |
93 | /// ``` | |
94 | pub SINGLE_MATCH_ELSE, | |
95 | pedantic, | |
96 | "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern" | |
97 | } | |
98 | ||
99 | declare_clippy_lint! { | |
100 | /// **What it does:** Checks for matches where all arms match a reference, | |
101 | /// suggesting to remove the reference and deref the matched expression | |
102 | /// instead. It also checks for `if let &foo = bar` blocks. | |
103 | /// | |
104 | /// **Why is this bad?** It just makes the code less readable. That reference | |
105 | /// destructuring adds nothing to the code. | |
106 | /// | |
107 | /// **Known problems:** None. | |
108 | /// | |
109 | /// **Example:** | |
110 | /// ```rust,ignore | |
111 | /// // Bad | |
112 | /// match x { | |
113 | /// &A(ref y) => foo(y), | |
114 | /// &B => bar(), | |
115 | /// _ => frob(&x), | |
116 | /// } | |
117 | /// | |
118 | /// // Good | |
119 | /// match *x { | |
120 | /// A(ref y) => foo(y), | |
121 | /// B => bar(), | |
122 | /// _ => frob(x), | |
123 | /// } | |
124 | /// ``` | |
125 | pub MATCH_REF_PATS, | |
126 | style, | |
127 | "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression" | |
128 | } | |
129 | ||
130 | declare_clippy_lint! { | |
131 | /// **What it does:** Checks for matches where match expression is a `bool`. It | |
132 | /// suggests to replace the expression with an `if...else` block. | |
133 | /// | |
134 | /// **Why is this bad?** It makes the code less readable. | |
135 | /// | |
136 | /// **Known problems:** None. | |
137 | /// | |
138 | /// **Example:** | |
139 | /// ```rust | |
140 | /// # fn foo() {} | |
141 | /// # fn bar() {} | |
142 | /// let condition: bool = true; | |
143 | /// match condition { | |
144 | /// true => foo(), | |
145 | /// false => bar(), | |
146 | /// } | |
147 | /// ``` | |
148 | /// Use if/else instead: | |
149 | /// ```rust | |
150 | /// # fn foo() {} | |
151 | /// # fn bar() {} | |
152 | /// let condition: bool = true; | |
153 | /// if condition { | |
154 | /// foo(); | |
155 | /// } else { | |
156 | /// bar(); | |
157 | /// } | |
158 | /// ``` | |
159 | pub MATCH_BOOL, | |
160 | pedantic, | |
161 | "a `match` on a boolean expression instead of an `if..else` block" | |
162 | } | |
163 | ||
164 | declare_clippy_lint! { | |
165 | /// **What it does:** Checks for overlapping match arms. | |
166 | /// | |
167 | /// **Why is this bad?** It is likely to be an error and if not, makes the code | |
168 | /// less obvious. | |
169 | /// | |
170 | /// **Known problems:** None. | |
171 | /// | |
172 | /// **Example:** | |
173 | /// ```rust | |
174 | /// let x = 5; | |
175 | /// match x { | |
176 | /// 1...10 => println!("1 ... 10"), | |
177 | /// 5...15 => println!("5 ... 15"), | |
178 | /// _ => (), | |
179 | /// } | |
180 | /// ``` | |
181 | pub MATCH_OVERLAPPING_ARM, | |
182 | style, | |
183 | "a `match` with overlapping arms" | |
184 | } | |
185 | ||
186 | declare_clippy_lint! { | |
187 | /// **What it does:** Checks for arm which matches all errors with `Err(_)` | |
188 | /// and take drastic actions like `panic!`. | |
189 | /// | |
190 | /// **Why is this bad?** It is generally a bad practice, similar to | |
191 | /// catching all exceptions in java with `catch(Exception)` | |
192 | /// | |
193 | /// **Known problems:** None. | |
194 | /// | |
195 | /// **Example:** | |
196 | /// ```rust | |
197 | /// let x: Result<i32, &str> = Ok(3); | |
198 | /// match x { | |
199 | /// Ok(_) => println!("ok"), | |
200 | /// Err(_) => panic!("err"), | |
201 | /// } | |
202 | /// ``` | |
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:** Checks for match which is used to add a reference to an | |
210 | /// `Option` value. | |
211 | /// | |
212 | /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter. | |
213 | /// | |
214 | /// **Known problems:** None. | |
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 | pub MATCH_AS_REF, | |
230 | complexity, | |
231 | "a `match` on an Option value instead of using `as_ref()` or `as_mut`" | |
232 | } | |
233 | ||
234 | declare_clippy_lint! { | |
235 | /// **What it does:** Checks for wildcard enum matches using `_`. | |
236 | /// | |
237 | /// **Why is this bad?** New enum variants added by library updates can be missed. | |
238 | /// | |
239 | /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some | |
240 | /// variants, and also may not use correct path to enum if it's not present in the current scope. | |
241 | /// | |
242 | /// **Example:** | |
243 | /// ```rust | |
244 | /// # enum Foo { A(usize), B(usize) } | |
245 | /// # let x = Foo::B(1); | |
246 | /// // Bad | |
247 | /// match x { | |
248 | /// Foo::A(_) => {}, | |
249 | /// _ => {}, | |
250 | /// } | |
251 | /// | |
252 | /// // Good | |
253 | /// match x { | |
254 | /// Foo::A(_) => {}, | |
255 | /// Foo::B(_) => {}, | |
256 | /// } | |
257 | /// ``` | |
258 | pub WILDCARD_ENUM_MATCH_ARM, | |
259 | restriction, | |
260 | "a wildcard enum match arm using `_`" | |
261 | } | |
262 | ||
263 | declare_clippy_lint! { | |
264 | /// **What it does:** Checks for wildcard enum matches for a single variant. | |
265 | /// | |
266 | /// **Why is this bad?** New enum variants added by library updates can be missed. | |
267 | /// | |
268 | /// **Known problems:** Suggested replacements may not use correct path to enum | |
269 | /// if it's not present in the current scope. | |
270 | /// | |
271 | /// **Example:** | |
272 | /// | |
273 | /// ```rust | |
274 | /// # enum Foo { A, B, C } | |
275 | /// # let x = Foo::B; | |
276 | /// // Bad | |
277 | /// match x { | |
278 | /// Foo::A => {}, | |
279 | /// Foo::B => {}, | |
280 | /// _ => {}, | |
281 | /// } | |
282 | /// | |
283 | /// // Good | |
284 | /// match x { | |
285 | /// Foo::A => {}, | |
286 | /// Foo::B => {}, | |
287 | /// Foo::C => {}, | |
288 | /// } | |
289 | /// ``` | |
290 | pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS, | |
291 | pedantic, | |
292 | "a wildcard enum match for a single variant" | |
293 | } | |
294 | ||
295 | declare_clippy_lint! { | |
296 | /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm. | |
297 | /// | |
298 | /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway. | |
299 | /// It makes the code less readable, especially to spot wildcard pattern use in match arm. | |
300 | /// | |
301 | /// **Known problems:** None. | |
302 | /// | |
303 | /// **Example:** | |
304 | /// ```rust | |
305 | /// // Bad | |
306 | /// match "foo" { | |
307 | /// "a" => {}, | |
308 | /// "bar" | _ => {}, | |
309 | /// } | |
310 | /// | |
311 | /// // Good | |
312 | /// match "foo" { | |
313 | /// "a" => {}, | |
314 | /// _ => {}, | |
315 | /// } | |
316 | /// ``` | |
317 | pub WILDCARD_IN_OR_PATTERNS, | |
318 | complexity, | |
319 | "a wildcard pattern used with others patterns in same match arm" | |
320 | } | |
321 | ||
322 | declare_clippy_lint! { | |
323 | /// **What it does:** Checks for matches being used to destructure a single-variant enum | |
324 | /// or tuple struct where a `let` will suffice. | |
325 | /// | |
326 | /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does. | |
327 | /// | |
328 | /// **Known problems:** None. | |
329 | /// | |
330 | /// **Example:** | |
331 | /// ```rust | |
332 | /// enum Wrapper { | |
333 | /// Data(i32), | |
334 | /// } | |
335 | /// | |
336 | /// let wrapper = Wrapper::Data(42); | |
337 | /// | |
338 | /// let data = match wrapper { | |
339 | /// Wrapper::Data(i) => i, | |
340 | /// }; | |
341 | /// ``` | |
342 | /// | |
343 | /// The correct use would be: | |
344 | /// ```rust | |
345 | /// enum Wrapper { | |
346 | /// Data(i32), | |
347 | /// } | |
348 | /// | |
349 | /// let wrapper = Wrapper::Data(42); | |
350 | /// let Wrapper::Data(data) = wrapper; | |
351 | /// ``` | |
352 | pub INFALLIBLE_DESTRUCTURING_MATCH, | |
353 | style, | |
354 | "a `match` statement with a single infallible arm instead of a `let`" | |
355 | } | |
356 | ||
357 | declare_clippy_lint! { | |
358 | /// **What it does:** Checks for useless match that binds to only one value. | |
359 | /// | |
360 | /// **Why is this bad?** Readability and needless complexity. | |
361 | /// | |
362 | /// **Known problems:** Suggested replacements may be incorrect when `match` | |
363 | /// is actually binding temporary value, bringing a 'dropped while borrowed' error. | |
364 | /// | |
365 | /// **Example:** | |
366 | /// ```rust | |
367 | /// # let a = 1; | |
368 | /// # let b = 2; | |
369 | /// | |
370 | /// // Bad | |
371 | /// match (a, b) { | |
372 | /// (c, d) => { | |
373 | /// // useless match | |
374 | /// } | |
375 | /// } | |
376 | /// | |
377 | /// // Good | |
378 | /// let (c, d) = (a, b); | |
379 | /// ``` | |
380 | pub MATCH_SINGLE_BINDING, | |
381 | complexity, | |
382 | "a match with a single binding instead of using `let` statement" | |
383 | } | |
384 | ||
385 | declare_clippy_lint! { | |
386 | /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched. | |
387 | /// | |
388 | /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after | |
389 | /// matching all enum variants explicitly. | |
390 | /// | |
391 | /// **Known problems:** None. | |
392 | /// | |
393 | /// **Example:** | |
394 | /// ```rust | |
395 | /// # struct A { a: i32 } | |
396 | /// let a = A { a: 5 }; | |
397 | /// | |
398 | /// // Bad | |
399 | /// match a { | |
400 | /// A { a: 5, .. } => {}, | |
401 | /// _ => {}, | |
402 | /// } | |
403 | /// | |
404 | /// // Good | |
405 | /// match a { | |
406 | /// A { a: 5 } => {}, | |
407 | /// _ => {}, | |
408 | /// } | |
409 | /// ``` | |
410 | pub REST_PAT_IN_FULLY_BOUND_STRUCTS, | |
411 | restriction, | |
412 | "a match on a struct that binds all fields but still uses the wildcard pattern" | |
413 | } | |
414 | ||
415 | declare_clippy_lint! { | |
416 | /// **What it does:** Lint for redundant pattern matching over `Result`, `Option`, | |
417 | /// `std::task::Poll` or `std::net::IpAddr` | |
418 | /// | |
419 | /// **Why is this bad?** It's more concise and clear to just use the proper | |
420 | /// utility function | |
421 | /// | |
422 | /// **Known problems:** None. | |
423 | /// | |
424 | /// **Example:** | |
425 | /// | |
426 | /// ```rust | |
427 | /// # use std::task::Poll; | |
428 | /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; | |
429 | /// if let Ok(_) = Ok::<i32, i32>(42) {} | |
430 | /// if let Err(_) = Err::<i32, i32>(42) {} | |
431 | /// if let None = None::<()> {} | |
432 | /// if let Some(_) = Some(42) {} | |
433 | /// if let Poll::Pending = Poll::Pending::<()> {} | |
434 | /// if let Poll::Ready(_) = Poll::Ready(42) {} | |
435 | /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {} | |
436 | /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {} | |
437 | /// match Ok::<i32, i32>(42) { | |
438 | /// Ok(_) => true, | |
439 | /// Err(_) => false, | |
440 | /// }; | |
441 | /// ``` | |
442 | /// | |
443 | /// The more idiomatic use would be: | |
444 | /// | |
445 | /// ```rust | |
446 | /// # use std::task::Poll; | |
447 | /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; | |
448 | /// if Ok::<i32, i32>(42).is_ok() {} | |
449 | /// if Err::<i32, i32>(42).is_err() {} | |
450 | /// if None::<()>.is_none() {} | |
451 | /// if Some(42).is_some() {} | |
452 | /// if Poll::Pending::<()>.is_pending() {} | |
453 | /// if Poll::Ready(42).is_ready() {} | |
454 | /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {} | |
455 | /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {} | |
456 | /// Ok::<i32, i32>(42).is_ok(); | |
457 | /// ``` | |
458 | pub REDUNDANT_PATTERN_MATCHING, | |
459 | style, | |
460 | "use the proper utility function avoiding an `if let`" | |
461 | } | |
462 | ||
463 | declare_clippy_lint! { | |
464 | /// **What it does:** Checks for `match` or `if let` expressions producing a | |
465 | /// `bool` that could be written using `matches!` | |
466 | /// | |
467 | /// **Why is this bad?** Readability and needless complexity. | |
468 | /// | |
469 | /// **Known problems:** This lint falsely triggers, if there are arms with | |
470 | /// `cfg` attributes that remove an arm evaluating to `false`. | |
471 | /// | |
472 | /// **Example:** | |
473 | /// ```rust | |
474 | /// let x = Some(5); | |
475 | /// | |
476 | /// // Bad | |
477 | /// let a = match x { | |
478 | /// Some(0) => true, | |
479 | /// _ => false, | |
480 | /// }; | |
481 | /// | |
482 | /// let a = if let Some(0) = x { | |
483 | /// true | |
484 | /// } else { | |
485 | /// false | |
486 | /// }; | |
487 | /// | |
488 | /// // Good | |
489 | /// let a = matches!(x, Some(0)); | |
490 | /// ``` | |
491 | pub MATCH_LIKE_MATCHES_MACRO, | |
492 | style, | |
493 | "a match that could be written with the matches! macro" | |
494 | } | |
495 | ||
496 | declare_clippy_lint! { | |
497 | /// **What it does:** Checks for `match` with identical arm bodies. | |
498 | /// | |
499 | /// **Why is this bad?** This is probably a copy & paste error. If arm bodies | |
500 | /// are the same on purpose, you can factor them | |
501 | /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns). | |
502 | /// | |
503 | /// **Known problems:** False positive possible with order dependent `match` | |
504 | /// (see issue | |
505 | /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)). | |
506 | /// | |
507 | /// **Example:** | |
508 | /// ```rust,ignore | |
509 | /// match foo { | |
510 | /// Bar => bar(), | |
511 | /// Quz => quz(), | |
512 | /// Baz => bar(), // <= oops | |
513 | /// } | |
514 | /// ``` | |
515 | /// | |
516 | /// This should probably be | |
517 | /// ```rust,ignore | |
518 | /// match foo { | |
519 | /// Bar => bar(), | |
520 | /// Quz => quz(), | |
521 | /// Baz => baz(), // <= fixed | |
522 | /// } | |
523 | /// ``` | |
524 | /// | |
525 | /// or if the original code was not a typo: | |
526 | /// ```rust,ignore | |
527 | /// match foo { | |
528 | /// Bar | Baz => bar(), // <= shows the intent better | |
529 | /// Quz => quz(), | |
530 | /// } | |
531 | /// ``` | |
532 | pub MATCH_SAME_ARMS, | |
533 | pedantic, | |
534 | "`match` with identical arm bodies" | |
535 | } | |
536 | ||
537 | #[derive(Default)] | |
538 | pub struct Matches { | |
539 | msrv: Option<RustcVersion>, | |
540 | infallible_destructuring_match_linted: bool, | |
541 | } | |
542 | ||
543 | impl Matches { | |
544 | #[must_use] | |
545 | pub fn new(msrv: Option<RustcVersion>) -> Self { | |
546 | Self { | |
547 | msrv, | |
548 | ..Matches::default() | |
549 | } | |
550 | } | |
551 | } | |
552 | ||
553 | impl_lint_pass!(Matches => [ | |
554 | SINGLE_MATCH, | |
555 | MATCH_REF_PATS, | |
556 | MATCH_BOOL, | |
557 | SINGLE_MATCH_ELSE, | |
558 | MATCH_OVERLAPPING_ARM, | |
559 | MATCH_WILD_ERR_ARM, | |
560 | MATCH_AS_REF, | |
561 | WILDCARD_ENUM_MATCH_ARM, | |
562 | MATCH_WILDCARD_FOR_SINGLE_VARIANTS, | |
563 | WILDCARD_IN_OR_PATTERNS, | |
564 | MATCH_SINGLE_BINDING, | |
565 | INFALLIBLE_DESTRUCTURING_MATCH, | |
566 | REST_PAT_IN_FULLY_BOUND_STRUCTS, | |
567 | REDUNDANT_PATTERN_MATCHING, | |
568 | MATCH_LIKE_MATCHES_MACRO, | |
569 | MATCH_SAME_ARMS, | |
570 | ]); | |
571 | ||
572 | const MATCH_LIKE_MATCHES_MACRO_MSRV: RustcVersion = RustcVersion::new(1, 42, 0); | |
573 | ||
574 | impl<'tcx> LateLintPass<'tcx> for Matches { | |
575 | fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { | |
576 | if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) { | |
577 | return; | |
578 | } | |
579 | ||
580 | redundant_pattern_match::check(cx, expr); | |
581 | ||
582 | if meets_msrv(self.msrv.as_ref(), &MATCH_LIKE_MATCHES_MACRO_MSRV) { | |
583 | if !check_match_like_matches(cx, expr) { | |
584 | lint_match_arms(cx, expr); | |
585 | } | |
586 | } else { | |
587 | lint_match_arms(cx, expr); | |
588 | } | |
589 | ||
590 | if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind { | |
591 | check_single_match(cx, ex, arms, expr); | |
592 | check_match_bool(cx, ex, arms, expr); | |
593 | check_overlapping_arms(cx, ex, arms); | |
594 | check_wild_err_arm(cx, ex, arms); | |
595 | check_wild_enum_match(cx, ex, arms); | |
596 | check_match_as_ref(cx, ex, arms, expr); | |
597 | check_wild_in_or_pats(cx, arms); | |
598 | ||
599 | if self.infallible_destructuring_match_linted { | |
600 | self.infallible_destructuring_match_linted = false; | |
601 | } else { | |
602 | check_match_single_binding(cx, ex, arms, expr); | |
603 | } | |
604 | } | |
605 | if let ExprKind::Match(ref ex, ref arms, _) = expr.kind { | |
606 | check_match_ref_pats(cx, ex, arms, expr); | |
607 | } | |
608 | } | |
609 | ||
610 | fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) { | |
611 | if_chain! { | |
612 | if !in_external_macro(cx.sess(), local.span); | |
613 | if !in_macro(local.span); | |
614 | if let Some(ref expr) = local.init; | |
615 | if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind; | |
616 | if arms.len() == 1 && arms[0].guard.is_none(); | |
617 | if let PatKind::TupleStruct( | |
618 | QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pat.kind; | |
619 | if args.len() == 1; | |
620 | if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind; | |
621 | let body = remove_blocks(&arms[0].body); | |
622 | if path_to_local_id(body, arg); | |
623 | ||
624 | then { | |
625 | let mut applicability = Applicability::MachineApplicable; | |
626 | self.infallible_destructuring_match_linted = true; | |
627 | span_lint_and_sugg( | |
628 | cx, | |
629 | INFALLIBLE_DESTRUCTURING_MATCH, | |
630 | local.span, | |
631 | "you seem to be trying to use `match` to destructure a single infallible pattern. \ | |
632 | Consider using `let`", | |
633 | "try this", | |
634 | format!( | |
635 | "let {}({}) = {};", | |
636 | snippet_with_applicability(cx, variant_name.span, "..", &mut applicability), | |
637 | snippet_with_applicability(cx, local.pat.span, "..", &mut applicability), | |
638 | snippet_with_applicability(cx, target.span, "..", &mut applicability), | |
639 | ), | |
640 | applicability, | |
641 | ); | |
642 | } | |
643 | } | |
644 | } | |
645 | ||
646 | fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) { | |
647 | if_chain! { | |
648 | if !in_external_macro(cx.sess(), pat.span); | |
649 | if !in_macro(pat.span); | |
650 | if let PatKind::Struct(QPath::Resolved(_, ref path), fields, true) = pat.kind; | |
651 | if let Some(def_id) = path.res.opt_def_id(); | |
652 | let ty = cx.tcx.type_of(def_id); | |
653 | if let ty::Adt(def, _) = ty.kind(); | |
654 | if def.is_struct() || def.is_union(); | |
655 | if fields.len() == def.non_enum_variant().fields.len(); | |
656 | ||
657 | then { | |
658 | span_lint_and_help( | |
659 | cx, | |
660 | REST_PAT_IN_FULLY_BOUND_STRUCTS, | |
661 | pat.span, | |
662 | "unnecessary use of `..` pattern in struct binding. All fields were already bound", | |
663 | None, | |
664 | "consider removing `..` from this binding", | |
665 | ); | |
666 | } | |
667 | } | |
668 | } | |
669 | ||
670 | extract_msrv_attr!(LateContext); | |
671 | } | |
672 | ||
673 | #[rustfmt::skip] | |
674 | fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) { | |
675 | if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() { | |
676 | if in_macro(expr.span) { | |
677 | // Don't lint match expressions present in | |
678 | // macro_rules! block | |
679 | return; | |
680 | } | |
681 | if let PatKind::Or(..) = arms[0].pat.kind { | |
682 | // don't lint for or patterns for now, this makes | |
683 | // the lint noisy in unnecessary situations | |
684 | return; | |
685 | } | |
686 | let els = arms[1].body; | |
687 | let els = if is_unit_expr(remove_blocks(els)) { | |
688 | None | |
689 | } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind { | |
690 | if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() { | |
691 | // single statement/expr "else" block, don't lint | |
692 | return; | |
693 | } | |
694 | // block with 2+ statements or 1 expr and 1+ statement | |
695 | Some(els) | |
696 | } else { | |
697 | // not a block, don't lint | |
698 | return; | |
699 | }; | |
700 | ||
701 | let ty = cx.typeck_results().expr_ty(ex); | |
702 | if *ty.kind() != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) { | |
703 | check_single_match_single_pattern(cx, ex, arms, expr, els); | |
704 | check_single_match_opt_like(cx, ex, arms, expr, ty, els); | |
705 | } | |
706 | } | |
707 | } | |
708 | ||
709 | fn check_single_match_single_pattern( | |
710 | cx: &LateContext<'_>, | |
711 | ex: &Expr<'_>, | |
712 | arms: &[Arm<'_>], | |
713 | expr: &Expr<'_>, | |
714 | els: Option<&Expr<'_>>, | |
715 | ) { | |
716 | if is_wild(&arms[1].pat) { | |
717 | report_single_match_single_pattern(cx, ex, arms, expr, els); | |
718 | } | |
719 | } | |
720 | ||
721 | fn report_single_match_single_pattern( | |
722 | cx: &LateContext<'_>, | |
723 | ex: &Expr<'_>, | |
724 | arms: &[Arm<'_>], | |
725 | expr: &Expr<'_>, | |
726 | els: Option<&Expr<'_>>, | |
727 | ) { | |
728 | let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH }; | |
729 | let els_str = els.map_or(String::new(), |els| { | |
730 | format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span))) | |
731 | }); | |
732 | ||
733 | let (msg, sugg) = if_chain! { | |
734 | let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat); | |
735 | if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind; | |
736 | let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex)); | |
737 | if let Some(trait_id) = cx.tcx.lang_items().structural_peq_trait(); | |
738 | if ty.is_integral() || ty.is_char() || ty.is_str() || implements_trait(cx, ty, trait_id, &[]); | |
739 | then { | |
740 | // scrutinee derives PartialEq and the pattern is a constant. | |
741 | let pat_ref_count = match pat.kind { | |
742 | // string literals are already a reference. | |
743 | PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1, | |
744 | _ => pat_ref_count, | |
745 | }; | |
746 | // References are only implicitly added to the pattern, so no overflow here. | |
747 | // e.g. will work: match &Some(_) { Some(_) => () } | |
748 | // will not: match Some(_) { &Some(_) => () } | |
749 | let ref_count_diff = ty_ref_count - pat_ref_count; | |
750 | ||
751 | // Try to remove address of expressions first. | |
752 | let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff); | |
753 | let ref_count_diff = ref_count_diff - removed; | |
754 | ||
755 | let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`"; | |
756 | let sugg = format!( | |
757 | "if {} == {}{} {}{}", | |
758 | snippet(cx, ex.span, ".."), | |
759 | // PartialEq for different reference counts may not exist. | |
760 | "&".repeat(ref_count_diff), | |
761 | snippet(cx, arms[0].pat.span, ".."), | |
762 | expr_block(cx, &arms[0].body, None, "..", Some(expr.span)), | |
763 | els_str, | |
764 | ); | |
765 | (msg, sugg) | |
766 | } else { | |
767 | let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`"; | |
768 | let sugg = format!( | |
769 | "if let {} = {} {}{}", | |
770 | snippet(cx, arms[0].pat.span, ".."), | |
771 | snippet(cx, ex.span, ".."), | |
772 | expr_block(cx, &arms[0].body, None, "..", Some(expr.span)), | |
773 | els_str, | |
774 | ); | |
775 | (msg, sugg) | |
776 | } | |
777 | }; | |
778 | ||
779 | span_lint_and_sugg( | |
780 | cx, | |
781 | lint, | |
782 | expr.span, | |
783 | msg, | |
784 | "try this", | |
785 | sugg, | |
786 | Applicability::HasPlaceholders, | |
787 | ); | |
788 | } | |
789 | ||
790 | fn check_single_match_opt_like( | |
791 | cx: &LateContext<'_>, | |
792 | ex: &Expr<'_>, | |
793 | arms: &[Arm<'_>], | |
794 | expr: &Expr<'_>, | |
795 | ty: Ty<'_>, | |
796 | els: Option<&Expr<'_>>, | |
797 | ) { | |
798 | // list of candidate `Enum`s we know will never get any more members | |
799 | let candidates = &[ | |
800 | (&paths::COW, "Borrowed"), | |
801 | (&paths::COW, "Cow::Borrowed"), | |
802 | (&paths::COW, "Cow::Owned"), | |
803 | (&paths::COW, "Owned"), | |
804 | (&paths::OPTION, "None"), | |
805 | (&paths::RESULT, "Err"), | |
806 | (&paths::RESULT, "Ok"), | |
807 | ]; | |
808 | ||
809 | let path = match arms[1].pat.kind { | |
810 | PatKind::TupleStruct(ref path, ref inner, _) => { | |
811 | // Contains any non wildcard patterns (e.g., `Err(err)`)? | |
812 | if !inner.iter().all(is_wild) { | |
813 | return; | |
814 | } | |
815 | rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)) | |
816 | }, | |
817 | PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(), | |
818 | PatKind::Path(ref path) => { | |
819 | rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)) | |
820 | }, | |
821 | _ => return, | |
822 | }; | |
823 | ||
824 | for &(ty_path, pat_path) in candidates { | |
825 | if path == *pat_path && match_type(cx, ty, ty_path) { | |
826 | report_single_match_single_pattern(cx, ex, arms, expr, els); | |
827 | } | |
828 | } | |
829 | } | |
830 | ||
831 | fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) { | |
832 | // Type of expression is `bool`. | |
833 | if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool { | |
834 | span_lint_and_then( | |
835 | cx, | |
836 | MATCH_BOOL, | |
837 | expr.span, | |
838 | "you seem to be trying to match on a boolean expression", | |
839 | move |diag| { | |
840 | if arms.len() == 2 { | |
841 | // no guards | |
842 | let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind { | |
843 | if let ExprKind::Lit(ref lit) = arm_bool.kind { | |
844 | match lit.node { | |
845 | LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)), | |
846 | LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)), | |
847 | _ => None, | |
848 | } | |
849 | } else { | |
850 | None | |
851 | } | |
852 | } else { | |
853 | None | |
854 | }; | |
855 | ||
856 | if let Some((true_expr, false_expr)) = exprs { | |
857 | let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) { | |
858 | (false, false) => Some(format!( | |
859 | "if {} {} else {}", | |
860 | snippet(cx, ex.span, "b"), | |
861 | expr_block(cx, true_expr, None, "..", Some(expr.span)), | |
862 | expr_block(cx, false_expr, None, "..", Some(expr.span)) | |
863 | )), | |
864 | (false, true) => Some(format!( | |
865 | "if {} {}", | |
866 | snippet(cx, ex.span, "b"), | |
867 | expr_block(cx, true_expr, None, "..", Some(expr.span)) | |
868 | )), | |
869 | (true, false) => { | |
870 | let test = Sugg::hir(cx, ex, ".."); | |
871 | Some(format!( | |
872 | "if {} {}", | |
873 | !test, | |
874 | expr_block(cx, false_expr, None, "..", Some(expr.span)) | |
875 | )) | |
876 | }, | |
877 | (true, true) => None, | |
878 | }; | |
879 | ||
880 | if let Some(sugg) = sugg { | |
881 | diag.span_suggestion( | |
882 | expr.span, | |
883 | "consider using an `if`/`else` expression", | |
884 | sugg, | |
885 | Applicability::HasPlaceholders, | |
886 | ); | |
887 | } | |
888 | } | |
889 | } | |
890 | }, | |
891 | ); | |
892 | } | |
893 | } | |
894 | ||
895 | fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) { | |
896 | if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() { | |
897 | let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex)); | |
898 | let type_ranges = type_ranges(&ranges); | |
899 | if !type_ranges.is_empty() { | |
900 | if let Some((start, end)) = overlapping(&type_ranges) { | |
901 | span_lint_and_note( | |
902 | cx, | |
903 | MATCH_OVERLAPPING_ARM, | |
904 | start.span, | |
905 | "some ranges overlap", | |
906 | Some(end.span), | |
907 | "overlaps with this", | |
908 | ); | |
909 | } | |
910 | } | |
911 | } | |
912 | } | |
913 | ||
914 | fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) { | |
915 | let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs(); | |
916 | if is_type_diagnostic_item(cx, ex_ty, sym::result_type) { | |
917 | for arm in arms { | |
918 | if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind { | |
919 | let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)); | |
920 | if path_str == "Err" { | |
921 | let mut matching_wild = inner.iter().any(is_wild); | |
922 | let mut ident_bind_name = String::from("_"); | |
923 | if !matching_wild { | |
924 | // Looking for unused bindings (i.e.: `_e`) | |
925 | inner.iter().for_each(|pat| { | |
926 | if let PatKind::Binding(_, id, ident, None) = pat.kind { | |
927 | if ident.as_str().starts_with('_') | |
928 | && !LocalUsedVisitor::new(cx, id).check_expr(arm.body) | |
929 | { | |
930 | ident_bind_name = (&ident.name.as_str()).to_string(); | |
931 | matching_wild = true; | |
932 | } | |
933 | } | |
934 | }); | |
935 | } | |
936 | if_chain! { | |
937 | if matching_wild; | |
938 | if let ExprKind::Block(ref block, _) = arm.body.kind; | |
939 | if is_panic_block(block); | |
940 | then { | |
941 | // `Err(_)` or `Err(_e)` arm with `panic!` found | |
942 | span_lint_and_note(cx, | |
943 | MATCH_WILD_ERR_ARM, | |
944 | arm.pat.span, | |
945 | &format!("`Err({})` matches all errors", &ident_bind_name), | |
946 | None, | |
947 | "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable", | |
948 | ); | |
949 | } | |
950 | } | |
951 | } | |
952 | } | |
953 | } | |
954 | } | |
955 | } | |
956 | ||
957 | fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) { | |
958 | let ty = cx.typeck_results().expr_ty(ex); | |
959 | if !ty.is_enum() { | |
960 | // If there isn't a nice closed set of possible values that can be conveniently enumerated, | |
961 | // don't complain about not enumerating the mall. | |
962 | return; | |
963 | } | |
964 | ||
965 | // First pass - check for violation, but don't do much book-keeping because this is hopefully | |
966 | // the uncommon case, and the book-keeping is slightly expensive. | |
967 | let mut wildcard_span = None; | |
968 | let mut wildcard_ident = None; | |
969 | for arm in arms { | |
970 | if let PatKind::Wild = arm.pat.kind { | |
971 | wildcard_span = Some(arm.pat.span); | |
972 | } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind { | |
973 | wildcard_span = Some(arm.pat.span); | |
974 | wildcard_ident = Some(ident); | |
975 | } | |
976 | } | |
977 | ||
978 | if let Some(wildcard_span) = wildcard_span { | |
979 | // Accumulate the variants which should be put in place of the wildcard because they're not | |
980 | // already covered. | |
981 | ||
982 | let mut missing_variants = vec![]; | |
983 | if let ty::Adt(def, _) = ty.kind() { | |
984 | for variant in &def.variants { | |
985 | missing_variants.push(variant); | |
986 | } | |
987 | } | |
988 | ||
989 | for arm in arms { | |
990 | if arm.guard.is_some() { | |
991 | // Guards mean that this case probably isn't exhaustively covered. Technically | |
992 | // this is incorrect, as we should really check whether each variant is exhaustively | |
993 | // covered by the set of guards that cover it, but that's really hard to do. | |
994 | continue; | |
995 | } | |
996 | if let PatKind::Path(ref path) = arm.pat.kind { | |
997 | if let QPath::Resolved(_, p) = path { | |
998 | missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id())); | |
999 | } | |
1000 | } else if let PatKind::TupleStruct(QPath::Resolved(_, p), ref patterns, ..) = arm.pat.kind { | |
1001 | // Some simple checks for exhaustive patterns. | |
1002 | // There is a room for improvements to detect more cases, | |
1003 | // but it can be more expensive to do so. | |
1004 | let is_pattern_exhaustive = | |
1005 | |pat: &&Pat<'_>| matches!(pat.kind, PatKind::Wild | PatKind::Binding(.., None)); | |
1006 | if patterns.iter().all(is_pattern_exhaustive) { | |
1007 | missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id())); | |
1008 | } | |
1009 | } | |
1010 | } | |
1011 | ||
1012 | let mut suggestion: Vec<String> = missing_variants | |
1013 | .iter() | |
1014 | .map(|v| { | |
1015 | let suffix = match v.ctor_kind { | |
1016 | CtorKind::Fn => "(..)", | |
1017 | CtorKind::Const | CtorKind::Fictive => "", | |
1018 | }; | |
1019 | let ident_str = if let Some(ident) = wildcard_ident { | |
1020 | format!("{} @ ", ident.name) | |
1021 | } else { | |
1022 | String::new() | |
1023 | }; | |
1024 | // This path assumes that the enum type is imported into scope. | |
1025 | format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix) | |
1026 | }) | |
1027 | .collect(); | |
1028 | ||
1029 | if suggestion.is_empty() { | |
1030 | return; | |
1031 | } | |
1032 | ||
1033 | let mut message = "wildcard match will miss any future added variants"; | |
1034 | ||
1035 | if let ty::Adt(def, _) = ty.kind() { | |
1036 | if def.is_variant_list_non_exhaustive() { | |
1037 | message = "match on non-exhaustive enum doesn't explicitly match all known variants"; | |
1038 | suggestion.push(String::from("_")); | |
1039 | } | |
1040 | } | |
1041 | ||
1042 | if suggestion.len() == 1 { | |
1043 | // No need to check for non-exhaustive enum as in that case len would be greater than 1 | |
1044 | span_lint_and_sugg( | |
1045 | cx, | |
1046 | MATCH_WILDCARD_FOR_SINGLE_VARIANTS, | |
1047 | wildcard_span, | |
1048 | message, | |
1049 | "try this", | |
1050 | suggestion[0].clone(), | |
1051 | Applicability::MaybeIncorrect, | |
1052 | ) | |
1053 | }; | |
1054 | ||
1055 | span_lint_and_sugg( | |
1056 | cx, | |
1057 | WILDCARD_ENUM_MATCH_ARM, | |
1058 | wildcard_span, | |
1059 | message, | |
1060 | "try this", | |
1061 | suggestion.join(" | "), | |
1062 | Applicability::MaybeIncorrect, | |
1063 | ) | |
1064 | } | |
1065 | } | |
1066 | ||
1067 | // If the block contains only a `panic!` macro (as expression or statement) | |
1068 | fn is_panic_block(block: &Block<'_>) -> bool { | |
1069 | match (&block.expr, block.stmts.len(), block.stmts.first()) { | |
1070 | (&Some(ref exp), 0, _) => { | |
1071 | is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none() | |
1072 | }, | |
1073 | (&None, 1, Some(stmt)) => { | |
1074 | is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none() | |
1075 | }, | |
1076 | _ => false, | |
1077 | } | |
1078 | } | |
1079 | ||
1080 | fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) { | |
1081 | if has_only_ref_pats(arms) { | |
1082 | let mut suggs = Vec::with_capacity(arms.len() + 1); | |
1083 | let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind { | |
1084 | let span = ex.span.source_callsite(); | |
1085 | suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string())); | |
1086 | ( | |
1087 | "you don't need to add `&` to both the expression and the patterns", | |
1088 | "try", | |
1089 | ) | |
1090 | } else { | |
1091 | let span = ex.span.source_callsite(); | |
1092 | suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string())); | |
1093 | ( | |
1094 | "you don't need to add `&` to all patterns", | |
1095 | "instead of prefixing all patterns with `&`, you can dereference the expression", | |
1096 | ) | |
1097 | }; | |
1098 | ||
1099 | suggs.extend(arms.iter().filter_map(|a| { | |
1100 | if let PatKind::Ref(ref refp, _) = a.pat.kind { | |
1101 | Some((a.pat.span, snippet(cx, refp.span, "..").to_string())) | |
1102 | } else { | |
1103 | None | |
1104 | } | |
1105 | })); | |
1106 | ||
1107 | span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| { | |
1108 | if !expr.span.from_expansion() { | |
1109 | multispan_sugg(diag, msg, suggs); | |
1110 | } | |
1111 | }); | |
1112 | } | |
1113 | } | |
1114 | ||
1115 | fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) { | |
1116 | if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() { | |
1117 | let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) { | |
1118 | is_ref_some_arm(&arms[1]) | |
1119 | } else if is_none_arm(&arms[1]) { | |
1120 | is_ref_some_arm(&arms[0]) | |
1121 | } else { | |
1122 | None | |
1123 | }; | |
1124 | if let Some(rb) = arm_ref { | |
1125 | let suggestion = if rb == BindingAnnotation::Ref { | |
1126 | "as_ref" | |
1127 | } else { | |
1128 | "as_mut" | |
1129 | }; | |
1130 | ||
1131 | let output_ty = cx.typeck_results().expr_ty(expr); | |
1132 | let input_ty = cx.typeck_results().expr_ty(ex); | |
1133 | ||
1134 | let cast = if_chain! { | |
1135 | if let ty::Adt(_, substs) = input_ty.kind(); | |
1136 | let input_ty = substs.type_at(0); | |
1137 | if let ty::Adt(_, substs) = output_ty.kind(); | |
1138 | let output_ty = substs.type_at(0); | |
1139 | if let ty::Ref(_, output_ty, _) = *output_ty.kind(); | |
1140 | if input_ty != output_ty; | |
1141 | then { | |
1142 | ".map(|x| x as _)" | |
1143 | } else { | |
1144 | "" | |
1145 | } | |
1146 | }; | |
1147 | ||
1148 | let mut applicability = Applicability::MachineApplicable; | |
1149 | span_lint_and_sugg( | |
1150 | cx, | |
1151 | MATCH_AS_REF, | |
1152 | expr.span, | |
1153 | &format!("use `{}()` instead", suggestion), | |
1154 | "try this", | |
1155 | format!( | |
1156 | "{}.{}(){}", | |
1157 | snippet_with_applicability(cx, ex.span, "_", &mut applicability), | |
1158 | suggestion, | |
1159 | cast, | |
1160 | ), | |
1161 | applicability, | |
1162 | ) | |
1163 | } | |
1164 | } | |
1165 | } | |
1166 | ||
1167 | fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) { | |
1168 | for arm in arms { | |
1169 | if let PatKind::Or(ref fields) = arm.pat.kind { | |
1170 | // look for multiple fields in this arm that contains at least one Wild pattern | |
1171 | if fields.len() > 1 && fields.iter().any(is_wild) { | |
1172 | span_lint_and_help( | |
1173 | cx, | |
1174 | WILDCARD_IN_OR_PATTERNS, | |
1175 | arm.pat.span, | |
1176 | "wildcard pattern covers any other pattern as it will match anyway", | |
1177 | None, | |
1178 | "consider handling `_` separately", | |
1179 | ); | |
1180 | } | |
1181 | } | |
1182 | } | |
1183 | } | |
1184 | ||
1185 | /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!` | |
1186 | fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool { | |
1187 | if let ExprKind::Match(ex, arms, ref match_source) = &expr.kind { | |
1188 | match match_source { | |
1189 | MatchSource::Normal => find_matches_sugg(cx, ex, arms, expr, false), | |
1190 | MatchSource::IfLetDesugar { .. } => find_matches_sugg(cx, ex, arms, expr, true), | |
1191 | _ => false, | |
1192 | } | |
1193 | } else { | |
1194 | false | |
1195 | } | |
1196 | } | |
1197 | ||
1198 | /// Lint a `match` or desugared `if let` for replacement by `matches!` | |
1199 | fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>, desugared: bool) -> bool { | |
1200 | if_chain! { | |
1201 | if arms.len() >= 2; | |
1202 | if cx.typeck_results().expr_ty(expr).is_bool(); | |
1203 | if let Some((b1_arm, b0_arms)) = arms.split_last(); | |
1204 | if let Some(b0) = find_bool_lit(&b0_arms[0].body.kind, desugared); | |
1205 | if let Some(b1) = find_bool_lit(&b1_arm.body.kind, desugared); | |
1206 | if is_wild(&b1_arm.pat); | |
1207 | if b0 != b1; | |
1208 | let if_guard = &b0_arms[0].guard; | |
1209 | if if_guard.is_none() || b0_arms.len() == 1; | |
1210 | if cx.tcx.hir().attrs(b0_arms[0].hir_id).is_empty(); | |
1211 | if b0_arms[1..].iter() | |
1212 | .all(|arm| { | |
1213 | find_bool_lit(&arm.body.kind, desugared).map_or(false, |b| b == b0) && | |
1214 | arm.guard.is_none() && cx.tcx.hir().attrs(arm.hir_id).is_empty() | |
1215 | }); | |
1216 | then { | |
1217 | // The suggestion may be incorrect, because some arms can have `cfg` attributes | |
1218 | // evaluated into `false` and so such arms will be stripped before. | |
1219 | let mut applicability = Applicability::MaybeIncorrect; | |
1220 | let pat = { | |
1221 | use itertools::Itertools as _; | |
1222 | b0_arms.iter() | |
1223 | .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability)) | |
1224 | .join(" | ") | |
1225 | }; | |
1226 | let pat_and_guard = if let Some(Guard::If(g)) = if_guard { | |
1227 | format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability)) | |
1228 | } else { | |
1229 | pat | |
1230 | }; | |
1231 | ||
1232 | // strip potential borrows (#6503), but only if the type is a reference | |
1233 | let mut ex_new = ex; | |
1234 | if let ExprKind::AddrOf(BorrowKind::Ref, .., ex_inner) = ex.kind { | |
1235 | if let ty::Ref(..) = cx.typeck_results().expr_ty(&ex_inner).kind() { | |
1236 | ex_new = ex_inner; | |
1237 | } | |
1238 | }; | |
1239 | span_lint_and_sugg( | |
1240 | cx, | |
1241 | MATCH_LIKE_MATCHES_MACRO, | |
1242 | expr.span, | |
1243 | &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }), | |
1244 | "try this", | |
1245 | format!( | |
1246 | "{}matches!({}, {})", | |
1247 | if b0 { "" } else { "!" }, | |
1248 | snippet_with_applicability(cx, ex_new.span, "..", &mut applicability), | |
1249 | pat_and_guard, | |
1250 | ), | |
1251 | applicability, | |
1252 | ); | |
1253 | true | |
1254 | } else { | |
1255 | false | |
1256 | } | |
1257 | } | |
1258 | } | |
1259 | ||
1260 | /// Extract a `bool` or `{ bool }` | |
1261 | fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option<bool> { | |
1262 | match ex { | |
1263 | ExprKind::Lit(Spanned { | |
1264 | node: LitKind::Bool(b), .. | |
1265 | }) => Some(*b), | |
1266 | ExprKind::Block( | |
1267 | rustc_hir::Block { | |
1268 | stmts: &[], | |
1269 | expr: Some(exp), | |
1270 | .. | |
1271 | }, | |
1272 | _, | |
1273 | ) if desugared => { | |
1274 | if let ExprKind::Lit(Spanned { | |
1275 | node: LitKind::Bool(b), .. | |
1276 | }) = exp.kind | |
1277 | { | |
1278 | Some(b) | |
1279 | } else { | |
1280 | None | |
1281 | } | |
1282 | }, | |
1283 | _ => None, | |
1284 | } | |
1285 | } | |
1286 | ||
1287 | fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) { | |
1288 | if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) { | |
1289 | return; | |
1290 | } | |
1291 | ||
1292 | // HACK: | |
1293 | // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here | |
1294 | // to prevent false positives as there is currently no better way to detect if code was excluded by | |
1295 | // a macro. See PR #6435 | |
1296 | if_chain! { | |
1297 | if let Some(match_snippet) = snippet_opt(cx, expr.span); | |
1298 | if let Some(arm_snippet) = snippet_opt(cx, arms[0].span); | |
1299 | if let Some(ex_snippet) = snippet_opt(cx, ex.span); | |
1300 | let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, ""); | |
1301 | if rest_snippet.contains("=>"); | |
1302 | then { | |
1303 | // The code it self contains another thick arrow "=>" | |
1304 | // -> Either another arm or a comment | |
1305 | return; | |
1306 | } | |
1307 | } | |
1308 | ||
1309 | let matched_vars = ex.span; | |
1310 | let bind_names = arms[0].pat.span; | |
1311 | let match_body = remove_blocks(&arms[0].body); | |
1312 | let mut snippet_body = if match_body.span.from_expansion() { | |
1313 | Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string() | |
1314 | } else { | |
1315 | snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string() | |
1316 | }; | |
1317 | ||
1318 | // Do we need to add ';' to suggestion ? | |
1319 | match match_body.kind { | |
1320 | ExprKind::Block(block, _) => { | |
1321 | // macro + expr_ty(body) == () | |
1322 | if block.span.from_expansion() && cx.typeck_results().expr_ty(&match_body).is_unit() { | |
1323 | snippet_body.push(';'); | |
1324 | } | |
1325 | }, | |
1326 | _ => { | |
1327 | // expr_ty(body) == () | |
1328 | if cx.typeck_results().expr_ty(&match_body).is_unit() { | |
1329 | snippet_body.push(';'); | |
1330 | } | |
1331 | }, | |
1332 | } | |
1333 | ||
1334 | let mut applicability = Applicability::MaybeIncorrect; | |
1335 | match arms[0].pat.kind { | |
1336 | PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => { | |
1337 | // If this match is in a local (`let`) stmt | |
1338 | let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) { | |
1339 | ( | |
1340 | parent_let_node.span, | |
1341 | format!( | |
1342 | "let {} = {};\n{}let {} = {};", | |
1343 | snippet_with_applicability(cx, bind_names, "..", &mut applicability), | |
1344 | snippet_with_applicability(cx, matched_vars, "..", &mut applicability), | |
1345 | " ".repeat(indent_of(cx, expr.span).unwrap_or(0)), | |
1346 | snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability), | |
1347 | snippet_body | |
1348 | ), | |
1349 | ) | |
1350 | } else { | |
1351 | // If we are in closure, we need curly braces around suggestion | |
1352 | let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0)); | |
1353 | let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string()); | |
1354 | if let Some(parent_expr) = get_parent_expr(cx, expr) { | |
1355 | if let ExprKind::Closure(..) = parent_expr.kind { | |
1356 | cbrace_end = format!("\n{}}}", indent); | |
1357 | // Fix body indent due to the closure | |
1358 | indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0)); | |
1359 | cbrace_start = format!("{{\n{}", indent); | |
1360 | } | |
1361 | }; | |
1362 | ( | |
1363 | expr.span, | |
1364 | format!( | |
1365 | "{}let {} = {};\n{}{}{}", | |
1366 | cbrace_start, | |
1367 | snippet_with_applicability(cx, bind_names, "..", &mut applicability), | |
1368 | snippet_with_applicability(cx, matched_vars, "..", &mut applicability), | |
1369 | indent, | |
1370 | snippet_body, | |
1371 | cbrace_end | |
1372 | ), | |
1373 | ) | |
1374 | }; | |
1375 | span_lint_and_sugg( | |
1376 | cx, | |
1377 | MATCH_SINGLE_BINDING, | |
1378 | target_span, | |
1379 | "this match could be written as a `let` statement", | |
1380 | "consider using `let` statement", | |
1381 | sugg, | |
1382 | applicability, | |
1383 | ); | |
1384 | }, | |
1385 | PatKind::Wild => { | |
1386 | span_lint_and_sugg( | |
1387 | cx, | |
1388 | MATCH_SINGLE_BINDING, | |
1389 | expr.span, | |
1390 | "this match could be replaced by its body itself", | |
1391 | "consider using the match body instead", | |
1392 | snippet_body, | |
1393 | Applicability::MachineApplicable, | |
1394 | ); | |
1395 | }, | |
1396 | _ => (), | |
1397 | } | |
1398 | } | |
1399 | ||
1400 | /// Returns true if the `ex` match expression is in a local (`let`) statement | |
1401 | fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> { | |
1402 | if_chain! { | |
1403 | let map = &cx.tcx.hir(); | |
1404 | if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id)); | |
1405 | if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id)); | |
1406 | then { | |
1407 | return Some(parent_let_expr); | |
1408 | } | |
1409 | } | |
1410 | None | |
1411 | } | |
1412 | ||
1413 | /// Gets all arms that are unbounded `PatRange`s. | |
1414 | fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> { | |
1415 | arms.iter() | |
1416 | .flat_map(|arm| { | |
1417 | if let Arm { | |
1418 | ref pat, guard: None, .. | |
1419 | } = *arm | |
1420 | { | |
1421 | if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind { | |
1422 | let lhs = match lhs { | |
1423 | Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0, | |
1424 | None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?, | |
1425 | }; | |
1426 | let rhs = match rhs { | |
1427 | Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0, | |
1428 | None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?, | |
1429 | }; | |
1430 | let rhs = match range_end { | |
1431 | RangeEnd::Included => Bound::Included(rhs), | |
1432 | RangeEnd::Excluded => Bound::Excluded(rhs), | |
1433 | }; | |
1434 | return Some(SpannedRange { | |
1435 | span: pat.span, | |
1436 | node: (lhs, rhs), | |
1437 | }); | |
1438 | } | |
1439 | ||
1440 | if let PatKind::Lit(ref value) = pat.kind { | |
1441 | let value = constant(cx, cx.typeck_results(), value)?.0; | |
1442 | return Some(SpannedRange { | |
1443 | span: pat.span, | |
1444 | node: (value.clone(), Bound::Included(value)), | |
1445 | }); | |
1446 | } | |
1447 | } | |
1448 | None | |
1449 | }) | |
1450 | .collect() | |
1451 | } | |
1452 | ||
1453 | #[derive(Debug, Eq, PartialEq)] | |
1454 | pub struct SpannedRange<T> { | |
1455 | pub span: Span, | |
1456 | pub node: (T, Bound<T>), | |
1457 | } | |
1458 | ||
1459 | type TypedRanges = Vec<SpannedRange<u128>>; | |
1460 | ||
1461 | /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway | |
1462 | /// and other types than | |
1463 | /// `Uint` and `Int` probably don't make sense. | |
1464 | fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges { | |
1465 | ranges | |
1466 | .iter() | |
1467 | .filter_map(|range| match range.node { | |
1468 | (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange { | |
1469 | span: range.span, | |
1470 | node: (start, Bound::Included(end)), | |
1471 | }), | |
1472 | (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange { | |
1473 | span: range.span, | |
1474 | node: (start, Bound::Excluded(end)), | |
1475 | }), | |
1476 | (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange { | |
1477 | span: range.span, | |
1478 | node: (start, Bound::Unbounded), | |
1479 | }), | |
1480 | _ => None, | |
1481 | }) | |
1482 | .collect() | |
1483 | } | |
1484 | ||
1485 | fn is_unit_expr(expr: &Expr<'_>) -> bool { | |
1486 | match expr.kind { | |
1487 | ExprKind::Tup(ref v) if v.is_empty() => true, | |
1488 | ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true, | |
1489 | _ => false, | |
1490 | } | |
1491 | } | |
1492 | ||
1493 | // Checks if arm has the form `None => None` | |
1494 | fn is_none_arm(arm: &Arm<'_>) -> bool { | |
1495 | matches!(arm.pat.kind, PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE)) | |
1496 | } | |
1497 | ||
1498 | // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`) | |
1499 | fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> { | |
1500 | if_chain! { | |
1501 | if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind; | |
1502 | if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME); | |
1503 | if let PatKind::Binding(rb, .., ident, _) = pats[0].kind; | |
1504 | if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut; | |
1505 | if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind; | |
1506 | if let ExprKind::Path(ref some_path) = e.kind; | |
1507 | if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1; | |
1508 | if let ExprKind::Path(QPath::Resolved(_, ref path2)) = args[0].kind; | |
1509 | if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name; | |
1510 | then { | |
1511 | return Some(rb) | |
1512 | } | |
1513 | } | |
1514 | None | |
1515 | } | |
1516 | ||
1517 | fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool { | |
1518 | let mapped = arms | |
1519 | .iter() | |
1520 | .map(|a| { | |
1521 | match a.pat.kind { | |
1522 | PatKind::Ref(..) => Some(true), // &-patterns | |
1523 | PatKind::Wild => Some(false), // an "anything" wildcard is also fine | |
1524 | _ => None, // any other pattern is not fine | |
1525 | } | |
1526 | }) | |
1527 | .collect::<Option<Vec<bool>>>(); | |
1528 | // look for Some(v) where there's at least one true element | |
1529 | mapped.map_or(false, |v| v.iter().any(|el| *el)) | |
1530 | } | |
1531 | ||
1532 | pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)> | |
1533 | where | |
1534 | T: Copy + Ord, | |
1535 | { | |
1536 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] | |
1537 | enum Kind<'a, T> { | |
1538 | Start(T, &'a SpannedRange<T>), | |
1539 | End(Bound<T>, &'a SpannedRange<T>), | |
1540 | } | |
1541 | ||
1542 | impl<'a, T: Copy> Kind<'a, T> { | |
1543 | fn range(&self) -> &'a SpannedRange<T> { | |
1544 | match *self { | |
1545 | Kind::Start(_, r) | Kind::End(_, r) => r, | |
1546 | } | |
1547 | } | |
1548 | ||
1549 | fn value(self) -> Bound<T> { | |
1550 | match self { | |
1551 | Kind::Start(t, _) => Bound::Included(t), | |
1552 | Kind::End(t, _) => t, | |
1553 | } | |
1554 | } | |
1555 | } | |
1556 | ||
1557 | impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> { | |
1558 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | |
1559 | Some(self.cmp(other)) | |
1560 | } | |
1561 | } | |
1562 | ||
1563 | impl<'a, T: Copy + Ord> Ord for Kind<'a, T> { | |
1564 | fn cmp(&self, other: &Self) -> Ordering { | |
1565 | match (self.value(), other.value()) { | |
1566 | (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b), | |
1567 | // Range patterns cannot be unbounded (yet) | |
1568 | (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(), | |
1569 | (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) { | |
1570 | Ordering::Equal => Ordering::Greater, | |
1571 | other => other, | |
1572 | }, | |
1573 | (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) { | |
1574 | Ordering::Equal => Ordering::Less, | |
1575 | other => other, | |
1576 | }, | |
1577 | } | |
1578 | } | |
1579 | } | |
1580 | ||
1581 | let mut values = Vec::with_capacity(2 * ranges.len()); | |
1582 | ||
1583 | for r in ranges { | |
1584 | values.push(Kind::Start(r.node.0, r)); | |
1585 | values.push(Kind::End(r.node.1, r)); | |
1586 | } | |
1587 | ||
1588 | values.sort(); | |
1589 | ||
1590 | for (a, b) in values.iter().zip(values.iter().skip(1)) { | |
1591 | match (a, b) { | |
1592 | (&Kind::Start(_, ra), &Kind::End(_, rb)) => { | |
1593 | if ra.node != rb.node { | |
1594 | return Some((ra, rb)); | |
1595 | } | |
1596 | }, | |
1597 | (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (), | |
1598 | _ => { | |
1599 | // skip if the range `a` is completely included into the range `b` | |
1600 | if let Ordering::Equal | Ordering::Less = a.cmp(&b) { | |
1601 | let kind_a = Kind::End(a.range().node.1, a.range()); | |
1602 | let kind_b = Kind::End(b.range().node.1, b.range()); | |
1603 | if let Ordering::Equal | Ordering::Greater = kind_a.cmp(&kind_b) { | |
1604 | return None; | |
1605 | } | |
1606 | } | |
1607 | return Some((a.range(), b.range())); | |
1608 | }, | |
1609 | } | |
1610 | } | |
1611 | ||
1612 | None | |
1613 | } | |
1614 | ||
1615 | mod redundant_pattern_match { | |
1616 | use super::REDUNDANT_PATTERN_MATCHING; | |
1617 | use crate::utils::{match_qpath, match_trait_method, paths, snippet, span_lint_and_then}; | |
1618 | use if_chain::if_chain; | |
1619 | use rustc_ast::ast::LitKind; | |
1620 | use rustc_errors::Applicability; | |
1621 | use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind, QPath}; | |
1622 | use rustc_lint::LateContext; | |
1623 | use rustc_span::sym; | |
1624 | ||
1625 | pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { | |
1626 | if let ExprKind::Match(op, arms, ref match_source) = &expr.kind { | |
1627 | match match_source { | |
1628 | MatchSource::Normal => find_sugg_for_match(cx, expr, op, arms), | |
1629 | MatchSource::IfLetDesugar { .. } => find_sugg_for_if_let(cx, expr, op, arms, "if"), | |
1630 | MatchSource::WhileLetDesugar => find_sugg_for_if_let(cx, expr, op, arms, "while"), | |
1631 | _ => {}, | |
1632 | } | |
1633 | } | |
1634 | } | |
1635 | ||
1636 | fn find_sugg_for_if_let<'tcx>( | |
1637 | cx: &LateContext<'tcx>, | |
1638 | expr: &'tcx Expr<'_>, | |
1639 | op: &Expr<'_>, | |
1640 | arms: &[Arm<'_>], | |
1641 | keyword: &'static str, | |
1642 | ) { | |
1643 | let good_method = match arms[0].pat.kind { | |
1644 | PatKind::TupleStruct(ref path, ref patterns, _) if patterns.len() == 1 => { | |
1645 | if let PatKind::Wild = patterns[0].kind { | |
1646 | if match_qpath(path, &paths::RESULT_OK) { | |
1647 | "is_ok()" | |
1648 | } else if match_qpath(path, &paths::RESULT_ERR) { | |
1649 | "is_err()" | |
1650 | } else if match_qpath(path, &paths::OPTION_SOME) { | |
1651 | "is_some()" | |
1652 | } else if match_qpath(path, &paths::POLL_READY) { | |
1653 | "is_ready()" | |
1654 | } else if match_qpath(path, &paths::IPADDR_V4) { | |
1655 | "is_ipv4()" | |
1656 | } else if match_qpath(path, &paths::IPADDR_V6) { | |
1657 | "is_ipv6()" | |
1658 | } else { | |
1659 | return; | |
1660 | } | |
1661 | } else { | |
1662 | return; | |
1663 | } | |
1664 | }, | |
1665 | PatKind::Path(ref path) => { | |
1666 | if match_qpath(path, &paths::OPTION_NONE) { | |
1667 | "is_none()" | |
1668 | } else if match_qpath(path, &paths::POLL_PENDING) { | |
1669 | "is_pending()" | |
1670 | } else { | |
1671 | return; | |
1672 | } | |
1673 | }, | |
1674 | _ => return, | |
1675 | }; | |
1676 | ||
1677 | // check that `while_let_on_iterator` lint does not trigger | |
1678 | if_chain! { | |
1679 | if keyword == "while"; | |
1680 | if let ExprKind::MethodCall(method_path, _, _, _) = op.kind; | |
1681 | if method_path.ident.name == sym::next; | |
1682 | if match_trait_method(cx, op, &paths::ITERATOR); | |
1683 | then { | |
1684 | return; | |
1685 | } | |
1686 | } | |
1687 | ||
1688 | let result_expr = match &op.kind { | |
1689 | ExprKind::AddrOf(_, _, borrowed) => borrowed, | |
1690 | _ => op, | |
1691 | }; | |
1692 | span_lint_and_then( | |
1693 | cx, | |
1694 | REDUNDANT_PATTERN_MATCHING, | |
1695 | arms[0].pat.span, | |
1696 | &format!("redundant pattern matching, consider using `{}`", good_method), | |
1697 | |diag| { | |
1698 | // while let ... = ... { ... } | |
1699 | // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | |
1700 | let expr_span = expr.span; | |
1701 | ||
1702 | // while let ... = ... { ... } | |
1703 | // ^^^ | |
1704 | let op_span = result_expr.span.source_callsite(); | |
1705 | ||
1706 | // while let ... = ... { ... } | |
1707 | // ^^^^^^^^^^^^^^^^^^^ | |
1708 | let span = expr_span.until(op_span.shrink_to_hi()); | |
1709 | diag.span_suggestion( | |
1710 | span, | |
1711 | "try this", | |
1712 | format!("{} {}.{}", keyword, snippet(cx, op_span, "_"), good_method), | |
1713 | Applicability::MachineApplicable, // snippet | |
1714 | ); | |
1715 | }, | |
1716 | ); | |
1717 | } | |
1718 | ||
1719 | fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) { | |
1720 | if arms.len() == 2 { | |
1721 | let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind); | |
1722 | ||
1723 | let found_good_method = match node_pair { | |
1724 | ( | |
1725 | PatKind::TupleStruct(ref path_left, ref patterns_left, _), | |
1726 | PatKind::TupleStruct(ref path_right, ref patterns_right, _), | |
1727 | ) if patterns_left.len() == 1 && patterns_right.len() == 1 => { | |
1728 | if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) { | |
1729 | find_good_method_for_match( | |
1730 | arms, | |
1731 | path_left, | |
1732 | path_right, | |
1733 | &paths::RESULT_OK, | |
1734 | &paths::RESULT_ERR, | |
1735 | "is_ok()", | |
1736 | "is_err()", | |
1737 | ) | |
1738 | .or_else(|| { | |
1739 | find_good_method_for_match( | |
1740 | arms, | |
1741 | path_left, | |
1742 | path_right, | |
1743 | &paths::IPADDR_V4, | |
1744 | &paths::IPADDR_V6, | |
1745 | "is_ipv4()", | |
1746 | "is_ipv6()", | |
1747 | ) | |
1748 | }) | |
1749 | } else { | |
1750 | None | |
1751 | } | |
1752 | }, | |
1753 | (PatKind::TupleStruct(ref path_left, ref patterns, _), PatKind::Path(ref path_right)) | |
1754 | | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, ref patterns, _)) | |
1755 | if patterns.len() == 1 => | |
1756 | { | |
1757 | if let PatKind::Wild = patterns[0].kind { | |
1758 | find_good_method_for_match( | |
1759 | arms, | |
1760 | path_left, | |
1761 | path_right, | |
1762 | &paths::OPTION_SOME, | |
1763 | &paths::OPTION_NONE, | |
1764 | "is_some()", | |
1765 | "is_none()", | |
1766 | ) | |
1767 | .or_else(|| { | |
1768 | find_good_method_for_match( | |
1769 | arms, | |
1770 | path_left, | |
1771 | path_right, | |
1772 | &paths::POLL_READY, | |
1773 | &paths::POLL_PENDING, | |
1774 | "is_ready()", | |
1775 | "is_pending()", | |
1776 | ) | |
1777 | }) | |
1778 | } else { | |
1779 | None | |
1780 | } | |
1781 | }, | |
1782 | _ => None, | |
1783 | }; | |
1784 | ||
1785 | if let Some(good_method) = found_good_method { | |
1786 | let span = expr.span.to(op.span); | |
1787 | let result_expr = match &op.kind { | |
1788 | ExprKind::AddrOf(_, _, borrowed) => borrowed, | |
1789 | _ => op, | |
1790 | }; | |
1791 | span_lint_and_then( | |
1792 | cx, | |
1793 | REDUNDANT_PATTERN_MATCHING, | |
1794 | expr.span, | |
1795 | &format!("redundant pattern matching, consider using `{}`", good_method), | |
1796 | |diag| { | |
1797 | diag.span_suggestion( | |
1798 | span, | |
1799 | "try this", | |
1800 | format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method), | |
1801 | Applicability::MaybeIncorrect, // snippet | |
1802 | ); | |
1803 | }, | |
1804 | ); | |
1805 | } | |
1806 | } | |
1807 | } | |
1808 | ||
1809 | fn find_good_method_for_match<'a>( | |
1810 | arms: &[Arm<'_>], | |
1811 | path_left: &QPath<'_>, | |
1812 | path_right: &QPath<'_>, | |
1813 | expected_left: &[&str], | |
1814 | expected_right: &[&str], | |
1815 | should_be_left: &'a str, | |
1816 | should_be_right: &'a str, | |
1817 | ) -> Option<&'a str> { | |
1818 | let body_node_pair = if match_qpath(path_left, expected_left) && match_qpath(path_right, expected_right) { | |
1819 | (&(*arms[0].body).kind, &(*arms[1].body).kind) | |
1820 | } else if match_qpath(path_right, expected_left) && match_qpath(path_left, expected_right) { | |
1821 | (&(*arms[1].body).kind, &(*arms[0].body).kind) | |
1822 | } else { | |
1823 | return None; | |
1824 | }; | |
1825 | ||
1826 | match body_node_pair { | |
1827 | (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) { | |
1828 | (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left), | |
1829 | (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right), | |
1830 | _ => None, | |
1831 | }, | |
1832 | _ => None, | |
1833 | } | |
1834 | } | |
1835 | } | |
1836 | ||
1837 | #[test] | |
1838 | fn test_overlapping() { | |
1839 | use rustc_span::source_map::DUMMY_SP; | |
1840 | ||
1841 | let sp = |s, e| SpannedRange { | |
1842 | span: DUMMY_SP, | |
1843 | node: (s, e), | |
1844 | }; | |
1845 | ||
1846 | assert_eq!(None, overlapping::<u8>(&[])); | |
1847 | assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))])); | |
1848 | assert_eq!( | |
1849 | None, | |
1850 | overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))]) | |
1851 | ); | |
1852 | assert_eq!( | |
1853 | None, | |
1854 | overlapping(&[ | |
1855 | sp(1, Bound::Included(4)), | |
1856 | sp(5, Bound::Included(6)), | |
1857 | sp(10, Bound::Included(11)) | |
1858 | ],) | |
1859 | ); | |
1860 | assert_eq!( | |
1861 | Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))), | |
1862 | overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))]) | |
1863 | ); | |
1864 | assert_eq!( | |
1865 | Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))), | |
1866 | overlapping(&[ | |
1867 | sp(1, Bound::Included(4)), | |
1868 | sp(5, Bound::Included(6)), | |
1869 | sp(6, Bound::Included(11)) | |
1870 | ],) | |
1871 | ); | |
1872 | } | |
1873 | ||
1874 | /// Implementation of `MATCH_SAME_ARMS`. | |
1875 | fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) { | |
1876 | if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind { | |
1877 | let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 { | |
1878 | let mut h = SpanlessHash::new(cx); | |
1879 | h.hash_expr(&arm.body); | |
1880 | h.finish() | |
1881 | }; | |
1882 | ||
1883 | let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool { | |
1884 | let min_index = usize::min(lindex, rindex); | |
1885 | let max_index = usize::max(lindex, rindex); | |
1886 | ||
1887 | let mut local_map: FxHashMap<HirId, HirId> = FxHashMap::default(); | |
1888 | let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| { | |
1889 | if_chain! { | |
1890 | if let Some(a_id) = path_to_local(a); | |
1891 | if let Some(b_id) = path_to_local(b); | |
1892 | let entry = match local_map.entry(a_id) { | |
1893 | Entry::Vacant(entry) => entry, | |
1894 | // check if using the same bindings as before | |
1895 | Entry::Occupied(entry) => return *entry.get() == b_id, | |
1896 | }; | |
1897 | // the names technically don't have to match; this makes the lint more conservative | |
1898 | if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id); | |
1899 | if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b)); | |
1900 | if pat_contains_local(lhs.pat, a_id); | |
1901 | if pat_contains_local(rhs.pat, b_id); | |
1902 | then { | |
1903 | entry.insert(b_id); | |
1904 | true | |
1905 | } else { | |
1906 | false | |
1907 | } | |
1908 | } | |
1909 | }; | |
1910 | // Arms with a guard are ignored, those can’t always be merged together | |
1911 | // This is also the case for arms in-between each there is an arm with a guard | |
1912 | (min_index..=max_index).all(|index| arms[index].guard.is_none()) | |
1913 | && SpanlessEq::new(cx) | |
1914 | .expr_fallback(eq_fallback) | |
1915 | .eq_expr(&lhs.body, &rhs.body) | |
1916 | // these checks could be removed to allow unused bindings | |
1917 | && bindings_eq(lhs.pat, local_map.keys().copied().collect()) | |
1918 | && bindings_eq(rhs.pat, local_map.values().copied().collect()) | |
1919 | }; | |
1920 | ||
1921 | let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect(); | |
1922 | for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) { | |
1923 | span_lint_and_then( | |
1924 | cx, | |
1925 | MATCH_SAME_ARMS, | |
1926 | j.body.span, | |
1927 | "this `match` has identical arm bodies", | |
1928 | |diag| { | |
1929 | diag.span_note(i.body.span, "same as this"); | |
1930 | ||
1931 | // Note: this does not use `span_suggestion` on purpose: | |
1932 | // there is no clean way | |
1933 | // to remove the other arm. Building a span and suggest to replace it to "" | |
1934 | // makes an even more confusing error message. Also in order not to make up a | |
1935 | // span for the whole pattern, the suggestion is only shown when there is only | |
1936 | // one pattern. The user should know about `|` if they are already using it… | |
1937 | ||
1938 | let lhs = snippet(cx, i.pat.span, "<pat1>"); | |
1939 | let rhs = snippet(cx, j.pat.span, "<pat2>"); | |
1940 | ||
1941 | if let PatKind::Wild = j.pat.kind { | |
1942 | // if the last arm is _, then i could be integrated into _ | |
1943 | // note that i.pat cannot be _, because that would mean that we're | |
1944 | // hiding all the subsequent arms, and rust won't compile | |
1945 | diag.span_note( | |
1946 | i.body.span, | |
1947 | &format!( | |
1948 | "`{}` has the same arm body as the `_` wildcard, consider removing it", | |
1949 | lhs | |
1950 | ), | |
1951 | ); | |
1952 | } else { | |
1953 | diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs)); | |
1954 | } | |
1955 | }, | |
1956 | ); | |
1957 | } | |
1958 | } | |
1959 | } | |
1960 | ||
1961 | fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool { | |
1962 | let mut result = false; | |
1963 | pat.walk_short(|p| { | |
1964 | result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id); | |
1965 | !result | |
1966 | }); | |
1967 | result | |
1968 | } | |
1969 | ||
1970 | /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa | |
1971 | fn bindings_eq(pat: &Pat<'_>, mut ids: FxHashSet<HirId>) -> bool { | |
1972 | let mut result = true; | |
1973 | pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id)); | |
1974 | result && ids.is_empty() | |
1975 | } |