]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_field_names.rs
Implement redundant field names lint #2244
[rust.git] / clippy_lints / src / redundant_field_names.rs
1 use rustc::lint::*;
2 use rustc::hir::*;
3 use utils::{span_lint_and_sugg};
4
5 /// **What it does:** Checks for redundnat field names where shorthands
6 /// can be used.
7 /// 
8 /// **Why is this bad?** If the field and variable names are the same,
9 /// the field name is redundant.
10 /// 
11 /// **Known problems:** None.
12 /// 
13 /// **Example:**
14 /// ```rust
15 /// let bar: u8 = 123;
16 /// 
17 /// struct Foo {
18 ///     bar: u8,
19 /// }
20 /// 
21 /// let foo = Foo{ bar: bar }
22 /// ```
23 declare_lint! {
24     pub REDUNDANT_FIELD_NAMES,
25     Warn,
26     "using same name for field and variable ,where shorthand can be used"
27 }
28
29 pub struct RedundantFieldNames;
30
31 impl LintPass for RedundantFieldNames {
32     fn get_lints(&self) -> LintArray {
33         lint_array!(REDUNDANT_FIELD_NAMES)
34     }
35 }
36
37 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantFieldNames {
38     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
39         if let ExprStruct(_, ref fields, _) = expr.node {
40             for field in fields {
41                 let name = field.name.node;
42                 if let ExprPath(ref qpath) = field.expr.node {
43                     if let &QPath::Resolved(_, ref path) = qpath {
44                         let segments = &path.segments;
45
46                         if segments.len() == 1 {
47                             let expr_name = segments[0].name;
48
49                             if name == expr_name {
50                                 span_lint_and_sugg(
51                                     cx,
52                                     REDUNDANT_FIELD_NAMES,
53                                     path.span,
54                                     "redundant field names in struct initialization",
55                                     &format!(
56                                         "replace '{0}: {0}' with '{0}'",
57                                         name,
58                                     ),
59                                     "".to_string()
60                                 );
61                             }
62                         }
63                     }
64                 }
65             }
66         }
67     }
68 }