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};
9 /// **What it does:** Checks for fields in struct literals where shorthands
12 /// **Why is this bad?** If the field and variable names are the same,
13 /// the field name is redundant.
15 /// **Known problems:** None.
19 /// let bar: u8 = 123;
25 /// let foo = Foo { bar: bar };
27 /// the last line can be simplified to
29 /// let foo = Foo { bar };
31 pub REDUNDANT_FIELD_NAMES,
33 "checks for fields in struct literals where shorthands could be used"
36 declare_lint_pass!(RedundantFieldNames => [REDUNDANT_FIELD_NAMES]);
38 impl EarlyLintPass for RedundantFieldNames {
39 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
40 if in_external_macro(cx.sess, expr.span) {
43 if let ExprKind::Struct(_, ref fields, _) = expr.kind {
45 if field.is_shorthand {
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()
55 REDUNDANT_FIELD_NAMES,
57 "redundant field names in struct initialization",
59 field.ident.to_string(),
60 Applicability::MachineApplicable,