internal: rewrite **Repalce impl Trait** assist to mutable syntax trees

This commit is contained in:
Aleksey Kladov 2021-05-09 18:20:37 +03:00
parent 984d20aad8
commit 5342800147
2 changed files with 20 additions and 23 deletions

View File

@ -1,4 +1,7 @@
use syntax::ast::{self, edit::AstNodeEdit, make, AstNode, GenericParamsOwner};
use syntax::{
ast::{self, edit_in_place::GenericParamsOwnerEdit, make, AstNode},
ted,
};
use crate::{utils::suggest_name, AssistContext, AssistId, AssistKind, Assists};
@ -29,18 +32,17 @@ pub(crate) fn replace_impl_trait_with_generic(
"Replace impl trait with generic",
target,
|edit| {
let impl_trait_type = edit.make_ast_mut(impl_trait_type);
let fn_ = edit.make_ast_mut(fn_);
let type_param_name = suggest_name::for_generic_parameter(&impl_trait_type);
let generic_param_list = fn_
.generic_param_list()
.unwrap_or_else(|| make::generic_param_list(None))
.append_param(make::generic_param(&type_param_name, Some(type_bound_list)));
let type_param =
make::generic_param(&type_param_name, Some(type_bound_list)).clone_for_update();
let new_ty = make::ty(&type_param_name).clone_for_update();
let new_type_fn = fn_
.replace_descendant::<ast::Type>(impl_trait_type.into(), make::ty(&type_param_name))
.with_generic_param_list(generic_param_list);
edit.replace_ast(fn_.clone(), new_type_fn);
ted::replace(impl_trait_type.syntax(), new_ty.syntax());
fn_.get_or_create_generic_param_list().add_generic_param(type_param)
},
)
}
@ -127,7 +129,7 @@ fn foo<
fn foo<
G: Foo,
F,
H, B: Bar
H, B: Bar,
>(bar: B) {}
"#,
);

View File

@ -195,18 +195,13 @@ impl ast::GenericParamList {
pub fn add_generic_param(&self, generic_param: ast::GenericParam) {
match self.generic_params().last() {
Some(last_param) => {
let mut elems = Vec::new();
if !last_param
.syntax()
.siblings_with_tokens(Direction::Next)
.any(|it| it.kind() == T![,])
{
elems.push(make::token(T![,]).into());
elems.push(make::tokens::single_space().into());
};
elems.push(generic_param.syntax().clone().into());
let after_last_param = Position::after(last_param.syntax());
ted::insert_all(after_last_param, elems);
let position = Position::after(last_param.syntax());
let elements = vec![
make::token(T![,]).into(),
make::tokens::single_space().into(),
generic_param.syntax().clone().into(),
];
ted::insert_all(position, elements);
}
None => {
let after_l_angle = Position::after(self.l_angle_token().unwrap());