feat: handle while let to loop

This commit is contained in:
rainy-me 2021-12-04 03:19:19 +09:00
parent 8dd06ece20
commit fb90bf9cad

View file

@ -39,17 +39,14 @@ use crate::{
// ```
pub(crate) fn convert_while_to_loop(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
let while_kw = ctx.find_token_syntax_at_offset(T![while])?;
let while_expr: ast::WhileExpr = while_kw.parent().and_then(ast::WhileExpr::cast)?;
let while_expr = while_kw.parent().and_then(ast::WhileExpr::cast)?;
let while_body = while_expr.loop_body()?;
let cond = while_expr.condition()?;
let while_cond = while_expr.condition()?;
// Don't handle while let
if cond.pat().is_some() {
return None;
let if_cond = match while_cond.pat() {
Some(_) => while_expr.condition()?,
None => make::condition(invert_boolean_expression(while_cond.expr()?), None),
};
let cond_expr = cond.expr()?;
let target = while_expr.syntax().text_range();
acc.add(
AssistId("convert_while_to_loop", AssistKind::RefactorRewrite),
@ -58,27 +55,24 @@ pub(crate) fn convert_while_to_loop(acc: &mut Assists, ctx: &AssistContext) -> O
|edit| {
let while_indent_level = IndentLevel::from_node(while_expr.syntax());
let replacement = {
let if_expr = {
let cond = invert_boolean_expression(cond_expr);
let then_branch = make::block_expr(
once(make::expr_stmt(make::expr_break(None)).into()),
None,
);
make::expr_if(make::condition(cond, None), then_branch, None)
};
let if_expr = if_expr.indent(while_indent_level);
let stmts = once(make::expr_stmt(if_expr).into()).chain(while_body.statements());
let block_expr = make::block_expr(stmts, while_body.tail_expr());
let block_expr = block_expr.indent(while_indent_level);
make::expr_loop(block_expr)
let break_block =
make::block_expr(once(make::expr_stmt(make::expr_break(None)).into()), None)
.indent(while_indent_level);
let block_expr = match while_cond.pat() {
Some(_) => {
let if_expr = make::expr_if(if_cond, while_body, Some(break_block.into()));
let stmts = once(make::expr_stmt(if_expr).into());
make::block_expr(stmts, None)
}
None => {
let if_expr = make::expr_if(if_cond, break_block, None);
let stmts =
once(make::expr_stmt(if_expr).into()).chain(while_body.statements());
make::block_expr(stmts, while_body.tail_expr())
}
};
let replacement = make::expr_loop(block_expr.indent(while_indent_level));
edit.replace(target, replacement.syntax().text())
},
)
@ -160,8 +154,8 @@ fn main() {
}
#[test]
fn ignore_while_let() {
check_assist_not_applicable(
fn convert_while_let() {
check_assist(
convert_while_to_loop,
r#"
fn main() {
@ -169,6 +163,17 @@ fn main() {
bar();
}
}
"#,
r#"
fn main() {
loop {
if let Some(_) = foo() {
bar();
} else {
break;
}
}
}
"#,
);
}