Skip to content

Commit f79f3db

Browse files
bors[bot]weirane
andauthored
Merge #11030
11030: Add comma for "move if to guard" r=Veykril a=weirane As I mentioned in #11017, there is a little issue in the implementation for if branch. This code ```rust let y = match 92 { x => { if x == 0 {$0 false } } _ => true, }; ``` will be transformed to ```rust let y = match 92 { x if x == 0 => false _ => true, }; ``` a comma is missing after the false. I moved the fix from the code handling else branch to above. Co-authored-by: Wang Ruochen <[email protected]>
2 parents 098b1f2 + ee07956 commit f79f3db

File tree

1 file changed

+37
-8
lines changed

1 file changed

+37
-8
lines changed

crates/ide_assists/src/handlers/move_guard.rs

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,15 @@ pub(crate) fn move_arm_cond_to_match_guard(acc: &mut Assists, ctx: &AssistContex
135135

136136
match &then_block.tail_expr() {
137137
Some(then_expr) if then_only_expr => {
138-
edit.replace(replace_node.text_range(), then_expr.syntax().text())
138+
edit.replace(replace_node.text_range(), then_expr.syntax().text());
139+
// Insert comma for expression if there isn't one
140+
match match_arm.syntax().last_child_or_token() {
141+
Some(NodeOrToken::Token(t)) if t.kind() == COMMA => {}
142+
_ => {
143+
cov_mark::hit!(move_guard_if_add_comma);
144+
edit.insert(match_arm.syntax().text_range().end(), ",");
145+
}
146+
}
139147
}
140148
_ if replace_node != *if_expr.syntax() => {
141149
// Dedent because if_expr is in a BlockExpr
@@ -150,13 +158,6 @@ pub(crate) fn move_arm_cond_to_match_guard(acc: &mut Assists, ctx: &AssistContex
150158
// If with only an else branch
151159
if let Some(ElseBranch::Block(else_block)) = if_expr.else_branch() {
152160
let then_arm_end = match_arm.syntax().text_range().end();
153-
if then_block.tail_expr().is_some() && then_only_expr {
154-
// Insert comma for expression if there isn't one
155-
match match_arm.syntax().last_child_or_token() {
156-
Some(NodeOrToken::Token(t)) if t.kind() == COMMA => {}
157-
_ => edit.insert(then_arm_end, ","),
158-
}
159-
}
160161
let else_only_expr = else_block.statements().next().is_none();
161162
let indent_level = match_arm.indent_level();
162163
let spaces = " ".repeat(indent_level.0 as _);
@@ -318,6 +319,34 @@ fn main() {
318319
);
319320
}
320321

322+
#[test]
323+
fn move_arm_cond_in_block_to_match_guard_add_comma_works() {
324+
cov_mark::check!(move_guard_if_add_comma);
325+
check_assist(
326+
move_arm_cond_to_match_guard,
327+
r#"
328+
fn main() {
329+
match 92 {
330+
x => {
331+
$0if x > 10 {
332+
false
333+
}
334+
}
335+
_ => true
336+
}
337+
}
338+
"#,
339+
r#"
340+
fn main() {
341+
match 92 {
342+
x if x > 10 => false,
343+
_ => true
344+
}
345+
}
346+
"#,
347+
);
348+
}
349+
321350
#[test]
322351
fn move_arm_cond_to_match_guard_if_let_not_works() {
323352
check_assist_not_applicable(

0 commit comments

Comments
 (0)