Merge #4857
4857: Fix invalid shorthand initialization diagnostic for tuple structs r=jonas-schievink a=OptimalStrategy
Initializing tuple structs explicitly, like in the example below, produces a "Shorthand struct initialization" diagnostic that leads to a compilation error when applied:
```rust
struct S(usize);
fn main() {
let s = S { 0: 0 }; // OK, but triggers the diagnostic
// let s = S { 0 }; // Compilation error
}
```
This PR adds a check that the field name is not a literal.
Co-authored-by: OptimalStrategy <george@usan-podgornov.com>
Co-authored-by: OptimalStrategy <17456182+OptimalStrategy@users.noreply.github.com>
This commit is contained in:
commit
b56ad148db
1 changed files with 14 additions and 1 deletions
|
|
@ -187,7 +187,8 @@ fn check_struct_shorthand_initialization(
|
|||
if let (Some(name_ref), Some(expr)) = (record_field.name_ref(), record_field.expr()) {
|
||||
let field_name = name_ref.syntax().text().to_string();
|
||||
let field_expr = expr.syntax().text().to_string();
|
||||
if field_name == field_expr {
|
||||
let field_name_is_tup_index = name_ref.as_tuple_field().is_some();
|
||||
if field_name == field_expr && !field_name_is_tup_index {
|
||||
let mut edit_builder = TextEditBuilder::default();
|
||||
edit_builder.delete(record_field.syntax().text_range());
|
||||
edit_builder.insert(record_field.syntax().text_range().start(), field_name);
|
||||
|
|
@ -719,6 +720,18 @@ mod tests {
|
|||
"#,
|
||||
check_struct_shorthand_initialization,
|
||||
);
|
||||
check_not_applicable(
|
||||
r#"
|
||||
struct A(usize);
|
||||
|
||||
fn main() {
|
||||
A {
|
||||
0: 0
|
||||
}
|
||||
}
|
||||
"#,
|
||||
check_struct_shorthand_initialization,
|
||||
);
|
||||
|
||||
check_apply(
|
||||
r#"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue