Suggestion fixed, simplified lint logic.

This commit is contained in:
TomasKralCZ 2018-02-11 10:50:19 +01:00
parent 85642ddd23
commit 42120141bd
4 changed files with 23 additions and 33 deletions

View file

@ -1,9 +1,9 @@
use rustc::lint::*;
use rustc::hir::*;
use utils::{span_lint_and_sugg};
use utils::{span_lint_and_sugg, match_var};
/// **What it does:** Checks for redundnat field names where shorthands
/// can be used.
/// **What it does:** Checks for fields in struct literals where shorthands
/// could be used.
///
/// **Why is this bad?** If the field and variable names are the same,
/// the field name is redundant.
@ -23,7 +23,7 @@ use utils::{span_lint_and_sugg};
declare_lint! {
pub REDUNDANT_FIELD_NAMES,
Warn,
"using same name for field and variable ,where shorthand can be used"
"checks for fields in struct literals where shorthands could be used"
}
pub struct RedundantFieldNames;
@ -39,28 +39,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantFieldNames {
if let ExprStruct(_, ref fields, _) = expr.node {
for field in fields {
let name = field.name.node;
if let ExprPath(ref qpath) = field.expr.node {
if let &QPath::Resolved(_, ref path) = qpath {
let segments = &path.segments;
if segments.len() == 1 {
let expr_name = segments[0].name;
if name == expr_name {
span_lint_and_sugg(
cx,
REDUNDANT_FIELD_NAMES,
path.span,
"redundant field names in struct initialization",
&format!(
"replace '{0}: {0}' with '{0}'",
name,
),
"".to_string()
);
}
}
}
if match_var(&field.expr, name) && !field.is_shorthand {
span_lint_and_sugg (
cx,
REDUNDANT_FIELD_NAMES,
field.span,
"redundant field names in struct initialization",
"replace it with",
name.to_string()
);
}
}
}

View file

@ -29,7 +29,7 @@ impl ClippyCompilerCalls {
fn new(run_lints: bool) -> Self {
Self {
default: RustcDefaultCalls,
run_lints: run_lints,
run_lints,
}
}
}

View file

@ -8,7 +8,7 @@ mod foo {
struct Person {
gender: u8,
age: u8,
name: u8,
buzz: u64,
foo: u8,
}
@ -17,11 +17,13 @@ fn main() {
let gender: u8 = 42;
let age = 0;
let fizz: u64 = 0;
let name: u8 = 0;
let me = Person {
gender: gender,
age: age,
name, //should be ok
buzz: fizz, //should be ok
foo: foo::BAR, //should be ok
};

View file

@ -1,16 +1,16 @@
error: redundant field names in struct initialization
--> $DIR/redundant_field_names.rs:22:17
--> $DIR/redundant_field_names.rs:23:9
|
22 | gender: gender,
| ^^^^^^ help: replace 'gender: gender' with 'gender'
23 | gender: gender,
| ^^^^^^^^^^^^^^ help: replace it with: `gender`
|
= note: `-D redundant-field-names` implied by `-D warnings`
error: redundant field names in struct initialization
--> $DIR/redundant_field_names.rs:23:14
--> $DIR/redundant_field_names.rs:24:9
|
23 | age: age,
| ^^^ help: replace 'age: age' with 'age'
24 | age: age,
| ^^^^^^^^ help: replace it with: `age`
error: aborting due to 2 previous errors