1 //! An algorithm to find a path to refer to a certain item.
3 use hir_expand::name::{known, AsName, Name};
4 use rustc_hash::FxHashSet;
10 path::{ModPath, PathKind},
11 visibility::Visibility,
12 ModuleDefId, ModuleId,
15 // FIXME: handle local items
17 /// Find a path that can be used to refer to a certain item. This can depend on
18 /// *from where* you're referring to the item, hence the `from` parameter.
19 pub fn find_path(db: &dyn DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
20 let _p = profile::span("find_path");
21 find_path_inner(db, item, from, MAX_PATH_LEN)
24 const MAX_PATH_LEN: usize = 15;
27 fn starts_with_std(&self) -> bool {
28 self.segments.first() == Some(&known::std)
31 // When std library is present, paths starting with `std::`
32 // should be preferred over paths starting with `core::` and `alloc::`
33 fn can_start_with_std(&self) -> bool {
34 let first_segment = self.segments.first();
35 first_segment == Some(&known::alloc) || first_segment == Some(&known::core)
44 ) -> Option<ModPath> {
51 // - if the item is already in scope, return the name under which it is
52 let def_map = db.crate_def_map(from.krate);
53 let from_scope: &crate::item_scope::ItemScope = &def_map.modules[from.local_id].scope;
54 if let Some((name, _)) = from_scope.name_of(item) {
55 return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
58 // - if the item is the crate root, return `crate`
60 == ItemInNs::Types(ModuleDefId::ModuleId(ModuleId {
62 local_id: def_map.root,
65 return Some(ModPath::from_segments(PathKind::Crate, Vec::new()));
68 // - if the item is the module we're in, use `self`
69 if item == ItemInNs::Types(from.into()) {
70 return Some(ModPath::from_segments(PathKind::Super(0), Vec::new()));
73 // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
74 if let Some(parent_id) = def_map.modules[from.local_id].parent {
76 == ItemInNs::Types(ModuleDefId::ModuleId(ModuleId {
81 return Some(ModPath::from_segments(PathKind::Super(1), Vec::new()));
85 // - if the item is the crate root of a dependency crate, return the name from the extern prelude
86 for (name, def_id) in &def_map.extern_prelude {
87 if item == ItemInNs::Types(*def_id) {
88 return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
92 // - if the item is in the prelude, return the name from there
93 if let Some(prelude_module) = def_map.prelude {
94 let prelude_def_map = db.crate_def_map(prelude_module.krate);
95 let prelude_scope: &crate::item_scope::ItemScope =
96 &prelude_def_map.modules[prelude_module.local_id].scope;
97 if let Some((name, vis)) = prelude_scope.name_of(item) {
98 if vis.is_visible_from(db, from) {
99 return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
104 // - if the item is a builtin, it's in scope
105 if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
106 return Some(ModPath::from_segments(PathKind::Plain, vec![builtin.as_name()]));
110 // - if the item is an enum variant, refer to it via the enum
111 if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
112 if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) {
113 let data = db.enum_data(variant.parent);
114 path.segments.push(data.variants[variant.local_id].name.clone());
117 // If this doesn't work, it seems we have no way of referring to the
118 // enum; that's very weird, but there might still be a reexport of the
122 // - otherwise, look for modules containing (reexporting) it and import it from one of those
124 let crate_root = ModuleId { local_id: def_map.root, krate: from.krate };
125 let crate_attrs = db.attrs(crate_root.into());
126 let prefer_no_std = crate_attrs.by_key("no_std").exists();
127 let mut best_path = None;
128 let mut best_path_len = max_len;
130 if item.krate(db) == Some(from.krate) {
131 // Item was defined in the same crate that wants to import it. It cannot be found in any
132 // dependency in this case.
134 let local_imports = find_local_import_locations(db, item, from);
135 for (module_id, name) in local_imports {
136 if let Some(mut path) = find_path_inner(
138 ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
142 path.segments.push(name);
144 let new_path = if let Some(best_path) = best_path {
145 select_best_path(best_path, path, prefer_no_std)
149 best_path_len = new_path.len();
150 best_path = Some(new_path);
154 // Item was defined in some upstream crate. This means that it must be exported from one,
155 // too (unless we can't name it at all). It could *also* be (re)exported by the same crate
156 // that wants to import it here, but we always prefer to use the external path here.
158 let crate_graph = db.crate_graph();
159 let extern_paths = crate_graph[from.krate].dependencies.iter().filter_map(|dep| {
160 let import_map = db.import_map(dep.crate_id);
161 import_map.import_info_for(item).and_then(|info| {
162 // Determine best path for containing module and append last segment from `info`.
163 let mut path = find_path_inner(
165 ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
169 path.segments.push(info.path.segments.last().unwrap().clone());
174 for path in extern_paths {
175 let new_path = if let Some(best_path) = best_path {
176 select_best_path(best_path, path, prefer_no_std)
180 best_path = Some(new_path);
187 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
188 if old_path.starts_with_std() && new_path.can_start_with_std() {
190 mark::hit!(prefer_no_std_paths);
193 mark::hit!(prefer_std_paths);
196 } else if new_path.starts_with_std() && old_path.can_start_with_std() {
198 mark::hit!(prefer_no_std_paths);
201 mark::hit!(prefer_std_paths);
204 } else if new_path.len() < old_path.len() {
211 /// Finds locations in `from.krate` from which `item` can be imported by `from`.
212 fn find_local_import_locations(
213 db: &dyn DefDatabase,
216 ) -> Vec<(ModuleId, Name)> {
217 let _p = profile::span("find_local_import_locations");
219 // `from` can import anything below `from` with visibility of at least `from`, and anything
220 // above `from` with any visibility. That means we do not need to descend into private siblings
221 // of `from` (and similar).
223 let def_map = db.crate_def_map(from.krate);
225 // Compute the initial worklist. We start with all direct child modules of `from` as well as all
226 // of its (recursive) parent modules.
227 let data = &def_map.modules[from.local_id];
228 let mut worklist = data
231 .map(|child| ModuleId { krate: from.krate, local_id: *child })
232 .collect::<Vec<_>>();
233 let mut parent = data.parent;
234 while let Some(p) = parent {
235 worklist.push(ModuleId { krate: from.krate, local_id: p });
236 parent = def_map.modules[p].parent;
239 let mut seen: FxHashSet<_> = FxHashSet::default();
241 let mut locations = Vec::new();
242 while let Some(module) = worklist.pop() {
243 if !seen.insert(module) {
244 continue; // already processed this module
248 let data = if module.krate == from.krate {
249 &def_map[module.local_id]
251 // The crate might reexport a module defined in another crate.
252 ext_def_map = db.crate_def_map(module.krate);
253 &ext_def_map[module.local_id]
256 if let Some((name, vis)) = data.scope.name_of(item) {
257 if vis.is_visible_from(db, from) {
258 let is_private = if let Visibility::Module(private_to) = vis {
259 private_to.local_id == module.local_id
263 let is_original_def = if let Some(module_def_id) = item.as_module_def_id() {
264 data.scope.declarations().any(|it| it == module_def_id)
269 // Ignore private imports. these could be used if we are
270 // in a submodule of this module, but that's usually not
271 // what the user wants; and if this module can import
272 // the item and we're a submodule of it, so can we.
273 // Also this keeps the cached data smaller.
274 if !is_private || is_original_def {
275 locations.push((module, name.clone()));
280 // Descend into all modules visible from `from`.
281 for (_, per_ns) in data.scope.entries() {
282 if let Some((ModuleDefId::ModuleId(module), vis)) = per_ns.take_types_vis() {
283 if vis.is_visible_from(db, from) {
284 worklist.push(module);
295 use base_db::fixture::WithFixture;
296 use hir_expand::hygiene::Hygiene;
297 use syntax::ast::AstNode;
298 use test_utils::mark;
300 use crate::test_db::TestDB;
304 /// `code` needs to contain a cursor marker; checks that `find_path` for the
305 /// item the `path` refers to returns that same path when called from the
306 /// module the cursor is in.
307 fn check_found_path(ra_fixture: &str, path: &str) {
308 let (db, pos) = TestDB::with_position(ra_fixture);
309 let module = db.module_for_file(pos.file_id);
310 let parsed_path_file = syntax::SourceFile::parse(&format!("use {};", path));
312 parsed_path_file.syntax_node().descendants().find_map(syntax::ast::Path::cast).unwrap();
313 let mod_path = ModPath::from_src(ast_path, &Hygiene::new_unhygienic()).unwrap();
315 let crate_def_map = db.crate_def_map(module.krate);
316 let resolved = crate_def_map
321 crate::item_scope::BuiltinShadowMode::Module,
327 let found_path = find_path(&db, ItemInNs::Types(resolved), module);
329 assert_eq!(found_path, Some(mod_path));
339 check_found_path(code, "S");
349 check_found_path(code, "E::A");
361 check_found_path(code, "foo::S");
375 check_found_path(code, "super::S");
386 check_found_path(code, "self");
397 check_found_path(code, "crate");
409 check_found_path(code, "crate::S");
413 fn different_crate() {
415 //- /main.rs crate:main deps:std
417 //- /std.rs crate:std
420 check_found_path(code, "std::S");
424 fn different_crate_renamed() {
426 //- /main.rs crate:main deps:std
427 extern crate std as std_renamed;
429 //- /std.rs crate:std
432 check_found_path(code, "std_renamed::S");
436 fn partially_imported() {
437 // Tests that short paths are used even for external items, when parts of the path are
441 //- /main.rs crate:main deps:syntax
446 //- /lib.rs crate:syntax
448 pub enum ModuleItem {
458 //- /main.rs crate:main deps:syntax
462 //- /lib.rs crate:syntax
464 pub enum ModuleItem {
469 "syntax::ast::ModuleItem",
474 fn same_crate_reexport() {
478 mod foo { pub(super) struct S; }
479 pub(crate) use foo::*;
483 check_found_path(code, "bar::S");
487 fn same_crate_reexport_rename() {
491 mod foo { pub(super) struct S; }
492 pub(crate) use foo::S as U;
496 check_found_path(code, "bar::U");
500 fn different_crate_reexport() {
502 //- /main.rs crate:main deps:std
504 //- /std.rs crate:std deps:core
506 //- /core.rs crate:core
509 check_found_path(code, "std::S");
515 //- /main.rs crate:main deps:std
517 //- /std.rs crate:std
518 pub mod prelude { pub struct S; }
522 check_found_path(code, "S");
526 fn enum_variant_from_prelude() {
528 //- /main.rs crate:main deps:std
530 //- /std.rs crate:std
532 pub enum Option<T> { Some(T), None }
538 check_found_path(code, "None");
539 check_found_path(code, "Some");
551 pub mod bar { pub struct S; }
553 pub use crate::foo::bar::S;
555 check_found_path(code, "baz::S");
559 fn discount_private_imports() {
563 pub mod bar { pub struct S; }
568 // crate::S would be shorter, but using private imports seems wrong
569 check_found_path(code, "crate::bar::S");
587 check_found_path(code, "crate::foo::S");
591 fn prefer_std_paths_over_alloc() {
592 mark::check!(prefer_std_paths);
594 //- /main.rs crate:main deps:alloc,std
597 //- /std.rs crate:std deps:alloc
599 pub use alloc::sync::Arc;
602 //- /zzz.rs crate:alloc
607 check_found_path(code, "std::sync::Arc");
611 fn prefer_core_paths_over_std() {
612 mark::check!(prefer_no_std_paths);
614 //- /main.rs crate:main deps:core,std
619 //- /std.rs crate:std deps:core
622 pub use core::fmt::Error;
625 //- /zzz.rs crate:core
631 check_found_path(code, "core::fmt::Error");
635 fn prefer_alloc_paths_over_std() {
637 //- /main.rs crate:main deps:alloc,std
642 //- /std.rs crate:std deps:alloc
645 pub use alloc::sync::Arc;
648 //- /zzz.rs crate:alloc
654 check_found_path(code, "alloc::sync::Arc");
658 fn prefer_shorter_paths_if_not_alloc() {
660 //- /main.rs crate:main deps:megaalloc,std
663 //- /std.rs crate:std deps:megaalloc
665 pub use megaalloc::sync::Arc;
668 //- /zzz.rs crate:megaalloc
671 check_found_path(code, "megaalloc::Arc");
675 fn builtins_are_in_scope() {
684 check_found_path(code, "u8");
685 check_found_path(code, "u16");