1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
11 use crate::rustc::{declare_tool_lint, lint_array};
12 use crate::rustc_errors::Applicability;
13 use crate::syntax::ast::*;
14 use crate::utils::span_lint_and_sugg;
16 /// **What it does:** Checks for fields in struct literals where shorthands
19 /// **Why is this bad?** If the field and variable names are the same,
20 /// the field name is redundant.
22 /// **Known problems:** None.
26 /// let bar: u8 = 123;
32 /// let foo = Foo{ bar: bar }
34 /// the last line can be simplified to
36 /// let foo = Foo{ bar }
38 declare_clippy_lint! {
39 pub REDUNDANT_FIELD_NAMES,
41 "checks for fields in struct literals where shorthands could be used"
44 pub struct RedundantFieldNames;
46 impl LintPass for RedundantFieldNames {
47 fn get_lints(&self) -> LintArray {
48 lint_array!(REDUNDANT_FIELD_NAMES)
52 impl EarlyLintPass for RedundantFieldNames {
53 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
54 if let ExprKind::Struct(_, ref fields, _) = expr.node {
56 if field.is_shorthand {
59 if let ExprKind::Path(None, path) = &field.expr.node {
60 if path.segments.len() == 1
61 && path.segments[0].ident == field.ident
62 && path.segments[0].args.is_none()
66 REDUNDANT_FIELD_NAMES,
68 "redundant field names in struct initialization",
70 field.ident.to_string(),
71 Applicability::MachineApplicable,