Skip to content

Commit df9d3bd

Browse files
committed
Use shortest path
1 parent 1ea2b47 commit df9d3bd

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

crates/ra_hir_def/src/find_path.rs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ use hir_expand::name::Name;
1010

1111
// TODO don't import from super imports? or at least deprioritize
1212
// TODO use super?
13-
// TODO use shortest path
1413
// TODO performance / memoize
1514

1615
pub fn find_path(db: &impl DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
@@ -61,17 +60,17 @@ pub fn find_path(db: &impl DefDatabase, item: ItemInNs, from: ModuleId) -> Optio
6160

6261
// - otherwise, look for modules containing (reexporting) it and import it from one of those
6362
let importable_locations = find_importable_locations(db, item, from);
64-
// XXX going in order for now
63+
let mut candidate_paths = Vec::new();
6564
for (module_id, name) in importable_locations {
6665
// TODO prevent infinite loops
6766
let mut path = match find_path(db, ItemInNs::Types(ModuleDefId::ModuleId(module_id)), from) {
6867
None => continue,
6968
Some(path) => path,
7069
};
7170
path.segments.push(name);
72-
return Some(path);
71+
candidate_paths.push(path);
7372
}
74-
None
73+
candidate_paths.into_iter().min_by_key(|path| path.segments.len())
7574
}
7675

7776
fn find_importable_locations(db: &impl DefDatabase, item: ItemInNs, from: ModuleId) -> Vec<(ModuleId, Name)> {
@@ -275,4 +274,20 @@ mod tests {
275274
check_found_path(code, "None");
276275
check_found_path(code, "Some");
277276
}
277+
278+
#[test]
279+
fn shortest_path() {
280+
let code = r#"
281+
//- /main.rs
282+
pub mod foo;
283+
pub mod baz;
284+
struct S;
285+
<|>
286+
//- /foo.rs
287+
pub mod bar { pub struct S; }
288+
//- /baz.rs
289+
pub use crate::foo::bar::S;
290+
"#;
291+
check_found_path(code, "baz::S");
292+
}
278293
}

0 commit comments

Comments
 (0)