Skip to content

Commit

Permalink
Merge pull request #18495 from tareknaser/syntax_factory_reorder_fields
Browse files Browse the repository at this point in the history
Migrate `reorder_fields` Assist to Use `SyntaxFactory`
  • Loading branch information
davidbarsky authored Nov 15, 2024
2 parents fc98e06 + 5c41c20 commit 1b90e97
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions crates/ide-assists/src/handlers/reorder_fields.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand All @@ -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)
Expand Down Expand Up @@ -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 {
Either::Left((sorted, field_list)) => {
replace(builder.make_mut(field_list).fields(), sorted)
}
Either::Right((sorted, field_list)) => {
replace(builder.make_mut(field_list).fields(), sorted)
|builder| {
let mut editor = builder.make_editor(&parent_node);

match fields {
Either::Left((sorted, field_list)) => {
replace(&mut editor, field_list.fields(), sorted)
}
Either::Right((sorted, field_list)) => {
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())
});
}

Expand Down

0 comments on commit 1b90e97

Please sign in to comment.