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