Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 2a7ec0b

Browse files
Consider all expressions that autoderef in "Extract variable", not just method and field accesses.
1 parent 248a557 commit 2a7ec0b

File tree

1 file changed

+48
-3
lines changed

1 file changed

+48
-3
lines changed

src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_variable.rs

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,15 @@ pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
5858
}
5959

6060
let parent = to_extract.syntax().parent().and_then(ast::Expr::cast);
61-
let needs_adjust = parent
62-
.as_ref()
63-
.map_or(false, |it| matches!(it, ast::Expr::FieldExpr(_) | ast::Expr::MethodCallExpr(_)));
61+
// Any expression that autoderefs may need adjustment.
62+
let needs_adjust = parent.as_ref().map_or(false, |it| match it {
63+
ast::Expr::FieldExpr(_)
64+
| ast::Expr::MethodCallExpr(_)
65+
| ast::Expr::CallExpr(_)
66+
| ast::Expr::AwaitExpr(_) => true,
67+
ast::Expr::IndexExpr(index) if index.base().as_ref() == Some(&to_extract) => true,
68+
_ => false,
69+
});
6470

6571
let anchor = Anchor::from(&to_extract)?;
6672
let target = to_extract.syntax().text_range();
@@ -1220,6 +1226,45 @@ fn foo(s: &S) {
12201226
);
12211227
}
12221228

1229+
#[test]
1230+
fn test_extract_var_index_deref() {
1231+
check_assist(
1232+
extract_variable,
1233+
r#"
1234+
//- minicore: index
1235+
struct X;
1236+
1237+
impl std::ops::Index<usize> for X {
1238+
type Output = i32;
1239+
fn index(&self) -> &Self::Output { 0 }
1240+
}
1241+
1242+
struct S {
1243+
sub: X
1244+
}
1245+
1246+
fn foo(s: &S) {
1247+
$0s.sub$0[0];
1248+
}"#,
1249+
r#"
1250+
struct X;
1251+
1252+
impl std::ops::Index<usize> for X {
1253+
type Output = i32;
1254+
fn index(&self) -> &Self::Output { 0 }
1255+
}
1256+
1257+
struct S {
1258+
sub: X
1259+
}
1260+
1261+
fn foo(s: &S) {
1262+
let $0sub = &s.sub;
1263+
sub[0];
1264+
}"#,
1265+
);
1266+
}
1267+
12231268
#[test]
12241269
fn test_extract_var_reference_parameter_deep_nesting() {
12251270
check_assist(

0 commit comments

Comments
 (0)