Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate merge_imports Assist to Use SyntaxFactory #18484

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 24 additions & 14 deletions crates/ide-assists/src/handlers/merge_imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ use ide_db::imports::{
use itertools::Itertools;
use syntax::{
algo::neighbor,
ast::{self, edit_in_place::Removable},
match_ast, ted, AstNode, SyntaxElement, SyntaxNode,
ast::{self, syntax_factory::SyntaxFactory},
match_ast,
syntax_editor::edits::Removable,
AstNode, SyntaxElement, SyntaxNode,
};

use crate::{
Expand Down Expand Up @@ -68,24 +70,30 @@ pub(crate) fn merge_imports(acc: &mut Assists, ctx: &AssistContext<'_>) -> Optio
(selection_range, edits?)
};

let parent_node = match ctx.covering_element() {
SyntaxElement::Node(n) => n,
SyntaxElement::Token(t) => t.parent()?,
};
let make = SyntaxFactory::new();

acc.add(
AssistId("merge_imports", AssistKind::RefactorRewrite),
"Merge imports",
target,
|builder| {
let edits_mut: Vec<Edit> = edits
.into_iter()
.map(|it| match it {
Remove(Either::Left(it)) => Remove(Either::Left(builder.make_mut(it))),
Remove(Either::Right(it)) => Remove(Either::Right(builder.make_mut(it))),
Replace(old, new) => Replace(builder.make_syntax_mut(old), new),
})
.collect();
for edit in edits_mut {
let mut editor = builder.make_editor(&parent_node);
for edit in edits {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that to avoid the intersection assertion failure, we should use SyntaxEditor::replace_all for consecutive text ranges instead of individual insert or delete calls

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So the edits are generated in a vector by calling either use_item.try_merge_from() or use_tree.try_merge_from(). How can we combine all of these edits into a single replace_all() call?

match edit {
Remove(it) => it.as_ref().either(Removable::remove, Removable::remove),
Remove(it) => {
let node = it.as_ref();
if let Some(left) = node.left() {
left.remove(&mut editor);
} else if let Some(right) = node.right() {
right.remove(&mut editor);
}
}
Replace(old, new) => {
ted::replace(old, &new);
editor.replace(old, &new);

// If there's a selection and we're replacing a use tree in a tree list,
// normalize the parent use tree if it only contains the merged subtree.
Expand All @@ -109,12 +117,14 @@ pub(crate) fn merge_imports(acc: &mut Assists, ctx: &AssistContext<'_>) -> Optio
});
if let Some((old_tree, new_tree)) = normalized_use_tree {
cov_mark::hit!(replace_parent_with_normalized_use_tree);
ted::replace(old_tree.syntax(), new_tree.syntax());
editor.replace(old_tree.syntax(), new_tree.syntax());
}
}
}
}
}
editor.add_mappings(make.finish_with_mappings());
builder.add_file_edits(ctx.file_id(), editor);
},
)
}
Expand Down
4 changes: 4 additions & 0 deletions crates/syntax/src/ast/syntax_factory/constructors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ impl SyntaxFactory {
make::ty(text).clone_for_update()
}

pub fn whitespace(&self, text: &str) -> SyntaxToken {
make::tokens::whitespace(text)
}

pub fn type_param(
&self,
name: ast::Name,
Expand Down
2 changes: 1 addition & 1 deletion crates/syntax/src/syntax_editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use rustc_hash::FxHashMap;
use crate::{SyntaxElement, SyntaxNode, SyntaxToken};

mod edit_algo;
mod edits;
pub mod edits;
mod mapping;

pub use mapping::{SyntaxMapping, SyntaxMappingBuilder};
Expand Down
71 changes: 69 additions & 2 deletions crates/syntax/src/syntax_editor/edits.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
//! Structural editing for ast using `SyntaxEditor`

use crate::{
ast::make, ast::AstNode, ast::Fn, ast::GenericParam, ast::HasGenericParams, ast::HasName,
syntax_editor::Position, syntax_editor::SyntaxEditor, SyntaxKind,
algo::neighbor,
ast::{
self, make, syntax_factory::SyntaxFactory, AstNode, Fn, GenericParam, HasGenericParams,
HasName,
},
syntax_editor::{Position, SyntaxEditor},
AstToken, Direction, SyntaxKind,
};

impl SyntaxEditor {
Expand Down Expand Up @@ -70,3 +75,65 @@ impl SyntaxEditor {
}
}
}

pub trait Removable: AstNode {
fn remove(&self, editor: &mut SyntaxEditor);
}

impl Removable for ast::Use {
fn remove(&self, editor: &mut SyntaxEditor) {
let make = SyntaxFactory::new();

let next_ws = self
.syntax()
.next_sibling_or_token()
.and_then(|it| it.into_token())
.and_then(ast::Whitespace::cast);
if let Some(next_ws) = next_ws {
let ws_text = next_ws.syntax().text();
if let Some(rest) = ws_text.strip_prefix('\n') {
if rest.is_empty() {
editor.delete(next_ws.syntax());
} else {
editor.replace(next_ws.syntax(), make.whitespace(rest));
}
}
}
let prev_ws = self
.syntax()
.prev_sibling_or_token()
.and_then(|it| it.into_token())
.and_then(ast::Whitespace::cast);
if let Some(prev_ws) = prev_ws {
let ws_text = prev_ws.syntax().text();
let prev_newline = ws_text.rfind('\n').map(|x| x + 1).unwrap_or(0);
let rest = &ws_text[0..prev_newline];
if rest.is_empty() {
editor.delete(prev_ws.syntax());
} else {
editor.replace(prev_ws.syntax(), make.whitespace(rest));
}
}

editor.delete(self.syntax());
}
}

impl Removable for ast::UseTree {
fn remove(&self, editor: &mut SyntaxEditor) {
for dir in [Direction::Next, Direction::Prev] {
if let Some(next_use_tree) = neighbor(self, dir) {
let separators = self
.syntax()
.siblings_with_tokens(dir)
.skip(1)
.take_while(|it| it.as_node() != Some(next_use_tree.syntax()));
for sep in separators {
editor.delete(sep);
}
break;
}
}
editor.delete(self.syntax());
}
}
Loading