Skip to content

Commit c1d08b5

Browse files
committed
Auto merge of rust-lang#17588 - CamWass:more-rename, r=Veykril
feat: Add incorrect case diagnostics for enum variant fields and all variables/params Updates the incorrect case diagnostic to check: 1. Fields of enum variants. Example: ```rust enum Foo { Variant { nonSnake: u8 } } ``` 2. All variable bindings, instead of just let bindings and certain match arm patters. Examples: ```rust match 1 { nonSnake => () } match 1 { nonSnake @ 1 => () } match 1 { nonSnake1 @ nonSnake2 => () } // slightly cursed, but these both introduce new // bindings that are bound to the same value. const ONE: i32 = 1; match 1 { nonSnake @ ONE } // ONE is ignored since it is not a binding match Some(1) { Some(nonSnake) => () } struct Foo { field: u8 } match (Foo { field: 1 } ) { Foo { field: nonSnake } => (); } struct Foo { nonSnake: u8 } // diagnostic here, at definition match (Foo { nonSnake: 1 } ) { // no diagnostic here... Foo { nonSnake } => (); // ...or here, since these are not where the name is introduced } for nonSnake in [] {} struct Foo(u8); for Foo(nonSnake) in [] {} ``` 3. All parameter bindings, instead of just top-level binding identifiers. Examples: ```rust fn func(nonSnake: u8) {} // worked before struct Foo { field: u8 } fn func(Foo { field: nonSnake }: Foo) {} // now get diagnostic for nonSnake ``` This is accomplished by changing the way binding identifier patterns are filtered: - Previously, all binding idents were skipped, except a few classes of "good" binding locations that were checked. - Now, all binding idents are checked, except field shorthands which are skipped. Moving from a whitelist to a blacklist potentially makes the analysis more brittle: If new pattern types are added in the future where ident pats don't introduce new names, then they may incorrectly create diagnostics. But the benefit of the blacklist approach is simplicity: I think a whitelist approach would need to recursively visit patterns to collect renaming candidates?
2 parents 82d0187 + 6351a20 commit c1d08b5

File tree

3 files changed

+194
-31
lines changed

3 files changed

+194
-31
lines changed

src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/decl_check.rs

+83-10
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ use std::fmt;
1717

1818
use hir_def::{
1919
data::adt::VariantData, db::DefDatabase, hir::Pat, src::HasSource, AdtId, AttrDefId, ConstId,
20-
EnumId, FunctionId, ItemContainerId, Lookup, ModuleDefId, ModuleId, StaticId, StructId,
21-
TraitId, TypeAliasId,
20+
EnumId, EnumVariantId, FunctionId, ItemContainerId, Lookup, ModuleDefId, ModuleId, StaticId,
21+
StructId, TraitId, TypeAliasId,
2222
};
2323
use hir_expand::{
2424
name::{AsName, Name},
@@ -353,17 +353,16 @@ impl<'a> DeclValidator<'a> {
353353
continue;
354354
};
355355

356-
let is_param = ast::Param::can_cast(parent.kind());
357-
// We have to check that it's either `let var = ...` or `var @ Variant(_)` statement,
358-
// because e.g. match arms are patterns as well.
359-
// In other words, we check that it's a named variable binding.
360-
let is_binding = ast::LetStmt::can_cast(parent.kind())
361-
|| (ast::MatchArm::can_cast(parent.kind()) && ident_pat.at_token().is_some());
362-
if !(is_param || is_binding) {
363-
// This pattern is not an actual variable declaration, e.g. `Some(val) => {..}` match arm.
356+
let is_shorthand = ast::RecordPatField::cast(parent.clone())
357+
.map(|parent| parent.name_ref().is_none())
358+
.unwrap_or_default();
359+
if is_shorthand {
360+
// We don't check shorthand field patterns, such as 'field' in `Thing { field }`,
361+
// since the shorthand isn't the declaration.
364362
continue;
365363
}
366364

365+
let is_param = ast::Param::can_cast(parent.kind());
367366
let ident_type = if is_param { IdentType::Parameter } else { IdentType::Variable };
368367

369368
self.create_incorrect_case_diagnostic_for_ast_node(
@@ -489,6 +488,11 @@ impl<'a> DeclValidator<'a> {
489488
/// Check incorrect names for enum variants.
490489
fn validate_enum_variants(&mut self, enum_id: EnumId) {
491490
let data = self.db.enum_data(enum_id);
491+
492+
for (variant_id, _) in data.variants.iter() {
493+
self.validate_enum_variant_fields(*variant_id);
494+
}
495+
492496
let mut enum_variants_replacements = data
493497
.variants
494498
.iter()
@@ -551,6 +555,75 @@ impl<'a> DeclValidator<'a> {
551555
}
552556
}
553557

558+
/// Check incorrect names for fields of enum variant.
559+
fn validate_enum_variant_fields(&mut self, variant_id: EnumVariantId) {
560+
let variant_data = self.db.enum_variant_data(variant_id);
561+
let VariantData::Record(fields) = variant_data.variant_data.as_ref() else {
562+
return;
563+
};
564+
let mut variant_field_replacements = fields
565+
.iter()
566+
.filter_map(|(_, field)| {
567+
to_lower_snake_case(&field.name.to_smol_str()).map(|new_name| Replacement {
568+
current_name: field.name.clone(),
569+
suggested_text: new_name,
570+
expected_case: CaseType::LowerSnakeCase,
571+
})
572+
})
573+
.peekable();
574+
575+
// XXX: only look at sources if we do have incorrect names
576+
if variant_field_replacements.peek().is_none() {
577+
return;
578+
}
579+
580+
let variant_loc = variant_id.lookup(self.db.upcast());
581+
let variant_src = variant_loc.source(self.db.upcast());
582+
583+
let Some(ast::FieldList::RecordFieldList(variant_fields_list)) =
584+
variant_src.value.field_list()
585+
else {
586+
always!(
587+
variant_field_replacements.peek().is_none(),
588+
"Replacements ({:?}) were generated for an enum variant \
589+
which had no fields list: {:?}",
590+
variant_field_replacements.collect::<Vec<_>>(),
591+
variant_src
592+
);
593+
return;
594+
};
595+
let mut variant_variants_iter = variant_fields_list.fields();
596+
for field_replacement in variant_field_replacements {
597+
// We assume that parameters in replacement are in the same order as in the
598+
// actual params list, but just some of them (ones that named correctly) are skipped.
599+
let field = loop {
600+
if let Some(field) = variant_variants_iter.next() {
601+
let Some(field_name) = field.name() else {
602+
continue;
603+
};
604+
if field_name.as_name() == field_replacement.current_name {
605+
break field;
606+
}
607+
} else {
608+
never!(
609+
"Replacement ({:?}) was generated for an enum variant field \
610+
which was not found: {:?}",
611+
field_replacement,
612+
variant_src
613+
);
614+
return;
615+
}
616+
};
617+
618+
self.create_incorrect_case_diagnostic_for_ast_node(
619+
field_replacement,
620+
variant_src.file_id,
621+
&field,
622+
IdentType::Field,
623+
);
624+
}
625+
}
626+
554627
fn validate_const(&mut self, const_id: ConstId) {
555628
let container = const_id.lookup(self.db.upcast()).container;
556629
if self.is_trait_impl_container(container) {

src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/incorrect_case.rs

+109-19
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,7 @@ impl someStruct {
332332
check_diagnostics(
333333
r#"
334334
enum Option { Some, None }
335+
use Option::{Some, None};
335336
336337
#[allow(unused)]
337338
fn main() {
@@ -344,24 +345,6 @@ fn main() {
344345
);
345346
}
346347

347-
#[test]
348-
fn non_let_bind() {
349-
check_diagnostics(
350-
r#"
351-
enum Option { Some, None }
352-
353-
#[allow(unused)]
354-
fn main() {
355-
match Option::None {
356-
SOME_VAR @ None => (),
357-
// ^^^^^^^^ 💡 warn: Variable `SOME_VAR` should have snake_case name, e.g. `some_var`
358-
Some => (),
359-
}
360-
}
361-
"#,
362-
);
363-
}
364-
365348
#[test]
366349
fn allow_attributes_crate_attr() {
367350
check_diagnostics(
@@ -427,7 +410,12 @@ fn qualify() {
427410

428411
#[test] // Issue #8809.
429412
fn parenthesized_parameter() {
430-
check_diagnostics(r#"fn f((O): _) { _ = O; }"#)
413+
check_diagnostics(
414+
r#"
415+
fn f((_O): u8) {}
416+
// ^^ 💡 warn: Variable `_O` should have snake_case name, e.g. `_o`
417+
"#,
418+
)
431419
}
432420

433421
#[test]
@@ -766,4 +754,106 @@ mod Foo;
766754
"#,
767755
)
768756
}
757+
758+
#[test]
759+
fn test_field_shorthand() {
760+
check_diagnostics(
761+
r#"
762+
struct Foo { _nonSnake: u8 }
763+
// ^^^^^^^^^ 💡 warn: Field `_nonSnake` should have snake_case name, e.g. `_non_snake`
764+
fn func(Foo { _nonSnake }: Foo) {}
765+
"#,
766+
);
767+
}
768+
769+
#[test]
770+
fn test_match() {
771+
check_diagnostics(
772+
r#"
773+
enum Foo { Variant { nonSnake1: u8 } }
774+
// ^^^^^^^^^ 💡 warn: Field `nonSnake1` should have snake_case name, e.g. `non_snake1`
775+
fn func() {
776+
match (Foo::Variant { nonSnake1: 1 }) {
777+
Foo::Variant { nonSnake1: _nonSnake2 } => {},
778+
// ^^^^^^^^^^ 💡 warn: Variable `_nonSnake2` should have snake_case name, e.g. `_non_snake2`
779+
}
780+
}
781+
"#,
782+
);
783+
784+
check_diagnostics(
785+
r#"
786+
struct Foo(u8);
787+
788+
fn func() {
789+
match Foo(1) {
790+
Foo(_nonSnake) => {},
791+
// ^^^^^^^^^ 💡 warn: Variable `_nonSnake` should have snake_case name, e.g. `_non_snake`
792+
}
793+
}
794+
"#,
795+
);
796+
797+
check_diagnostics(
798+
r#"
799+
fn main() {
800+
match 1 {
801+
_Bad1 @ _Bad2 => {}
802+
// ^^^^^ 💡 warn: Variable `_Bad1` should have snake_case name, e.g. `_bad1`
803+
// ^^^^^ 💡 warn: Variable `_Bad2` should have snake_case name, e.g. `_bad2`
804+
}
805+
}
806+
"#,
807+
);
808+
check_diagnostics(
809+
r#"
810+
fn main() {
811+
match 1 { _Bad1 => () }
812+
// ^^^^^ 💡 warn: Variable `_Bad1` should have snake_case name, e.g. `_bad1`
813+
}
814+
"#,
815+
);
816+
817+
check_diagnostics(
818+
r#"
819+
enum Foo { V1, V2 }
820+
use Foo::V1;
821+
822+
fn main() {
823+
match V1 {
824+
_Bad1 @ V1 => {},
825+
// ^^^^^ 💡 warn: Variable `_Bad1` should have snake_case name, e.g. `_bad1`
826+
Foo::V2 => {}
827+
}
828+
}
829+
"#,
830+
);
831+
}
832+
833+
#[test]
834+
fn test_for_loop() {
835+
check_diagnostics(
836+
r#"
837+
//- minicore: iterators
838+
fn func() {
839+
for _nonSnake in [] {}
840+
// ^^^^^^^^^ 💡 warn: Variable `_nonSnake` should have snake_case name, e.g. `_non_snake`
841+
}
842+
"#,
843+
);
844+
845+
check_fix(
846+
r#"
847+
//- minicore: iterators
848+
fn func() {
849+
for nonSnake$0 in [] { nonSnake; }
850+
}
851+
"#,
852+
r#"
853+
fn func() {
854+
for non_snake in [] { non_snake; }
855+
}
856+
"#,
857+
);
858+
}
769859
}

src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_match_arms.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -608,8 +608,8 @@ fn main() {
608608
// `Never` is deliberately not defined so that it's an uninferred type.
609609
// We ignore these to avoid triggering bugs in the analysis.
610610
match Option::<Never>::None {
611-
None => (),
612-
Some(never) => match never {},
611+
Option::None => (),
612+
Option::Some(never) => match never {},
613613
}
614614
match Option::<Never>::None {
615615
Option::Some(_never) => {},

0 commit comments

Comments
 (0)