]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_field_names.rs
Merge pull request #3036 from matthiaskrgr/clippy_self
[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 /// the last line can be simplified to
25 /// ```rust
26 /// let foo = Foo{ bar }
27 /// ```
28 declare_clippy_lint! {
29     pub REDUNDANT_FIELD_NAMES,
30     style,
31     "checks for fields in struct literals where shorthands could be used"
32 }
33
34 pub struct RedundantFieldNames;
35
36 impl LintPass for RedundantFieldNames {
37     fn get_lints(&self) -> LintArray {
38         lint_array!(REDUNDANT_FIELD_NAMES)
39     }
40 }
41
42 impl EarlyLintPass for RedundantFieldNames {
43     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
44         if let ExprKind::Struct(_, ref fields, _) = expr.node {
45             for field in fields {
46                 if field.is_shorthand {
47                     continue;
48                 }
49                 if let ExprKind::Path(None, path) = &field.expr.node {
50                     if path.segments.len() == 1 && path.segments[0].ident == field.ident {
51                         span_lint_and_sugg (
52                             cx,
53                             REDUNDANT_FIELD_NAMES,
54                             field.span,
55                             "redundant field names in struct initialization",
56                             "replace it with",
57                             field.ident.to_string()
58                         );
59                     }
60                 }
61             }
62         }
63     }
64 }