diff --git a/crates/ide-assists/src/handlers/replace_arith_op.rs b/crates/ide-assists/src/handlers/replace_arith_op.rs index 94ac1c342d30..a3fb851fb0e2 100644 --- a/crates/ide-assists/src/handlers/replace_arith_op.rs +++ b/crates/ide-assists/src/handlers/replace_arith_op.rs @@ -1,7 +1,7 @@ use ide_db::assists::{AssistId, GroupLabel}; use syntax::{ - AstNode, TextRange, - ast::{self, ArithOp, BinaryOp}, + AstNode, + ast::{self, ArithOp, BinaryOp, syntax_factory::SyntaxFactory}, }; use crate::assist_context::{AssistContext, Assists}; @@ -71,28 +71,31 @@ pub(crate) fn replace_arith_with_wrapping( fn replace_arith(acc: &mut Assists, ctx: &AssistContext<'_>, kind: ArithKind) -> Option<()> { let (lhs, op, rhs) = parse_binary_op(ctx)?; + let op_expr = lhs.syntax().parent()?; if !is_primitive_int(ctx, &lhs) || !is_primitive_int(ctx, &rhs) { return None; } - let start = lhs.syntax().text_range().start(); - let end = rhs.syntax().text_range().end(); - let range = TextRange::new(start, end); - acc.add_group( &GroupLabel("Replace arithmetic...".into()), kind.assist_id(), kind.label(), - range, + op_expr.text_range(), |builder| { + let mut edit = builder.make_editor(rhs.syntax()); + let make = SyntaxFactory::with_mappings(); let method_name = kind.method_name(op); - if lhs.precedence().needs_parentheses_in(ast::prec::ExprPrecedence::Postfix) { - builder.replace(range, format!("({lhs}).{method_name}({rhs})")) - } else { - builder.replace(range, format!("{lhs}.{method_name}({rhs})")) - } + let needs_parentheses = + lhs.precedence().needs_parentheses_in(ast::prec::ExprPrecedence::Postfix); + let receiver = if needs_parentheses { make.expr_paren(lhs).into() } else { lhs }; + let arith_expr = + make.expr_method_call(receiver, make.name_ref(&method_name), make.arg_list([rhs])); + edit.replace(op_expr, arith_expr.syntax()); + + edit.add_mappings(make.finish_with_mappings()); + builder.add_file_edits(ctx.vfs_file_id(), edit); }, ) }