mirror of
https://github.com/rust-lang/rust-analyzer.git
synced 2025-09-27 20:42:04 +00:00
Suggest pub(crate)
imports
rust-analyzer has logic that discounts suggesting `use`s for private
imports, but that logic is unnecessarily strict - for instance given
this code:
```rust
mod foo {
pub struct Foo;
}
pub(crate) use self::foo::*;
mod bar {
fn main() {
Foo$0;
}
}
```
... RA will suggest to add `use crate::foo::Foo;`, which not only makes
the code overly verbose (especially in larger code bases), but also is
disjoint with what rustc itself suggests.
This commit adjusts the logic, so that `pub(crate)` imports are taken
into account when generating the suggestions; considering rustc's
behavior, I think this change doesn't warrant any extra configuration
flag.
Note that this is my first commit to RA, so I guess the approach taken
here might be suboptimal - certainly feels somewhat hacky, maybe there's
some better way of finding out the optimal import path 😅
This commit is contained in:
parent
c84352a346
commit
76aaf17794
9 changed files with 106 additions and 18 deletions
|
@ -551,7 +551,18 @@ fn find_local_import_locations(
|
|||
if let Some((name, vis)) = data.scope.name_of(item) {
|
||||
if vis.is_visible_from(db, from) {
|
||||
let is_private = match vis {
|
||||
Visibility::Module(private_to) => private_to.local_id == module.local_id,
|
||||
Visibility::Module(private_mod, private_vis) => {
|
||||
if private_mod == def_map.module_id(DefMap::ROOT)
|
||||
&& private_vis.is_explicit()
|
||||
{
|
||||
// Treat `pub(crate)` imports as non-private, so
|
||||
// that we suggest adding `use crate::Foo;` instead
|
||||
// of `use crate::foo::Foo;` etc.
|
||||
false
|
||||
} else {
|
||||
private_mod.local_id == module.local_id
|
||||
}
|
||||
}
|
||||
Visibility::Public => false,
|
||||
};
|
||||
let is_original_def = match item.as_module_def_id() {
|
||||
|
@ -1021,6 +1032,24 @@ $0
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promote_pub_crate_imports() {
|
||||
check_found_path(
|
||||
r#"
|
||||
//- /main.rs
|
||||
mod foo;
|
||||
pub mod bar { pub struct S; }
|
||||
pub(crate) use bar::S;
|
||||
//- /foo.rs
|
||||
$0
|
||||
"#,
|
||||
"crate::S",
|
||||
"crate::S",
|
||||
"crate::S",
|
||||
"crate::S",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_cycle() {
|
||||
check_found_path(
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue