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;
7 use crate::nameres::DefMap;
11 path::{ModPath, PathKind},
12 visibility::Visibility,
13 ModuleDefId, ModuleId,
16 /// Find a path that can be used to refer to a certain item. This can depend on
17 /// *from where* you're referring to the item, hence the `from` parameter.
18 pub fn find_path(db: &dyn DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
19 let _p = profile::span("find_path");
20 find_path_inner(db, item, from, MAX_PATH_LEN, None)
23 pub fn find_path_prefixed(
27 prefix_kind: PrefixKind,
28 ) -> Option<ModPath> {
29 let _p = profile::span("find_path_prefixed");
30 find_path_inner(db, item, from, MAX_PATH_LEN, Some(prefix_kind))
33 const MAX_PATH_LEN: usize = 15;
36 fn starts_with_std(&self) -> bool {
37 self.segments().first() == Some(&known::std)
40 // When std library is present, paths starting with `std::`
41 // should be preferred over paths starting with `core::` and `alloc::`
42 fn can_start_with_std(&self) -> bool {
43 let first_segment = self.segments().first();
44 first_segment == Some(&known::alloc) || first_segment == Some(&known::core)
48 fn check_self_super(def_map: &DefMap, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
49 if item == ItemInNs::Types(from.into()) {
50 // - if the item is the module we're in, use `self`
51 Some(ModPath::from_segments(PathKind::Super(0), Vec::new()))
52 } else if let Some(parent_id) = def_map[from.local_id].parent {
53 // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
54 let parent_id = def_map.module_id(parent_id);
55 if item == ItemInNs::Types(ModuleDefId::ModuleId(parent_id)) {
56 Some(ModPath::from_segments(PathKind::Super(1), Vec::new()))
65 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
67 /// Causes paths to always start with either `self`, `super`, `crate` or a crate-name.
68 /// This is the same as plain, just that paths will start with `self` iprepended f the path
69 /// starts with an identifier that is not a crate.
71 /// Causes paths to ignore imports in the local module.
73 /// Causes paths to start with `crate` where applicable, effectively forcing paths to be absolute.
79 fn prefix(self) -> PathKind {
81 PrefixKind::BySelf => PathKind::Super(0),
82 PrefixKind::Plain => PathKind::Plain,
83 PrefixKind::ByCrate => PathKind::Crate,
88 fn is_absolute(&self) -> bool {
89 self == &PrefixKind::ByCrate
98 prefixed: Option<PrefixKind>,
99 ) -> Option<ModPath> {
106 // - if the item is already in scope, return the name under which it is
107 let def_map = from.def_map(db);
108 let scope_name = def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
109 def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone())
111 if prefixed.is_none() && scope_name.is_some() {
113 .map(|scope_name| ModPath::from_segments(PathKind::Plain, vec![scope_name]));
116 // - if the item is the crate root, return `crate`
117 let root = def_map.module_id(def_map.root());
118 if item == ItemInNs::Types(ModuleDefId::ModuleId(root)) && def_map.block_id().is_none() {
119 return Some(ModPath::from_segments(PathKind::Crate, Vec::new()));
122 if prefixed.filter(PrefixKind::is_absolute).is_none() {
123 if let modpath @ Some(_) = check_self_super(&def_map, item, from) {
128 // - if the item is the crate root of a dependency crate, return the name from the extern prelude
129 for (name, def_id) in def_map.extern_prelude() {
130 if item == ItemInNs::Types(*def_id) {
131 let name = scope_name.unwrap_or_else(|| name.clone());
132 return Some(ModPath::from_segments(PathKind::Plain, vec![name]));
136 // - if the item is in the prelude, return the name from there
137 if let Some(prelude_module) = def_map.prelude() {
138 let prelude_def_map = prelude_module.def_map(db);
139 let prelude_scope: &crate::item_scope::ItemScope =
140 &prelude_def_map[prelude_module.local_id].scope;
141 if let Some((name, vis)) = prelude_scope.name_of(item) {
142 if vis.is_visible_from(db, from) {
143 return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
148 // - if the item is a builtin, it's in scope
149 if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
150 return Some(ModPath::from_segments(PathKind::Plain, vec![builtin.as_name()]));
154 // - if the item is an enum variant, refer to it via the enum
155 if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
156 if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) {
157 let data = db.enum_data(variant.parent);
158 path.push_segment(data.variants[variant.local_id].name.clone());
161 // If this doesn't work, it seems we have no way of referring to the
162 // enum; that's very weird, but there might still be a reexport of the
166 // - otherwise, look for modules containing (reexporting) it and import it from one of those
168 let crate_root = def_map.module_id(def_map.root());
169 let crate_attrs = db.attrs(crate_root.into());
170 let prefer_no_std = crate_attrs.by_key("no_std").exists();
171 let mut best_path = None;
172 let mut best_path_len = max_len;
174 if item.krate(db) == Some(from.krate) {
175 // Item was defined in the same crate that wants to import it. It cannot be found in any
176 // dependency in this case.
178 let local_imports = find_local_import_locations(db, item, from);
179 for (module_id, name) in local_imports {
180 if let Some(mut path) = find_path_inner(
182 ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
187 path.push_segment(name);
189 let new_path = if let Some(best_path) = best_path {
190 select_best_path(best_path, path, prefer_no_std)
194 best_path_len = new_path.len();
195 best_path = Some(new_path);
199 // Item was defined in some upstream crate. This means that it must be exported from one,
200 // too (unless we can't name it at all). It could *also* be (re)exported by the same crate
201 // that wants to import it here, but we always prefer to use the external path here.
203 let crate_graph = db.crate_graph();
204 let extern_paths = crate_graph[from.krate].dependencies.iter().filter_map(|dep| {
205 let import_map = db.import_map(dep.crate_id);
206 import_map.import_info_for(item).and_then(|info| {
207 // Determine best path for containing module and append last segment from `info`.
208 let mut path = find_path_inner(
210 ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
215 mark::hit!(partially_imported);
216 path.push_segment(info.path.segments.last().unwrap().clone());
221 for path in extern_paths {
222 let new_path = if let Some(best_path) = best_path {
223 select_best_path(best_path, path, prefer_no_std)
227 best_path = Some(new_path);
231 if let Some(mut prefix) = prefixed.map(PrefixKind::prefix) {
232 if matches!(prefix, PathKind::Crate | PathKind::Super(0)) && def_map.block_id().is_some() {
233 // Inner items cannot be referred to via `crate::` or `self::` paths.
234 prefix = PathKind::Plain;
237 best_path.or_else(|| {
238 scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name]))
245 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
246 if old_path.starts_with_std() && new_path.can_start_with_std() {
248 mark::hit!(prefer_no_std_paths);
251 mark::hit!(prefer_std_paths);
254 } else if new_path.starts_with_std() && old_path.can_start_with_std() {
256 mark::hit!(prefer_no_std_paths);
259 mark::hit!(prefer_std_paths);
262 } else if new_path.len() < old_path.len() {
269 /// Finds locations in `from.krate` from which `item` can be imported by `from`.
270 fn find_local_import_locations(
271 db: &dyn DefDatabase,
274 ) -> Vec<(ModuleId, Name)> {
275 let _p = profile::span("find_local_import_locations");
277 // `from` can import anything below `from` with visibility of at least `from`, and anything
278 // above `from` with any visibility. That means we do not need to descend into private siblings
279 // of `from` (and similar).
281 let def_map = from.def_map(db);
283 // Compute the initial worklist. We start with all direct child modules of `from` as well as all
284 // of its (recursive) parent modules.
285 let data = &def_map[from.local_id];
287 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>();
288 let mut parent = data.parent;
289 while let Some(p) = parent {
290 worklist.push(def_map.module_id(p));
291 parent = def_map[p].parent;
294 let mut seen: FxHashSet<_> = FxHashSet::default();
296 let mut locations = Vec::new();
297 while let Some(module) = worklist.pop() {
298 if !seen.insert(module) {
299 continue; // already processed this module
303 let data = if module.krate == from.krate {
304 &def_map[module.local_id]
306 // The crate might reexport a module defined in another crate.
307 ext_def_map = module.def_map(db);
308 &ext_def_map[module.local_id]
311 if let Some((name, vis)) = data.scope.name_of(item) {
312 if vis.is_visible_from(db, from) {
313 let is_private = if let Visibility::Module(private_to) = vis {
314 private_to.local_id == module.local_id
318 let is_original_def = if let Some(module_def_id) = item.as_module_def_id() {
319 data.scope.declarations().any(|it| it == module_def_id)
324 // Ignore private imports. these could be used if we are
325 // in a submodule of this module, but that's usually not
326 // what the user wants; and if this module can import
327 // the item and we're a submodule of it, so can we.
328 // Also this keeps the cached data smaller.
329 if !is_private || is_original_def {
330 locations.push((module, name.clone()));
335 // Descend into all modules visible from `from`.
336 for (_, per_ns) in data.scope.entries() {
337 if let Some((ModuleDefId::ModuleId(module), vis)) = per_ns.take_types_vis() {
338 if vis.is_visible_from(db, from) {
339 worklist.push(module);
350 use base_db::fixture::WithFixture;
351 use hir_expand::hygiene::Hygiene;
352 use syntax::ast::AstNode;
353 use test_utils::mark;
355 use crate::test_db::TestDB;
359 /// `code` needs to contain a cursor marker; checks that `find_path` for the
360 /// item the `path` refers to returns that same path when called from the
361 /// module the cursor is in.
362 fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKind>) {
363 let (db, pos) = TestDB::with_position(ra_fixture);
364 let module = db.module_at_position(pos);
365 let parsed_path_file = syntax::SourceFile::parse(&format!("use {};", path));
367 parsed_path_file.syntax_node().descendants().find_map(syntax::ast::Path::cast).unwrap();
368 let mod_path = ModPath::from_src(ast_path, &Hygiene::new_unhygienic()).unwrap();
370 let def_map = module.def_map(&db);
371 let resolved = def_map
376 crate::item_scope::BuiltinShadowMode::Module,
383 find_path_inner(&db, ItemInNs::Types(resolved), module, MAX_PATH_LEN, prefix_kind);
384 assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind);
394 check_found_path_(ra_fixture, unprefixed, None);
395 check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain));
396 check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate));
397 check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf));
407 check_found_path(code, "S", "S", "crate::S", "self::S");
417 check_found_path(code, "E::A", "E::A", "E::A", "E::A");
429 check_found_path(code, "foo::S", "foo::S", "crate::foo::S", "self::foo::S");
443 check_found_path(code, "super::S", "super::S", "crate::foo::S", "super::S");
454 check_found_path(code, "self", "self", "crate::foo", "self");
465 check_found_path(code, "crate", "crate", "crate", "crate");
477 check_found_path(code, "crate::S", "crate::S", "crate::S", "crate::S");
481 fn different_crate() {
483 //- /main.rs crate:main deps:std
485 //- /std.rs crate:std
488 check_found_path(code, "std::S", "std::S", "std::S", "std::S");
492 fn different_crate_renamed() {
494 //- /main.rs crate:main deps:std
495 extern crate std as std_renamed;
497 //- /std.rs crate:std
510 fn partially_imported() {
511 mark::check!(partially_imported);
512 // Tests that short paths are used even for external items, when parts of the path are
515 //- /main.rs crate:main deps:syntax
520 //- /lib.rs crate:syntax
522 pub enum ModuleItem {
530 "syntax::ast::ModuleItem",
531 "syntax::ast::ModuleItem",
532 "syntax::ast::ModuleItem",
536 //- /main.rs crate:main deps:syntax
540 //- /lib.rs crate:syntax
542 pub enum ModuleItem {
549 "syntax::ast::ModuleItem",
550 "syntax::ast::ModuleItem",
551 "syntax::ast::ModuleItem",
552 "syntax::ast::ModuleItem",
557 fn same_crate_reexport() {
561 mod foo { pub(super) struct S; }
562 pub(crate) use foo::*;
566 check_found_path(code, "bar::S", "bar::S", "crate::bar::S", "self::bar::S");
570 fn same_crate_reexport_rename() {
574 mod foo { pub(super) struct S; }
575 pub(crate) use foo::S as U;
579 check_found_path(code, "bar::U", "bar::U", "crate::bar::U", "self::bar::U");
583 fn different_crate_reexport() {
585 //- /main.rs crate:main deps:std
587 //- /std.rs crate:std deps:core
589 //- /core.rs crate:core
592 check_found_path(code, "std::S", "std::S", "std::S", "std::S");
598 //- /main.rs crate:main deps:std
600 //- /std.rs crate:std
601 pub mod prelude { pub struct S; }
605 check_found_path(code, "S", "S", "S", "S");
609 fn enum_variant_from_prelude() {
611 //- /main.rs crate:main deps:std
613 //- /std.rs crate:std
615 pub enum Option<T> { Some(T), None }
621 check_found_path(code, "None", "None", "None", "None");
622 check_found_path(code, "Some", "Some", "Some", "Some");
634 pub mod bar { pub struct S; }
636 pub use crate::foo::bar::S;
638 check_found_path(code, "baz::S", "baz::S", "crate::baz::S", "self::baz::S");
642 fn discount_private_imports() {
646 pub mod bar { pub struct S; }
651 // crate::S would be shorter, but using private imports seems wrong
652 check_found_path(code, "crate::bar::S", "crate::bar::S", "crate::bar::S", "crate::bar::S");
670 check_found_path(code, "crate::foo::S", "crate::foo::S", "crate::foo::S", "crate::foo::S");
674 fn prefer_std_paths_over_alloc() {
675 mark::check!(prefer_std_paths);
677 //- /main.rs crate:main deps:alloc,std
680 //- /std.rs crate:std deps:alloc
682 pub use alloc::sync::Arc;
685 //- /zzz.rs crate:alloc
700 fn prefer_core_paths_over_std() {
701 mark::check!(prefer_no_std_paths);
703 //- /main.rs crate:main deps:core,std
708 //- /std.rs crate:std deps:core
711 pub use core::fmt::Error;
714 //- /zzz.rs crate:core
730 fn prefer_alloc_paths_over_std() {
732 //- /main.rs crate:main deps:alloc,std
737 //- /std.rs crate:std deps:alloc
740 pub use alloc::sync::Arc;
743 //- /zzz.rs crate:alloc
759 fn prefer_shorter_paths_if_not_alloc() {
761 //- /main.rs crate:main deps:megaalloc,std
764 //- /std.rs crate:std deps:megaalloc
766 pub use megaalloc::sync::Arc;
769 //- /zzz.rs crate:megaalloc
782 fn builtins_are_in_scope() {
791 check_found_path(code, "u8", "u8", "u8", "u8");
792 check_found_path(code, "u16", "u16", "u16", "u16");
812 fn inner_items_from_outer_scope() {
830 fn inner_items_from_inner_module() {
851 fn inner_items_from_parent_module() {
852 // FIXME: ItemTree currently associates all inner items with `main`. Luckily, this sort of
853 // code is very rare, so this isn't terrible.
854 // To fix it, we should probably build dedicated `ItemTree`s for inner items, and not store
855 // them in the file's main ItemTree. This would also allow us to stop parsing function
856 // bodies when we only want to compute the crate's main DefMap.