]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_field_names.rs
Replace most of ty:Ty with Ty
[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 declare_clippy_lint! {
8     /// **What it does:** Checks for fields in struct literals where shorthands
9     /// could be used.
10     ///
11     /// **Why is this bad?** If the field and variable names are the same,
12     /// the field name is redundant.
13     ///
14     /// **Known problems:** None.
15     ///
16     /// **Example:**
17     /// ```rust
18     /// let bar: u8 = 123;
19     ///
20     /// struct Foo {
21     ///     bar: u8,
22     /// }
23     ///
24     /// let foo = Foo { bar: bar };
25     /// ```
26     /// the last line can be simplified to
27     /// ```ignore
28     /// let foo = Foo { bar };
29     /// ```
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 }