Merge pull request #20509 from A4-Tacks/fix-move-guard-to-arm-indent

Fix indent for move_guard_to_arm_body
This commit is contained in:
Shoyu Vanilla (Flint) 2025-08-26 05:52:06 +00:00 committed by GitHub
commit d86cf448c3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -40,28 +40,34 @@ pub(crate) fn move_guard_to_arm_body(acc: &mut Assists, ctx: &AssistContext<'_>)
return None;
}
let space_before_guard = guard.syntax().prev_sibling_or_token();
let space_after_arrow = match_arm.fat_arrow_token()?.next_sibling_or_token();
let guard_condition = guard.condition()?;
let guard_condition = guard.condition()?.reset_indent();
let arm_expr = match_arm.expr()?;
let if_expr =
make::expr_if(guard_condition, make::block_expr(None, Some(arm_expr.clone())), None)
.indent(arm_expr.indent_level());
let then_branch = make::block_expr(None, Some(arm_expr.reset_indent().indent(1.into())));
let if_expr = make::expr_if(guard_condition, then_branch, None).indent(arm_expr.indent_level());
let target = guard.syntax().text_range();
acc.add(
AssistId::refactor_rewrite("move_guard_to_arm_body"),
"Move guard to arm body",
target,
|edit| {
match space_before_guard {
Some(element) if element.kind() == WHITESPACE => {
edit.delete(element.text_range());
}
_ => (),
};
|builder| {
let mut edit = builder.make_editor(match_arm.syntax());
if let Some(element) = space_before_guard
&& element.kind() == WHITESPACE
{
edit.delete(element);
}
if let Some(element) = space_after_arrow
&& element.kind() == WHITESPACE
{
edit.replace(element, make::tokens::single_space());
}
edit.delete(guard.syntax().text_range());
edit.replace_ast(arm_expr, if_expr.into());
edit.delete(guard.syntax());
edit.replace(arm_expr.syntax(), if_expr.syntax());
builder.add_file_edits(ctx.vfs_file_id(), edit);
},
)
}
@ -298,6 +304,44 @@ fn main() {
);
}
#[test]
fn move_multiline_guard_to_arm_body_works() {
check_assist(
move_guard_to_arm_body,
r#"
fn main() {
match 92 {
x $0if true
&& true
&& true =>
{
{
false
}
},
_ => true
}
}
"#,
r#"
fn main() {
match 92 {
x => if true
&& true
&& true {
{
{
false
}
}
},
_ => true
}
}
"#,
);
}
#[test]
fn move_guard_to_arm_body_works_complex_match() {
check_assist(