1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::{meets_msrv, msrvs};
3 use rustc_ast::ast::{Expr, ExprKind};
4 use rustc_errors::Applicability;
5 use rustc_lint::{EarlyContext, EarlyLintPass};
6 use rustc_middle::lint::in_external_macro;
7 use rustc_semver::RustcVersion;
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for fields in struct literals where shorthands
14 /// **Why is this bad?** If the field and variable names are the same,
15 /// the field name is redundant.
17 /// **Known problems:** None.
21 /// let bar: u8 = 123;
27 /// let foo = Foo { bar: bar };
29 /// the last line can be simplified to
31 /// let foo = Foo { bar };
33 pub REDUNDANT_FIELD_NAMES,
35 "checks for fields in struct literals where shorthands could be used"
38 pub struct RedundantFieldNames {
39 msrv: Option<RustcVersion>,
42 impl RedundantFieldNames {
44 pub fn new(msrv: Option<RustcVersion>) -> Self {
49 impl_lint_pass!(RedundantFieldNames => [REDUNDANT_FIELD_NAMES]);
51 impl EarlyLintPass for RedundantFieldNames {
52 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
53 if !meets_msrv(self.msrv.as_ref(), &msrvs::FIELD_INIT_SHORTHAND) {
57 if in_external_macro(cx.sess, expr.span) {
60 if let ExprKind::Struct(ref se) = expr.kind {
61 for field in &se.fields {
62 if field.is_shorthand {
65 if let ExprKind::Path(None, path) = &field.expr.kind {
66 if path.segments.len() == 1
67 && path.segments[0].ident == field.ident
68 && path.segments[0].args.is_none()
72 REDUNDANT_FIELD_NAMES,
74 "redundant field names in struct initialization",
76 field.ident.to_string(),
77 Applicability::MachineApplicable,
84 extract_msrv_attr!(EarlyContext);