mirror of
https://github.com/rust-lang/rust-analyzer
synced 2024-12-28 05:53:45 +00:00
feat: migrate reorder_fields
assist to use SyntaxFactory
Signed-off-by: Tarek <tareknaser360@gmail.com>
This commit is contained in:
parent
fc98e0657a
commit
5c41c20c11
1 changed files with 21 additions and 8 deletions
|
@ -1,7 +1,7 @@
|
|||
use either::Either;
|
||||
use ide_db::FxHashMap;
|
||||
use itertools::Itertools;
|
||||
use syntax::{ast, ted, AstNode, SmolStr, ToSmolStr};
|
||||
use syntax::{ast, syntax_editor::SyntaxEditor, AstNode, SmolStr, SyntaxElement, ToSmolStr};
|
||||
|
||||
use crate::{AssistContext, AssistId, AssistKind, Assists};
|
||||
|
||||
|
@ -24,6 +24,11 @@ pub(crate) fn reorder_fields(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti
|
|||
let record =
|
||||
path.syntax().parent().and_then(<Either<ast::RecordExpr, ast::RecordPat>>::cast)?;
|
||||
|
||||
let parent_node = match ctx.covering_element() {
|
||||
SyntaxElement::Node(n) => n,
|
||||
SyntaxElement::Token(t) => t.parent()?,
|
||||
};
|
||||
|
||||
let ranks = compute_fields_ranks(&path, ctx)?;
|
||||
let get_rank_of_field = |of: Option<SmolStr>| {
|
||||
*ranks.get(of.unwrap_or_default().trim_start_matches("r#")).unwrap_or(&usize::MAX)
|
||||
|
@ -65,23 +70,31 @@ pub(crate) fn reorder_fields(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti
|
|||
AssistId("reorder_fields", AssistKind::RefactorRewrite),
|
||||
"Reorder record fields",
|
||||
target,
|
||||
|builder| match fields {
|
||||
|builder| {
|
||||
let mut editor = builder.make_editor(&parent_node);
|
||||
|
||||
match fields {
|
||||
Either::Left((sorted, field_list)) => {
|
||||
replace(builder.make_mut(field_list).fields(), sorted)
|
||||
replace(&mut editor, field_list.fields(), sorted)
|
||||
}
|
||||
Either::Right((sorted, field_list)) => {
|
||||
replace(builder.make_mut(field_list).fields(), sorted)
|
||||
replace(&mut editor, field_list.fields(), sorted)
|
||||
}
|
||||
}
|
||||
|
||||
builder.add_file_edits(ctx.file_id(), editor);
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn replace<T: AstNode + PartialEq>(
|
||||
editor: &mut SyntaxEditor,
|
||||
fields: impl Iterator<Item = T>,
|
||||
sorted_fields: impl IntoIterator<Item = T>,
|
||||
) {
|
||||
fields.zip(sorted_fields).for_each(|(field, sorted_field)| {
|
||||
ted::replace(field.syntax(), sorted_field.syntax().clone_for_update())
|
||||
// FIXME: remove `clone_for_update` when `SyntaxEditor` handles it for us
|
||||
editor.replace(field.syntax(), sorted_field.syntax().clone_for_update())
|
||||
});
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue