]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_field_names.rs
Merge pull request #2999 from flip1995/single_char_pattern
[rust.git] / clippy_lints / src / redundant_field_names.rs
1 use rustc::lint::*;
2 use rustc::{declare_lint, lint_array};
3 use rustc::hir::*;
4 use crate::utils::{in_macro, match_var, 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 declare_clippy_lint! {
25     pub REDUNDANT_FIELD_NAMES,
26     style,
27     "checks for fields in struct literals where shorthands could be used"
28 }
29
30 pub struct RedundantFieldNames;
31
32 impl LintPass for RedundantFieldNames {
33     fn get_lints(&self) -> LintArray {
34         lint_array!(REDUNDANT_FIELD_NAMES)
35     }
36 }
37
38 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantFieldNames {
39     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
40         // Ignore all macros including range expressions.
41         // They can have redundant field names when expanded.
42         // e.g. range expression `start..end` is desugared to `Range { start: start, end: end }`
43         if in_macro(expr.span) {
44             return;
45         }
46
47         if let ExprKind::Struct(_, ref fields, _) = expr.node {
48             for field in fields {
49                 let name = field.ident.name;
50
51                 if match_var(&field.expr, name) && !field.is_shorthand {
52                     span_lint_and_sugg (
53                         cx,
54                         REDUNDANT_FIELD_NAMES,
55                         field.span,
56                         "redundant field names in struct initialization",
57                         "replace it with",
58                         name.to_string()
59                     );
60                 }
61             }
62         }
63     }
64 }