]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_field_names.rs
Merge pull request #2519 from ordovicia/issue-2516
[rust.git] / clippy_lints / src / redundant_field_names.rs
1 use rustc::lint::*;
2 use rustc::hir::*;
3 use utils::{in_macro, is_range_expression, match_var, span_lint_and_sugg};
4
5 /// **What it does:** Checks for fields in struct literals where shorthands
6 /// could 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     "checks for fields in struct literals where shorthands could 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         // Ignore all macros including range expressions.
40         // They can have redundant field names when expanded.
41         // e.g. range expression `start..end` is desugared to `Range { start: start, end: end }`
42         if in_macro(expr.span) || is_range_expression(expr.span) {
43             return;
44         }
45
46         if let ExprStruct(_, ref fields, _) = expr.node {
47             for field in fields {
48                 let name = field.name.node;
49
50                 if match_var(&field.expr, name) && !field.is_shorthand {
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                         name.to_string()
58                     );
59                 }
60             }
61         }
62     }
63 }