]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_field_names.rs
Merge pull request #2823 from flip1995/thingies_things
[rust.git] / clippy_lints / src / redundant_field_names.rs
1 use rustc::lint::*;
2 use rustc::{declare_lint, lint_array};
3 use syntax::ast::*;
4 use crate::utils::{span_lint_and_sugg};
5
6 /// **What it does:** Checks for fields in struct literals where shorthands
7 /// could be used.
8 ///
9 /// **Why is this bad?** If the field and variable names are the same,
10 /// the field name is redundant.
11 ///
12 /// **Known problems:** None.
13 ///
14 /// **Example:**
15 /// ```rust
16 /// let bar: u8 = 123;
17 ///
18 /// struct Foo {
19 ///     bar: u8,
20 /// }
21 ///
22 /// let foo = Foo{ bar: bar }
23 /// ```
24 declare_clippy_lint! {
25     pub REDUNDANT_FIELD_NAMES,
26     style,
27     "checks for fields in struct literals where shorthands could be used"
28 }
29
30 pub struct RedundantFieldNames;
31
32 impl LintPass for RedundantFieldNames {
33     fn get_lints(&self) -> LintArray {
34         lint_array!(REDUNDANT_FIELD_NAMES)
35     }
36 }
37
38 impl EarlyLintPass for RedundantFieldNames {
39     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
40         if let ExprKind::Struct(_, ref fields, _) = expr.node {
41             for field in fields {
42                 if field.is_shorthand {
43                     continue;
44                 }
45                 if let ExprKind::Path(None, path) = &field.expr.node {
46                     if path.segments.len() == 1 && path.segments[0].ident == field.ident {
47                         span_lint_and_sugg (
48                             cx,
49                             REDUNDANT_FIELD_NAMES,
50                             field.span,
51                             "redundant field names in struct initialization",
52                             "replace it with",
53                             field.ident.to_string()
54                         );
55                     }
56                 }
57             }
58         }
59     }
60 }