Unnamed repository; edit this file 'description' to name the repository.
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 }; } ```
bors 2023-09-16
parent 12e28c3 · parent cd0a89a · commit 9d0ccf0
-rw-r--r--crates/ide-assists/src/handlers/promote_local_to_const.rs40
1 files changed, 37 insertions, 3 deletions
diff --git a/crates/ide-assists/src/handlers/promote_local_to_const.rs b/crates/ide-assists/src/handlers/promote_local_to_const.rs
index 6fc2aa4997..6ed9bd85fc 100644
--- a/crates/ide-assists/src/handlers/promote_local_to_const.rs
+++ b/crates/ide-assists/src/handlers/promote_local_to_const.rs
@@ -76,12 +76,19 @@ pub(crate) fn promote_local_to_const(acc: &mut Assists, ctx: &AssistContext<'_>)
let name = to_upper_snake_case(&name.to_string());
let usages = Definition::Local(local).usages(&ctx.sema).all();
if let Some(usages) = usages.references.get(&ctx.file_id()) {
- let name = make::name_ref(&name);
+ let name_ref = make::name_ref(&name);
for usage in usages {
let Some(usage) = usage.name.as_name_ref().cloned() else { continue };
- let usage = edit.make_mut(usage);
- ted::replace(usage.syntax(), name.clone_for_update().syntax());
+ if let Some(record_field) = ast::RecordExprField::for_name_ref(&usage) {
+ let record_field = edit.make_mut(record_field);
+ let name_expr =
+ make::expr_path(make::path_from_text(&name)).clone_for_update();
+ record_field.replace_expr(name_expr);
+ } else {
+ let usage = edit.make_mut(usage);
+ ted::replace(usage.syntax(), name_ref.clone_for_update().syntax());
+ }
}
}
@@ -179,6 +186,33 @@ fn foo() {
}
#[test]
+ fn usage_in_field_shorthand() {
+ check_assist(
+ promote_local_to_const,
+ r"
+struct Foo {
+ bar: usize,
+}
+
+fn main() {
+ let $0bar = 0;
+ let foo = Foo { bar };
+}
+",
+ r"
+struct Foo {
+ bar: usize,
+}
+
+fn main() {
+ const $0BAR: usize = 0;
+ let foo = Foo { bar: BAR };
+}
+",
+ )
+ }
+
+ #[test]
fn not_applicable_non_const_meth_call() {
cov_mark::check!(promote_local_non_const);
check_assist_not_applicable(