]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_field_names.rs
Allow UUID style formatting for `inconsistent_digit_grouping` lint
[rust.git] / clippy_lints / src / redundant_field_names.rs
1 use crate::utils::span_lint_and_sugg;
2 use rustc_ast::ast::{Expr, ExprKind};
3 use rustc_errors::Applicability;
4 use rustc_lint::{EarlyContext, EarlyLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
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 declare_lint_pass!(RedundantFieldNames => [REDUNDANT_FIELD_NAMES]);
36
37 impl EarlyLintPass for RedundantFieldNames {
38     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
39         if let ExprKind::Struct(_, ref fields, _) = expr.kind {
40             for field in fields {
41                 if field.is_shorthand {
42                     continue;
43                 }
44                 if let ExprKind::Path(None, path) = &field.expr.kind {
45                     if path.segments.len() == 1
46                         && path.segments[0].ident == field.ident
47                         && path.segments[0].args.is_none()
48                     {
49                         span_lint_and_sugg(
50                             cx,
51                             REDUNDANT_FIELD_NAMES,
52                             field.span,
53                             "redundant field names in struct initialization",
54                             "replace it with",
55                             field.ident.to_string(),
56                             Applicability::MachineApplicable,
57                         );
58                     }
59                 }
60             }
61         }
62     }
63 }