|
1 | 1 | use ide_db::assists::{AssistId, GroupLabel};
|
2 | 2 | use syntax::{
|
3 |
| - AstNode, TextRange, |
4 |
| - ast::{self, ArithOp, BinaryOp}, |
| 3 | + AstNode, |
| 4 | + ast::{self, ArithOp, BinaryOp, syntax_factory::SyntaxFactory}, |
5 | 5 | };
|
6 | 6 |
|
7 | 7 | use crate::assist_context::{AssistContext, Assists};
|
@@ -71,28 +71,31 @@ pub(crate) fn replace_arith_with_wrapping(
|
71 | 71 |
|
72 | 72 | fn replace_arith(acc: &mut Assists, ctx: &AssistContext<'_>, kind: ArithKind) -> Option<()> {
|
73 | 73 | let (lhs, op, rhs) = parse_binary_op(ctx)?;
|
| 74 | + let op_expr = lhs.syntax().parent()?; |
74 | 75 |
|
75 | 76 | if !is_primitive_int(ctx, &lhs) || !is_primitive_int(ctx, &rhs) {
|
76 | 77 | return None;
|
77 | 78 | }
|
78 | 79 |
|
79 |
| - let start = lhs.syntax().text_range().start(); |
80 |
| - let end = rhs.syntax().text_range().end(); |
81 |
| - let range = TextRange::new(start, end); |
82 |
| - |
83 | 80 | acc.add_group(
|
84 | 81 | &GroupLabel("Replace arithmetic...".into()),
|
85 | 82 | kind.assist_id(),
|
86 | 83 | kind.label(),
|
87 |
| - range, |
| 84 | + op_expr.text_range(), |
88 | 85 | |builder| {
|
| 86 | + let mut edit = builder.make_editor(rhs.syntax()); |
| 87 | + let make = SyntaxFactory::with_mappings(); |
89 | 88 | let method_name = kind.method_name(op);
|
90 | 89 |
|
91 |
| - if lhs.precedence().needs_parentheses_in(ast::prec::ExprPrecedence::Postfix) { |
92 |
| - builder.replace(range, format!("({lhs}).{method_name}({rhs})")) |
93 |
| - } else { |
94 |
| - builder.replace(range, format!("{lhs}.{method_name}({rhs})")) |
95 |
| - } |
| 90 | + let needs_parentheses = |
| 91 | + lhs.precedence().needs_parentheses_in(ast::prec::ExprPrecedence::Postfix); |
| 92 | + let receiver = if needs_parentheses { make.expr_paren(lhs).into() } else { lhs }; |
| 93 | + let arith_expr = |
| 94 | + make.expr_method_call(receiver, make.name_ref(&method_name), make.arg_list([rhs])); |
| 95 | + edit.replace(op_expr, arith_expr.syntax()); |
| 96 | + |
| 97 | + edit.add_mappings(make.finish_with_mappings()); |
| 98 | + builder.add_file_edits(ctx.vfs_file_id(), edit); |
96 | 99 | },
|
97 | 100 | )
|
98 | 101 | }
|
|
0 commit comments