|
| 1 | +use clippy_utils::diagnostics::span_lint_and_help; |
| 2 | +use rustc_ast::ast::{Pat, PatFieldsRest, PatKind}; |
| 3 | +use rustc_lint::{EarlyContext, EarlyLintPass}; |
| 4 | +use rustc_session::declare_lint_pass; |
| 5 | + |
| 6 | +declare_clippy_lint! { |
| 7 | + /// ### What it does |
| 8 | + /// Disallows the use of rest patterns when destructuring structs. |
| 9 | + /// |
| 10 | + /// ### Why is this bad? |
| 11 | + /// It might lead to unhandled fields when the struct changes. |
| 12 | + /// |
| 13 | + /// ### Example |
| 14 | + /// ```no_run |
| 15 | + /// struct S { |
| 16 | + /// a: u8, |
| 17 | + /// b: u8, |
| 18 | + /// c: u8, |
| 19 | + /// } |
| 20 | + /// |
| 21 | + /// let s = S { a: 1, b: 2, c: 3 }; |
| 22 | + /// |
| 23 | + /// let S { a, b, .. } = s; |
| 24 | + /// ``` |
| 25 | + /// Use instead: |
| 26 | + /// ```no_run |
| 27 | + /// struct S { |
| 28 | + /// a: u8, |
| 29 | + /// b: u8, |
| 30 | + /// c: u8, |
| 31 | + /// } |
| 32 | + /// |
| 33 | + /// let s = S { a: 1, b: 2, c: 3 }; |
| 34 | + /// |
| 35 | + /// let S { a, b, c: _ } = s; |
| 36 | + /// ``` |
| 37 | + #[clippy::version = "1.89.0"] |
| 38 | + pub REST_WHEN_DESTRUCTURING_STRUCT, |
| 39 | + nursery, |
| 40 | + "rest (..) in destructuring expression" |
| 41 | +} |
| 42 | +declare_lint_pass!(RestWhenDestructuringStruct => [REST_WHEN_DESTRUCTURING_STRUCT]); |
| 43 | + |
| 44 | +impl EarlyLintPass for RestWhenDestructuringStruct { |
| 45 | + fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat) { |
| 46 | + if let PatKind::Struct(_, _, _, PatFieldsRest::Rest) = pat.kind { |
| 47 | + span_lint_and_help( |
| 48 | + cx, |
| 49 | + REST_WHEN_DESTRUCTURING_STRUCT, |
| 50 | + pat.span, |
| 51 | + "struct destructuring with rest (..)", |
| 52 | + None, |
| 53 | + "consider explicitly ignoring remaining fields with wildcard patterns (x: _)", |
| 54 | + ); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments