1 //! An algorithm to find a path to refer to a certain item.
5 use hir_expand::name::{known, AsName, Name};
6 use rustc_hash::FxHashSet;
12 path::{ModPath, PathKind},
13 visibility::Visibility,
14 ModuleDefId, ModuleId,
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, None)
24 pub fn find_path_prefixed(
28 prefix_kind: PrefixKind,
29 ) -> Option<ModPath> {
30 let _p = profile::span("find_path_prefixed");
31 find_path_inner(db, item, from, Some(prefix_kind))
34 const MAX_PATH_LEN: usize = 15;
37 fn starts_with_std(&self) -> bool;
38 fn can_start_with_std(&self) -> bool;
41 impl ModPathExt for ModPath {
42 fn starts_with_std(&self) -> bool {
43 self.segments().first() == Some(&known::std)
46 // Can we replace the first segment with `std::` and still get a valid, identical path?
47 fn can_start_with_std(&self) -> bool {
48 let first_segment = self.segments().first();
49 first_segment == Some(&known::alloc) || first_segment == Some(&known::core)
53 fn check_self_super(def_map: &DefMap, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
54 if item == ItemInNs::Types(from.into()) {
55 // - if the item is the module we're in, use `self`
56 Some(ModPath::from_segments(PathKind::Super(0), None))
57 } else if let Some(parent_id) = def_map[from.local_id].parent {
58 // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
59 let parent_id = def_map.module_id(parent_id);
60 if item == ItemInNs::Types(ModuleDefId::ModuleId(parent_id)) {
61 Some(ModPath::from_segments(PathKind::Super(1), None))
70 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
72 /// Causes paths to always start with either `self`, `super`, `crate` or a crate-name.
73 /// This is the same as plain, just that paths will start with `self` iprepended f the path
74 /// starts with an identifier that is not a crate.
76 /// Causes paths to ignore imports in the local module.
78 /// Causes paths to start with `crate` where applicable, effectively forcing paths to be absolute.
84 fn prefix(self) -> PathKind {
86 PrefixKind::BySelf => PathKind::Super(0),
87 PrefixKind::Plain => PathKind::Plain,
88 PrefixKind::ByCrate => PathKind::Crate,
93 fn is_absolute(&self) -> bool {
94 self == &PrefixKind::ByCrate
97 /// Attempts to find a path to refer to the given `item` visible from the `from` ModuleId
102 prefixed: Option<PrefixKind>,
103 ) -> Option<ModPath> {
104 // FIXME: Do fast path for std/core libs?
106 let mut visited_modules = FxHashSet::default();
107 let def_map = from.def_map(db);
108 find_path_inner_(db, &def_map, from, item, MAX_PATH_LEN, prefixed, &mut visited_modules)
112 db: &dyn DefDatabase,
117 mut prefixed: Option<PrefixKind>,
118 visited_modules: &mut FxHashSet<ModuleId>,
119 ) -> Option<ModPath> {
126 // - if the item is already in scope, return the name under which it is
127 let scope_name = def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
128 def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone())
130 if prefixed.is_none() {
131 if let Some(scope_name) = scope_name {
132 return Some(ModPath::from_segments(PathKind::Plain, Some(scope_name)));
136 // - if the item is a builtin, it's in scope
137 if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
138 return Some(ModPath::from_segments(PathKind::Plain, Some(builtin.as_name())));
141 // - if the item is the crate root, return `crate`
142 let crate_root = def_map.crate_root(db);
143 if item == ItemInNs::Types(ModuleDefId::ModuleId(crate_root)) {
144 return Some(ModPath::from_segments(PathKind::Crate, None));
147 if prefixed.filter(PrefixKind::is_absolute).is_none() {
148 if let modpath @ Some(_) = check_self_super(&def_map, item, from) {
153 // - if the item is the crate root of a dependency crate, return the name from the extern prelude
154 let root_def_map = crate_root.def_map(db);
155 if let ItemInNs::Types(ModuleDefId::ModuleId(item)) = item {
156 for (name, &def_id) in root_def_map.extern_prelude() {
158 let name = scope_name.unwrap_or_else(|| name.clone());
160 let name_already_occupied_in_type_ns = def_map
161 .with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
165 .filter(|&(id, _)| id != ModuleDefId::ModuleId(def_id))
168 let kind = if name_already_occupied_in_type_ns {
169 cov_mark::hit!(ambiguous_crate_start);
174 return Some(ModPath::from_segments(kind, Some(name)));
179 // - if the item is in the prelude, return the name from there
180 if let Some(prelude_module) = root_def_map.prelude() {
181 // Preludes in block DefMaps are ignored, only the crate DefMap is searched
182 let prelude_def_map = prelude_module.def_map(db);
183 let prelude_scope = &prelude_def_map[prelude_module.local_id].scope;
184 if let Some((name, vis)) = prelude_scope.name_of(item) {
185 if vis.is_visible_from(db, from) {
186 return Some(ModPath::from_segments(PathKind::Plain, Some(name.clone())));
192 // - if the item is an enum variant, refer to it via the enum
193 if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
194 if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) {
195 let data = db.enum_data(variant.parent);
196 path.push_segment(data.variants[variant.local_id].name.clone());
199 // If this doesn't work, it seems we have no way of referring to the
200 // enum; that's very weird, but there might still be a reexport of the
204 // - otherwise, look for modules containing (reexporting) it and import it from one of those
205 let prefer_no_std = db.crate_supports_no_std(crate_root.krate);
206 let mut best_path = None;
207 let mut best_path_len = max_len;
209 if item.krate(db) == Some(from.krate) {
210 // Item was defined in the same crate that wants to import it. It cannot be found in any
211 // dependency in this case.
212 // FIXME: this should have a fast path that doesn't look through the prelude again?
213 for (module_id, name) in find_local_import_locations(db, item, from) {
214 if !visited_modules.insert(module_id) {
215 cov_mark::hit!(recursive_imports);
218 if let Some(mut path) = find_path_inner_(
222 ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
227 path.push_segment(name);
229 let new_path = match best_path {
230 Some(best_path) => select_best_path(best_path, path, prefer_no_std),
233 best_path_len = new_path.len();
234 best_path = Some(new_path);
238 // Item was defined in some upstream crate. This means that it must be exported from one,
239 // too (unless we can't name it at all). It could *also* be (re)exported by the same crate
240 // that wants to import it here, but we always prefer to use the external path here.
242 let crate_graph = db.crate_graph();
243 let extern_paths = crate_graph[from.krate].dependencies.iter().filter_map(|dep| {
244 let import_map = db.import_map(dep.crate_id);
245 import_map.import_info_for(item).and_then(|info| {
246 // Determine best path for containing module and append last segment from `info`.
247 // FIXME: we should guide this to look up the path locally, or from the same crate again?
248 let mut path = find_path_inner_(
252 ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
257 cov_mark::hit!(partially_imported);
258 path.push_segment(info.path.segments.last()?.clone());
263 for path in extern_paths {
264 let new_path = match best_path {
265 Some(best_path) => select_best_path(best_path, path, prefer_no_std),
268 best_path = Some(new_path);
272 // If the item is declared inside a block expression, don't use a prefix, as we don't handle
273 // that correctly (FIXME).
274 if let Some(item_module) = item.as_module_def_id().and_then(|did| did.module(db)) {
275 if item_module.def_map(db).block_id().is_some() && prefixed.is_some() {
276 cov_mark::hit!(prefixed_in_block_expression);
277 prefixed = Some(PrefixKind::Plain);
281 match prefixed.map(PrefixKind::prefix) {
282 Some(prefix) => best_path.or_else(|| {
283 scope_name.map(|scope_name| ModPath::from_segments(prefix, Some(scope_name)))
289 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
290 if old_path.starts_with_std() && new_path.can_start_with_std() {
292 cov_mark::hit!(prefer_no_std_paths);
295 cov_mark::hit!(prefer_std_paths);
298 } else if new_path.starts_with_std() && old_path.can_start_with_std() {
300 cov_mark::hit!(prefer_no_std_paths);
303 cov_mark::hit!(prefer_std_paths);
306 } else if new_path.len() < old_path.len() {
313 /// Finds locations in `from.krate` from which `item` can be imported by `from`.
314 fn find_local_import_locations(
315 db: &dyn DefDatabase,
318 ) -> Vec<(ModuleId, Name)> {
319 let _p = profile::span("find_local_import_locations");
321 // `from` can import anything below `from` with visibility of at least `from`, and anything
322 // above `from` with any visibility. That means we do not need to descend into private siblings
323 // of `from` (and similar).
325 let def_map = from.def_map(db);
327 // Compute the initial worklist. We start with all direct child modules of `from` as well as all
328 // of its (recursive) parent modules.
329 let data = &def_map[from.local_id];
331 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>();
332 // FIXME: do we need to traverse out of block expressions here?
333 for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) {
334 worklist.push(ancestor);
337 let def_map = def_map.crate_root(db).def_map(db);
339 let mut seen: FxHashSet<_> = FxHashSet::default();
341 let mut locations = Vec::new();
342 while let Some(module) = worklist.pop() {
343 if !seen.insert(module) {
344 continue; // already processed this module
348 let data = if module.krate == from.krate {
349 if module.block.is_some() {
350 // Re-query the block's DefMap
351 ext_def_map = module.def_map(db);
352 &ext_def_map[module.local_id]
354 // Reuse the root DefMap
355 &def_map[module.local_id]
358 // The crate might reexport a module defined in another crate.
359 ext_def_map = module.def_map(db);
360 &ext_def_map[module.local_id]
363 if let Some((name, vis)) = data.scope.name_of(item) {
364 if vis.is_visible_from(db, from) {
365 let is_private = match vis {
366 Visibility::Module(private_to) => private_to.local_id == module.local_id,
367 Visibility::Public => false,
369 let is_original_def = match item.as_module_def_id() {
370 Some(module_def_id) => data.scope.declarations().any(|it| it == module_def_id),
374 // Ignore private imports. these could be used if we are
375 // in a submodule of this module, but that's usually not
376 // what the user wants; and if this module can import
377 // the item and we're a submodule of it, so can we.
378 // Also this keeps the cached data smaller.
379 if !is_private || is_original_def {
380 locations.push((module, name.clone()));
385 // Descend into all modules visible from `from`.
386 for (ty, vis) in data.scope.types() {
387 if let ModuleDefId::ModuleId(module) = ty {
388 if vis.is_visible_from(db, from) {
389 worklist.push(module);
400 use base_db::fixture::WithFixture;
401 use hir_expand::hygiene::Hygiene;
402 use syntax::ast::AstNode;
404 use crate::test_db::TestDB;
408 /// `code` needs to contain a cursor marker; checks that `find_path` for the
409 /// item the `path` refers to returns that same path when called from the
410 /// module the cursor is in.
411 fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKind>) {
412 let (db, pos) = TestDB::with_position(ra_fixture);
413 let module = db.module_at_position(pos);
414 let parsed_path_file = syntax::SourceFile::parse(&format!("use {};", path));
416 parsed_path_file.syntax_node().descendants().find_map(syntax::ast::Path::cast).unwrap();
417 let mod_path = ModPath::from_src(&db, ast_path, &Hygiene::new_unhygienic()).unwrap();
419 let def_map = module.def_map(&db);
420 let resolved = def_map
425 crate::item_scope::BuiltinShadowMode::Module,
431 let found_path = find_path_inner(&db, ItemInNs::Types(resolved), module, prefix_kind);
432 assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind);
442 check_found_path_(ra_fixture, unprefixed, None);
443 check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain));
444 check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate));
445 check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf));
561 fn different_crate() {
564 //- /main.rs crate:main deps:std
566 //- /std.rs crate:std
577 fn different_crate_renamed() {
580 //- /main.rs crate:main deps:std
581 extern crate std as std_renamed;
583 //- /std.rs crate:std
594 fn partially_imported() {
595 cov_mark::check!(partially_imported);
596 // Tests that short paths are used even for external items, when parts of the path are
600 //- /main.rs crate:main deps:syntax
605 //- /lib.rs crate:syntax
607 pub enum ModuleItem {
613 "syntax::ast::ModuleItem",
614 "syntax::ast::ModuleItem",
615 "syntax::ast::ModuleItem",
620 //- /main.rs crate:main deps:syntax
623 //- /lib.rs crate:syntax
625 pub enum ModuleItem {
630 "syntax::ast::ModuleItem",
631 "syntax::ast::ModuleItem",
632 "syntax::ast::ModuleItem",
633 "syntax::ast::ModuleItem",
638 fn same_crate_reexport() {
642 mod foo { pub(super) struct S; }
643 pub(crate) use foo::*;
655 fn same_crate_reexport_rename() {
659 mod foo { pub(super) struct S; }
660 pub(crate) use foo::S as U;
672 fn different_crate_reexport() {
675 //- /main.rs crate:main deps:std
677 //- /std.rs crate:std deps:core
679 //- /core.rs crate:core
693 //- /main.rs crate:main deps:std
695 //- /std.rs crate:std
710 fn enum_variant_from_prelude() {
712 //- /main.rs crate:main deps:std
714 //- /std.rs crate:std
717 pub enum Option<T> { Some(T), None }
722 check_found_path(code, "None", "None", "None", "None");
723 check_found_path(code, "Some", "Some", "Some", "Some");
736 pub mod bar { pub struct S; }
738 pub use crate::foo::bar::S;
748 fn discount_private_imports() {
753 pub mod bar { pub struct S; }
758 // crate::S would be shorter, but using private imports seems wrong
790 fn prefer_std_paths_over_alloc() {
791 cov_mark::check!(prefer_std_paths);
794 //- /main.rs crate:main deps:alloc,std
797 //- /std.rs crate:std deps:alloc
799 pub use alloc::sync::Arc;
802 //- /zzz.rs crate:alloc
815 fn prefer_core_paths_over_std() {
816 cov_mark::check!(prefer_no_std_paths);
819 //- /main.rs crate:main deps:core,std
824 //- /std.rs crate:std deps:core
827 pub use core::fmt::Error;
830 //- /zzz.rs crate:core
842 // Should also work (on a best-effort basis) if `no_std` is conditional.
845 //- /main.rs crate:main deps:core,std
846 #![cfg_attr(not(test), no_std)]
850 //- /std.rs crate:std deps:core
853 pub use core::fmt::Error;
856 //- /zzz.rs crate:core
870 fn prefer_alloc_paths_over_std() {
873 //- /main.rs crate:main deps:alloc,std
878 //- /std.rs crate:std deps:alloc
881 pub use alloc::sync::Arc;
884 //- /zzz.rs crate:alloc
898 fn prefer_shorter_paths_if_not_alloc() {
901 //- /main.rs crate:main deps:megaalloc,std
904 //- /std.rs crate:std deps:megaalloc
906 pub use megaalloc::sync::Arc;
909 //- /zzz.rs crate:megaalloc
920 fn builtins_are_in_scope() {
928 check_found_path(code, "u8", "u8", "u8", "u8");
929 check_found_path(code, "u16", "u16", "u16", "u16");
949 fn inner_items_from_outer_scope() {
967 fn inner_items_from_inner_module() {
968 cov_mark::check!(prefixed_in_block_expression);
988 fn outer_items_with_inner_items_present() {
992 pub struct CompleteMe;
1000 // FIXME: these could use fewer/better prefixes
1001 "module::CompleteMe",
1002 "crate::module::CompleteMe",
1003 "crate::module::CompleteMe",
1004 "crate::module::CompleteMe",
1009 fn from_inside_module() {
1010 // This worked correctly, but the test suite logic was broken.
1011 cov_mark::check!(submodule_in_testdb);
1032 fn from_inside_module_with_inner_items() {
1054 fn recursive_pub_mod_reexport() {
1055 cov_mark::check!(recursive_imports);
1059 let _ = 22_i32.as_name$0();
1064 fn as_name(&self) -> String;
1066 impl AsName for i32 {
1067 fn as_name(&self) -> String {
1068 format!("Name: {}", self)
1071 pub use crate::name;
1076 "crate::name::AsName",
1077 "self::name::AsName",
1085 //- /main.rs crate:main deps:dep
1087 //- /dep.rs crate:dep
1097 //- /main.rs crate:main deps:dep
1102 //- /dep.rs crate:dep
1112 fn prelude_with_inner_items() {
1115 //- /main.rs crate:main deps:std
1120 //- /std.rs crate:std
1123 pub enum Option { None }