Skip to content

Commit dd16cbc

Browse files
harrysarsonharrysarson-signaloid
authored andcommitted
braces around {self} in UseTree are not unnecessary
Before this commit `UseTree::remove_unnecessary_braces` removed the braces around `{self}` in `use x::y::{self};` but `use x::y::self;` is not valid rust.
1 parent a200391 commit dd16cbc

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

src/tools/rust-analyzer/crates/ide-assists/src/handlers/remove_unused_imports.rs

+34
Original file line numberDiff line numberDiff line change
@@ -776,6 +776,40 @@ mod z {
776776
);
777777
}
778778

779+
#[test]
780+
fn remove_unused_fixes_nested_self() {
781+
check_assist(
782+
remove_unused_imports,
783+
r#"
784+
mod inner {
785+
pub struct X();
786+
pub struct Y();
787+
}
788+
789+
mod z {
790+
use super::inner::{self, X}$0;
791+
792+
fn f() {
793+
let y = inner::Y();
794+
}
795+
}
796+
"#,
797+
r#"mod inner {
798+
pub struct X();
799+
pub struct Y();
800+
}
801+
802+
mod z {
803+
use super::inner::{self};
804+
805+
fn f() {
806+
let y = inner::Y();
807+
}
808+
}
809+
"#,
810+
);
811+
}
812+
779813
#[test]
780814
fn dont_remove_used_glob() {
781815
check_assist_not_applicable(

src/tools/rust-analyzer/crates/syntax/src/ast/node_ext.rs

+19-2
Original file line numberDiff line numberDiff line change
@@ -378,9 +378,26 @@ impl ast::UseTreeList {
378378

379379
/// Remove the unnecessary braces in current `UseTreeList`
380380
pub fn remove_unnecessary_braces(mut self) {
381+
// Returns true iff there is a single subtree and it is not the self keyword. The braces in
382+
// `use x::{self};` are necessary and so we should not remove them.
383+
let has_single_subtree_that_is_not_self = |u: &ast::UseTreeList| {
384+
if let Some((single_subtree,)) = u.use_trees().collect_tuple() {
385+
// We have a single subtree, check whether it is self.
386+
387+
let is_self = single_subtree.path().as_ref().map_or(false, |path| {
388+
path.segment().and_then(|seg| seg.self_token()).is_some()
389+
&& path.qualifier().is_none()
390+
});
391+
392+
!is_self
393+
} else {
394+
// Not a single subtree
395+
false
396+
}
397+
};
398+
381399
let remove_brace_in_use_tree_list = |u: &ast::UseTreeList| {
382-
let use_tree_count = u.use_trees().count();
383-
if use_tree_count == 1 {
400+
if has_single_subtree_that_is_not_self(u) {
384401
if let Some(a) = u.l_curly_token() {
385402
ted::remove(a)
386403
}

0 commit comments

Comments
 (0)