Merge pull request #20748 from A4-Tacks/migrate-arith-op-prec
Migrate `replace_arith_op` assist to use `SyntaxEditor`
This commit is contained in:
commit
7de38d36eb
1 changed files with 15 additions and 12 deletions
|
|
@ -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);
|
||||
},
|
||||
)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue