Skip to content

Commit

Permalink
Merge pull request #18855 from Giga-Bowser/migrate-if-let
Browse files Browse the repository at this point in the history
internal: Migrate `if let` replacement assists to `SyntaxEditor`
  • Loading branch information
Veykril authored Jan 8, 2025
2 parents f2a7136 + 54d9b5a commit 1e975d6
Show file tree
Hide file tree
Showing 23 changed files with 433 additions and 154 deletions.
12 changes: 4 additions & 8 deletions crates/ide-assists/src/handlers/add_missing_match_arms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
!hidden
})
.map(|(pat, _)| {
make::match_arm(iter::once(pat), None, make::ext::expr_todo())
.clone_for_update()
make::match_arm(pat, None, make::ext::expr_todo()).clone_for_update()
});

let catch_all_arm = new_match_arm_list
Expand Down Expand Up @@ -243,12 +242,9 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)

if needs_catch_all_arm && !has_catch_all_arm {
cov_mark::hit!(added_wildcard_pattern);
let arm = make::match_arm(
iter::once(make::wildcard_pat().into()),
None,
make::ext::expr_todo(),
)
.clone_for_update();
let arm =
make::match_arm(make::wildcard_pat().into(), None, make::ext::expr_todo())
.clone_for_update();
todo_placeholders.push(arm.expr().unwrap());
added_arms.push(arm);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ide-assists/src/handlers/apply_demorgan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ fn tail_cb_impl(edit: &mut SourceChangeBuilder, e: &ast::Expr) {

/// Add bang and parentheses to the expression.
fn add_bang_paren(expr: ast::Expr) -> ast::Expr {
make::expr_prefix(T![!], make::expr_paren(expr))
make::expr_prefix(T![!], make::expr_paren(expr)).into()
}

#[cfg(test)]
Expand Down
1 change: 1 addition & 0 deletions crates/ide-assists/src/handlers/bool_to_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ fn bool_expr_to_enum_expr(expr: ast::Expr) -> ast::Expr {
make::tail_only_block_expr(true_expr),
Some(ast::ElseBranch::Block(make::tail_only_block_expr(false_expr))),
)
.into()
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/ide-assists/src/handlers/convert_closure_to_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ fn wrap_capture_in_deref_if_needed(
if does_autoderef {
return capture_name;
}
make::expr_prefix(T![*], capture_name)
make::expr_prefix(T![*], capture_name).into()
}

fn capture_as_arg(ctx: &AssistContext<'_>, capture: &ClosureCapture) -> ast::Expr {
Expand Down
2 changes: 1 addition & 1 deletion crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ pub(crate) fn convert_from_to_tryfrom(acc: &mut Assists, ctx: &AssistContext<'_>
);

for r in return_exprs {
let t = r.expr().unwrap_or_else(make::expr_unit);
let t = r.expr().unwrap_or_else(make::ext::expr_unit);
ted::replace(t.syntax(), wrap_ok(t.clone()).syntax().clone_for_update());
}

Expand Down
2 changes: 1 addition & 1 deletion crates/ide-assists/src/handlers/convert_while_to_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ pub(crate) fn convert_while_to_loop(acc: &mut Assists, ctx: &AssistContext<'_>)
.indent(while_indent_level);
let block_expr = if is_pattern_cond(while_cond.clone()) {
let if_expr = make::expr_if(while_cond, while_body, Some(break_block.into()));
let stmts = iter::once(make::expr_stmt(if_expr).into());
let stmts = iter::once(make::expr_stmt(if_expr.into()).into());
make::block_expr(stmts, None)
} else {
let if_cond = invert_boolean_expression(while_cond);
Expand Down
36 changes: 16 additions & 20 deletions crates/ide-assists/src/handlers/extract_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1533,7 +1533,7 @@ impl FlowHandler {
.into(),
call_expr,
);
make::expr_if(condition.into(), block, None)
make::expr_if(condition.into(), block, None).into()
}
FlowHandler::IfOption { action } => {
let path = make::ext::ident_path("Some");
Expand All @@ -1544,7 +1544,7 @@ impl FlowHandler {
let action_expr = action.make_result_handler(Some(value));
let action_stmt = make::expr_stmt(action_expr);
let then = make::block_expr(iter::once(action_stmt.into()), None);
make::expr_if(cond.into(), then, None)
make::expr_if(cond.into(), then, None).into()
}
FlowHandler::MatchOption { none } => {
let some_name = "value";
Expand All @@ -1554,15 +1554,15 @@ impl FlowHandler {
let value_pat = make::ext::simple_ident_pat(make::name(some_name));
let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
let value = make::expr_path(make::ext::ident_path(some_name));
make::match_arm(iter::once(pat.into()), None, value)
make::match_arm(pat.into(), None, value)
};
let none_arm = {
let path = make::ext::ident_path("None");
let pat = make::path_pat(path);
make::match_arm(iter::once(pat), None, none.make_result_handler(None))
make::match_arm(pat, None, none.make_result_handler(None))
};
let arms = make::match_arm_list(vec![some_arm, none_arm]);
make::expr_match(call_expr, arms)
make::expr_match(call_expr, arms).into()
}
FlowHandler::MatchResult { err } => {
let ok_name = "value";
Expand All @@ -1573,21 +1573,17 @@ impl FlowHandler {
let value_pat = make::ext::simple_ident_pat(make::name(ok_name));
let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
let value = make::expr_path(make::ext::ident_path(ok_name));
make::match_arm(iter::once(pat.into()), None, value)
make::match_arm(pat.into(), None, value)
};
let err_arm = {
let path = make::ext::ident_path("Err");
let value_pat = make::ext::simple_ident_pat(make::name(err_name));
let pat = make::tuple_struct_pat(path, iter::once(value_pat.into()));
let value = make::expr_path(make::ext::ident_path(err_name));
make::match_arm(
iter::once(pat.into()),
None,
err.make_result_handler(Some(value)),
)
make::match_arm(pat.into(), None, err.make_result_handler(Some(value)))
};
let arms = make::match_arm_list(vec![ok_arm, err_arm]);
make::expr_match(call_expr, arms)
make::expr_match(call_expr, arms).into()
}
}
}
Expand Down Expand Up @@ -1879,7 +1875,7 @@ fn make_body(ctx: &AssistContext<'_>, old_indent: IndentLevel, fun: &Function) -
.iter()
.map(|var| path_expr_from_local(ctx, var.local, fun.mods.edition));
let expr = make::expr_tuple(exprs);
tail_expr = Some(expr);
tail_expr = Some(expr.into());
}
},
};
Expand Down Expand Up @@ -1910,7 +1906,7 @@ fn make_body(ctx: &AssistContext<'_>, old_indent: IndentLevel, fun: &Function) -
match &handler {
FlowHandler::None => block,
FlowHandler::Try { kind } => {
let block = with_default_tail_expr(block, make::expr_unit());
let block = with_default_tail_expr(block, make::ext::expr_unit());
map_tail_expr(block, |tail_expr| {
let constructor = match kind {
TryKind::Option => "Some",
Expand All @@ -1924,7 +1920,7 @@ fn make_body(ctx: &AssistContext<'_>, old_indent: IndentLevel, fun: &Function) -
FlowHandler::If { .. } => {
let controlflow_continue = make::expr_call(
make::expr_path(make::path_from_text("ControlFlow::Continue")),
make::arg_list(iter::once(make::expr_unit())),
make::arg_list([make::ext::expr_unit()]),
);
with_tail_expr(block, controlflow_continue)
}
Expand Down Expand Up @@ -2127,17 +2123,17 @@ fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Op
FlowHandler::None | FlowHandler::Try { .. } => return None,
FlowHandler::If { .. } => make::expr_call(
make::expr_path(make::path_from_text("ControlFlow::Break")),
make::arg_list(iter::once(make::expr_unit())),
make::arg_list([make::ext::expr_unit()]),
),
FlowHandler::IfOption { .. } => {
let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
let args = make::arg_list(iter::once(expr));
let expr = arg_expr.unwrap_or_else(make::ext::expr_unit);
let args = make::arg_list([expr]);
make::expr_call(make::expr_path(make::ext::ident_path("Some")), args)
}
FlowHandler::MatchOption { .. } => make::expr_path(make::ext::ident_path("None")),
FlowHandler::MatchResult { .. } => {
let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
let args = make::arg_list(iter::once(expr));
let expr = arg_expr.unwrap_or_else(make::ext::expr_unit);
let args = make::arg_list([expr]);
make::expr_call(make::expr_path(make::ext::ident_path("Err")), args)
}
};
Expand Down
2 changes: 1 addition & 1 deletion crates/ide-assists/src/handlers/move_guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub(crate) fn move_guard_to_arm_body(acc: &mut Assists, ctx: &AssistContext<'_>)
};

edit.delete(guard.syntax().text_range());
edit.replace_ast(arm_expr, if_expr);
edit.replace_ast(arm_expr, if_expr.into());
},
)
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ide-assists/src/handlers/remove_dbg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ fn compute_dbg_replacement(macro_expr: ast::MacroExpr) -> Option<(TextRange, Opt
};
(range, None)
},
_ => (macro_call.syntax().text_range(), Some(make::expr_unit())),
_ => (macro_call.syntax().text_range(), Some(make::ext::expr_unit())),
}
}
}
Expand Down Expand Up @@ -152,7 +152,7 @@ fn compute_dbg_replacement(macro_expr: ast::MacroExpr) -> Option<(TextRange, Opt
exprs => {
let exprs = exprs.iter().cloned().map(replace_nested_dbgs);
let expr = make::expr_tuple(exprs);
(macro_call.syntax().text_range(), Some(expr))
(macro_call.syntax().text_range(), Some(expr.into()))
}
})
}
Expand Down
98 changes: 52 additions & 46 deletions crates/ide-assists/src/handlers/replace_if_let_with_match.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::iter::{self, successors};
use std::iter::successors;

use either::Either;
use ide_db::{
Expand All @@ -8,11 +8,7 @@ use ide_db::{
RootDatabase,
};
use syntax::{
ast::{
self,
edit::{AstNodeEdit, IndentLevel},
make, HasName,
},
ast::{self, edit::IndentLevel, edit_in_place::Indent, syntax_factory::SyntaxFactory, HasName},
AstNode, TextRange, T,
};

Expand Down Expand Up @@ -108,53 +104,58 @@ pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext<'
AssistId("replace_if_let_with_match", AssistKind::RefactorRewrite),
format!("Replace if{let_} with match"),
available_range,
move |edit| {
move |builder| {
let make = SyntaxFactory::new();
let match_expr = {
let else_arm = make_else_arm(ctx, else_block, &cond_bodies);
let else_arm = make_else_arm(ctx, &make, else_block, &cond_bodies);
let make_match_arm = |(pat, body): (_, ast::BlockExpr)| {
let body = body.reset_indent().indent(IndentLevel(1));
let body = make.block_expr(body.statements(), body.tail_expr());
body.indent(IndentLevel::from(1));
let body = unwrap_trivial_block(body);
match pat {
Either::Left(pat) => {
make::match_arm(iter::once(pat), None, unwrap_trivial_block(body))
Either::Left(pat) => make.match_arm(pat, None, body),
Either::Right(_) if !pat_seen => {
make.match_arm(make.literal_pat("true").into(), None, body)
}
Either::Right(_) if !pat_seen => make::match_arm(
iter::once(make::literal_pat("true").into()),
None,
unwrap_trivial_block(body),
),
Either::Right(expr) => make::match_arm(
iter::once(make::wildcard_pat().into()),
Some(expr),
unwrap_trivial_block(body),
Either::Right(expr) => make.match_arm(
make.wildcard_pat().into(),
Some(make.match_guard(expr)),
body,
),
}
};
let arms = cond_bodies.into_iter().map(make_match_arm).chain(iter::once(else_arm));
let match_expr = make::expr_match(scrutinee_to_be_expr, make::match_arm_list(arms));
match_expr.indent(IndentLevel::from_node(if_expr.syntax()))
let arms = cond_bodies.into_iter().map(make_match_arm).chain([else_arm]);
let match_expr = make.expr_match(scrutinee_to_be_expr, make.match_arm_list(arms));
match_expr.indent(IndentLevel::from_node(if_expr.syntax()));
match_expr.into()
};

let has_preceding_if_expr =
if_expr.syntax().parent().is_some_and(|it| ast::IfExpr::can_cast(it.kind()));
let expr = if has_preceding_if_expr {
// make sure we replace the `else if let ...` with a block so we don't end up with `else expr`
make::block_expr(None, Some(match_expr)).into()
make.block_expr([], Some(match_expr)).into()
} else {
match_expr
};
edit.replace_ast::<ast::Expr>(if_expr.into(), expr);

let mut editor = builder.make_editor(if_expr.syntax());
editor.replace(if_expr.syntax(), expr.syntax());
editor.add_mappings(make.finish_with_mappings());
builder.add_file_edits(ctx.file_id(), editor);
},
)
}

fn make_else_arm(
ctx: &AssistContext<'_>,
make: &SyntaxFactory,
else_block: Option<ast::BlockExpr>,
conditionals: &[(Either<ast::Pat, ast::Expr>, ast::BlockExpr)],
) -> ast::MatchArm {
let (pattern, expr) = if let Some(else_block) = else_block {
let pattern = match conditionals {
[(Either::Right(_), _)] => make::literal_pat("false").into(),
[(Either::Right(_), _)] => make.literal_pat("false").into(),
[(Either::Left(pat), _)] => match ctx
.sema
.type_of_pat(pat)
Expand All @@ -164,24 +165,24 @@ fn make_else_arm(
if does_pat_match_variant(pat, &it.sad_pattern()) {
it.happy_pattern_wildcard()
} else if does_pat_variant_nested_or_literal(ctx, pat) {
make::wildcard_pat().into()
make.wildcard_pat().into()
} else {
it.sad_pattern()
}
}
None => make::wildcard_pat().into(),
None => make.wildcard_pat().into(),
},
_ => make::wildcard_pat().into(),
_ => make.wildcard_pat().into(),
};
(pattern, unwrap_trivial_block(else_block))
} else {
let pattern = match conditionals {
[(Either::Right(_), _)] => make::literal_pat("false").into(),
_ => make::wildcard_pat().into(),
[(Either::Right(_), _)] => make.literal_pat("false").into(),
_ => make.wildcard_pat().into(),
};
(pattern, make::expr_unit())
(pattern, make.expr_unit())
};
make::match_arm(iter::once(pattern), None, expr)
make.match_arm(pattern, None, expr)
}

// Assist: replace_match_with_if_let
Expand Down Expand Up @@ -247,21 +248,21 @@ pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext<'
}
_ => " let",
};
let target = match_expr.syntax().text_range();
acc.add(
AssistId("replace_match_with_if_let", AssistKind::RefactorRewrite),
format!("Replace match with if{let_}"),
target,
move |edit| {
fn make_block_expr(expr: ast::Expr) -> ast::BlockExpr {
match_expr.syntax().text_range(),
move |builder| {
let make = SyntaxFactory::new();
let make_block_expr = |expr: ast::Expr| {
// Blocks with modifiers (unsafe, async, etc.) are parsed as BlockExpr, but are
// formatted without enclosing braces. If we encounter such block exprs,
// wrap them in another BlockExpr.
match expr {
ast::Expr::BlockExpr(block) if block.modifier().is_none() => block,
expr => make::block_expr(iter::empty(), Some(expr)),
expr => make.block_expr([], Some(expr)),
}
}
};

let condition = match if_let_pat {
ast::Pat::LiteralPat(p)
Expand All @@ -272,20 +273,25 @@ pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext<'
ast::Pat::LiteralPat(p)
if p.literal().is_some_and(|it| it.token().kind() == T![false]) =>
{
make::expr_prefix(T![!], scrutinee)
make.expr_prefix(T![!], scrutinee).into()
}
_ => make::expr_let(if_let_pat, scrutinee).into(),
_ => make.expr_let(if_let_pat, scrutinee).into(),
};
let then_block = make_block_expr(then_expr.reset_indent());
let then_expr = then_expr.clone_for_update();
then_expr.reindent_to(IndentLevel::single());
let then_block = make_block_expr(then_expr);
let else_expr = if is_empty_expr(&else_expr) { None } else { Some(else_expr) };
let if_let_expr = make::expr_if(
let if_let_expr = make.expr_if(
condition,
then_block,
else_expr.map(make_block_expr).map(ast::ElseBranch::Block),
)
.indent(IndentLevel::from_node(match_expr.syntax()));
);
if_let_expr.indent(IndentLevel::from_node(match_expr.syntax()));

edit.replace_ast::<ast::Expr>(match_expr.into(), if_let_expr);
let mut editor = builder.make_editor(match_expr.syntax());
editor.replace(match_expr.syntax(), if_let_expr.syntax());
editor.add_mappings(make.finish_with_mappings());
builder.add_file_edits(ctx.file_id(), editor);
},
)
}
Expand Down
Loading

0 comments on commit 1e975d6

Please sign in to comment.