]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_field_names.rs
Auto merge of #6325 - flip1995:rustup, r=flip1995
[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_middle::lint::in_external_macro;
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks for fields in struct literals where shorthands
10     /// could be used.
11     ///
12     /// **Why is this bad?** If the field and variable names are the same,
13     /// the field name is redundant.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     /// ```rust
19     /// let bar: u8 = 123;
20     ///
21     /// struct Foo {
22     ///     bar: u8,
23     /// }
24     ///
25     /// let foo = Foo { bar: bar };
26     /// ```
27     /// the last line can be simplified to
28     /// ```ignore
29     /// let foo = Foo { bar };
30     /// ```
31     pub REDUNDANT_FIELD_NAMES,
32     style,
33     "checks for fields in struct literals where shorthands could be used"
34 }
35
36 declare_lint_pass!(RedundantFieldNames => [REDUNDANT_FIELD_NAMES]);
37
38 impl EarlyLintPass for RedundantFieldNames {
39     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
40         if in_external_macro(cx.sess, expr.span) {
41             return;
42         }
43         if let ExprKind::Struct(_, ref fields, _) = expr.kind {
44             for field in fields {
45                 if field.is_shorthand {
46                     continue;
47                 }
48                 if let ExprKind::Path(None, path) = &field.expr.kind {
49                     if path.segments.len() == 1
50                         && path.segments[0].ident == field.ident
51                         && path.segments[0].args.is_none()
52                     {
53                         span_lint_and_sugg(
54                             cx,
55                             REDUNDANT_FIELD_NAMES,
56                             field.span,
57                             "redundant field names in struct initialization",
58                             "replace it with",
59                             field.ident.to_string(),
60                             Applicability::MachineApplicable,
61                         );
62                     }
63                 }
64             }
65         }
66     }
67 }