Skip to content

Commit c22bb03

Browse files
committed
Auto merge of #15651 - rmehri01:15639_fix_inline_local_closure, r=lnicola
Fix inlining closures from local variables and functions Previously, closures were not properly wrapped in parentheses for the `inline_local_variable` and `inline_call` assists, leading to the usages being incorrectly called: ```rust fn main() { let $0f = || 2; let _ = f(); } ``` Now produces: ```rust fn main() { let _ = (|| 2)(); } ``` Instead of: ```rust fn main() { let _ = || 2(); } ``` Closes #15639
2 parents d6fef2c + ea11846 commit c22bb03

File tree

2 files changed

+49
-3
lines changed

2 files changed

+49
-3
lines changed

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

+30-1
Original file line numberDiff line numberDiff line change
@@ -481,8 +481,12 @@ fn inline(
481481
};
482482
body.reindent_to(original_indentation);
483483

484+
let no_stmts = body.statements().next().is_none();
484485
match body.tail_expr() {
485-
Some(expr) if !is_async_fn && body.statements().next().is_none() => expr,
486+
Some(expr) if matches!(expr, ast::Expr::ClosureExpr(_)) && no_stmts => {
487+
make::expr_paren(expr).clone_for_update()
488+
}
489+
Some(expr) if !is_async_fn && no_stmts => expr,
486490
_ => match node
487491
.syntax()
488492
.parent()
@@ -1471,6 +1475,31 @@ fn main() {
14711475
}
14721476
});
14731477
}
1478+
"#,
1479+
);
1480+
}
1481+
1482+
#[test]
1483+
fn inline_call_closure_body() {
1484+
check_assist(
1485+
inline_call,
1486+
r#"
1487+
fn f() -> impl Fn() -> i32 {
1488+
|| 2
1489+
}
1490+
1491+
fn main() {
1492+
let _ = $0f()();
1493+
}
1494+
"#,
1495+
r#"
1496+
fn f() -> impl Fn() -> i32 {
1497+
|| 2
1498+
}
1499+
1500+
fn main() {
1501+
let _ = (|| 2)();
1502+
}
14741503
"#,
14751504
);
14761505
}

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

+19-2
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,7 @@ pub(crate) fn inline_local_variable(acc: &mut Assists, ctx: &AssistContext<'_>)
9696
);
9797
let parent = matches!(
9898
usage_parent,
99-
ast::Expr::CallExpr(_)
100-
| ast::Expr::TupleExpr(_)
99+
ast::Expr::TupleExpr(_)
101100
| ast::Expr::ArrayExpr(_)
102101
| ast::Expr::ParenExpr(_)
103102
| ast::Expr::ForExpr(_)
@@ -949,6 +948,24 @@ fn f() {
949948
let S$0 = S;
950949
S;
951950
}
951+
"#,
952+
);
953+
}
954+
955+
#[test]
956+
fn test_inline_closure() {
957+
check_assist(
958+
inline_local_variable,
959+
r#"
960+
fn main() {
961+
let $0f = || 2;
962+
let _ = f();
963+
}
964+
"#,
965+
r#"
966+
fn main() {
967+
let _ = (|| 2)();
968+
}
952969
"#,
953970
);
954971
}

0 commit comments

Comments
 (0)