Skip to content

Commit 9d0ccf0

Browse files
committed
Auto merge of #15597 - rmehri01:fix_promote_local_field_shorthand, r=HKalbasi
Field shorthand overwritten in promote local to const assist Currently, running `promote_local_to_const` on the following: ```rust struct Foo { bar: usize, } fn main() { let $0bar = 0; let foo = Foo { bar }; } ``` Results in: ```rust struct Foo { bar: usize, } fn main() { const BAR: usize = 0; let foo = Foo { BAR }; } ``` But instead should be something like: ```rust struct Foo { bar: usize, } fn main() { const BAR: usize = 0; let foo = Foo { bar: BAR }; } ```
2 parents 12e28c3 + cd0a89a commit 9d0ccf0

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

crates/ide-assists/src/handlers/promote_local_to_const.rs

+37-3
Original file line numberDiff line numberDiff line change
@@ -76,12 +76,19 @@ pub(crate) fn promote_local_to_const(acc: &mut Assists, ctx: &AssistContext<'_>)
7676
let name = to_upper_snake_case(&name.to_string());
7777
let usages = Definition::Local(local).usages(&ctx.sema).all();
7878
if let Some(usages) = usages.references.get(&ctx.file_id()) {
79-
let name = make::name_ref(&name);
79+
let name_ref = make::name_ref(&name);
8080

8181
for usage in usages {
8282
let Some(usage) = usage.name.as_name_ref().cloned() else { continue };
83-
let usage = edit.make_mut(usage);
84-
ted::replace(usage.syntax(), name.clone_for_update().syntax());
83+
if let Some(record_field) = ast::RecordExprField::for_name_ref(&usage) {
84+
let record_field = edit.make_mut(record_field);
85+
let name_expr =
86+
make::expr_path(make::path_from_text(&name)).clone_for_update();
87+
record_field.replace_expr(name_expr);
88+
} else {
89+
let usage = edit.make_mut(usage);
90+
ted::replace(usage.syntax(), name_ref.clone_for_update().syntax());
91+
}
8592
}
8693
}
8794

@@ -178,6 +185,33 @@ fn foo() {
178185
);
179186
}
180187

188+
#[test]
189+
fn usage_in_field_shorthand() {
190+
check_assist(
191+
promote_local_to_const,
192+
r"
193+
struct Foo {
194+
bar: usize,
195+
}
196+
197+
fn main() {
198+
let $0bar = 0;
199+
let foo = Foo { bar };
200+
}
201+
",
202+
r"
203+
struct Foo {
204+
bar: usize,
205+
}
206+
207+
fn main() {
208+
const $0BAR: usize = 0;
209+
let foo = Foo { bar: BAR };
210+
}
211+
",
212+
)
213+
}
214+
181215
#[test]
182216
fn not_applicable_non_const_meth_call() {
183217
cov_mark::check!(promote_local_non_const);

0 commit comments

Comments
 (0)