Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions crates/ide-assists/src/handlers/convert_to_guarded_return.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,26 +75,17 @@ fn if_expr_to_guarded_return(

let let_chains = flat_let_chain(cond);

let then_block = if_expr.then_branch()?;
let then_block = then_block.stmt_list()?;
let then_branch = if_expr.then_branch()?;
let then_block = then_branch.stmt_list()?;

let parent_block = if_expr.syntax().parent()?.ancestors().find_map(ast::BlockExpr::cast)?;

if parent_block.tail_expr()? != if_expr.clone().into() {
return None;
}

// FIXME: This relies on untyped syntax tree and casts to much. It should be
// rewritten to use strongly-typed APIs.

// check for early return and continue
let first_in_then_block = then_block.syntax().first_child()?;
if ast::ReturnExpr::can_cast(first_in_then_block.kind())
|| ast::ContinueExpr::can_cast(first_in_then_block.kind())
|| first_in_then_block
.children()
.any(|x| ast::ReturnExpr::can_cast(x.kind()) || ast::ContinueExpr::can_cast(x.kind()))
{
if is_early_block(&then_block) || is_never_block(&ctx.sema, &then_branch) {
return None;
}

Expand Down Expand Up @@ -284,6 +275,17 @@ fn clean_stmt_block(block: &ast::BlockExpr) -> ast::BlockExpr {
}
}

fn is_early_block(then_block: &ast::StmtList) -> bool {
let is_early_expr =
|expr| matches!(expr, ast::Expr::ReturnExpr(_) | ast::Expr::ContinueExpr(_));
let into_expr = |stmt| match stmt {
ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
_ => None,
};
then_block.tail_expr().is_some_and(is_early_expr)
|| then_block.statements().filter_map(into_expr).any(is_early_expr)
}

#[cfg(test)]
mod tests {
use crate::tests::{check_assist, check_assist_not_applicable};
Expand Down