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 let mut visited_modules = FxHashSet::default();
22 find_path_inner(db, item, from, MAX_PATH_LEN, None, &mut visited_modules)
25 pub fn find_path_prefixed(
29 prefix_kind: PrefixKind,
30 ) -> Option<ModPath> {
31 let _p = profile::span("find_path_prefixed");
32 let mut visited_modules = FxHashSet::default();
33 find_path_inner(db, item, from, MAX_PATH_LEN, Some(prefix_kind), &mut visited_modules)
36 const MAX_PATH_LEN: usize = 15;
39 fn starts_with_std(&self) -> bool {
40 self.segments().first() == Some(&known::std)
43 // When std library is present, paths starting with `std::`
44 // should be preferred over paths starting with `core::` and `alloc::`
45 fn can_start_with_std(&self) -> bool {
46 let first_segment = self.segments().first();
47 first_segment == Some(&known::alloc) || first_segment == Some(&known::core)
51 fn check_self_super(def_map: &DefMap, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
52 if item == ItemInNs::Types(from.into()) {
53 // - if the item is the module we're in, use `self`
54 Some(ModPath::from_segments(PathKind::Super(0), Vec::new()))
55 } else if let Some(parent_id) = def_map[from.local_id].parent {
56 // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
57 let parent_id = def_map.module_id(parent_id);
58 if item == ItemInNs::Types(ModuleDefId::ModuleId(parent_id)) {
59 Some(ModPath::from_segments(PathKind::Super(1), Vec::new()))
68 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
70 /// Causes paths to always start with either `self`, `super`, `crate` or a crate-name.
71 /// This is the same as plain, just that paths will start with `self` iprepended f the path
72 /// starts with an identifier that is not a crate.
74 /// Causes paths to ignore imports in the local module.
76 /// Causes paths to start with `crate` where applicable, effectively forcing paths to be absolute.
82 fn prefix(self) -> PathKind {
84 PrefixKind::BySelf => PathKind::Super(0),
85 PrefixKind::Plain => PathKind::Plain,
86 PrefixKind::ByCrate => PathKind::Crate,
91 fn is_absolute(&self) -> bool {
92 self == &PrefixKind::ByCrate
101 mut prefixed: Option<PrefixKind>,
102 visited_modules: &mut FxHashSet<ModuleId>,
103 ) -> Option<ModPath> {
110 // - if the item is already in scope, return the name under which it is
111 let def_map = from.def_map(db);
112 let scope_name = def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
113 def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone())
115 if prefixed.is_none() && scope_name.is_some() {
117 .map(|scope_name| ModPath::from_segments(PathKind::Plain, vec![scope_name]));
120 // - if the item is the crate root, return `crate`
121 let root = def_map.crate_root(db);
122 if item == ItemInNs::Types(ModuleDefId::ModuleId(root)) {
123 return Some(ModPath::from_segments(PathKind::Crate, Vec::new()));
126 if prefixed.filter(PrefixKind::is_absolute).is_none() {
127 if let modpath @ Some(_) = check_self_super(&def_map, item, from) {
132 // - if the item is the crate root of a dependency crate, return the name from the extern prelude
133 let root_def_map = root.def_map(db);
134 for (name, def_id) in root_def_map.extern_prelude() {
135 if item == ItemInNs::Types(*def_id) {
136 let name = scope_name.unwrap_or_else(|| name.clone());
138 let name_already_occupied_in_type_ns = def_map
139 .with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
140 def_map[local_id].scope.get(&name).take_types().filter(|&id| id != *def_id)
143 return Some(ModPath::from_segments(
144 if name_already_occupied_in_type_ns {
145 cov_mark::hit!(ambiguous_crate_start);
155 // - if the item is in the prelude, return the name from there
156 if let Some(prelude_module) = root_def_map.prelude() {
157 // Preludes in block DefMaps are ignored, only the crate DefMap is searched
158 let prelude_def_map = prelude_module.def_map(db);
159 let prelude_scope: &crate::item_scope::ItemScope =
160 &prelude_def_map[prelude_module.local_id].scope;
161 if let Some((name, vis)) = prelude_scope.name_of(item) {
162 if vis.is_visible_from(db, from) {
163 return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
168 // - if the item is a builtin, it's in scope
169 if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
170 return Some(ModPath::from_segments(PathKind::Plain, vec![builtin.as_name()]));
174 // - if the item is an enum variant, refer to it via the enum
175 if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
176 if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) {
177 let data = db.enum_data(variant.parent);
178 path.push_segment(data.variants[variant.local_id].name.clone());
181 // If this doesn't work, it seems we have no way of referring to the
182 // enum; that's very weird, but there might still be a reexport of the
186 // - otherwise, look for modules containing (reexporting) it and import it from one of those
188 let crate_root = def_map.crate_root(db);
189 let crate_attrs = db.attrs(crate_root.into());
190 let prefer_no_std = crate_attrs.by_key("no_std").exists();
191 let mut best_path = None;
192 let mut best_path_len = max_len;
194 if item.krate(db) == Some(from.krate) {
195 // Item was defined in the same crate that wants to import it. It cannot be found in any
196 // dependency in this case.
197 for (module_id, name) in find_local_import_locations(db, item, from) {
198 if !visited_modules.insert(module_id) {
199 cov_mark::hit!(recursive_imports);
202 if let Some(mut path) = find_path_inner(
204 ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
210 path.push_segment(name);
212 let new_path = if let Some(best_path) = best_path {
213 select_best_path(best_path, path, prefer_no_std)
217 best_path_len = new_path.len();
218 best_path = Some(new_path);
222 // Item was defined in some upstream crate. This means that it must be exported from one,
223 // too (unless we can't name it at all). It could *also* be (re)exported by the same crate
224 // that wants to import it here, but we always prefer to use the external path here.
226 let crate_graph = db.crate_graph();
227 let extern_paths = crate_graph[from.krate].dependencies.iter().filter_map(|dep| {
228 let import_map = db.import_map(dep.crate_id);
229 import_map.import_info_for(item).and_then(|info| {
230 // Determine best path for containing module and append last segment from `info`.
231 let mut path = find_path_inner(
233 ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
239 cov_mark::hit!(partially_imported);
240 path.push_segment(info.path.segments.last().unwrap().clone());
245 for path in extern_paths {
246 let new_path = if let Some(best_path) = best_path {
247 select_best_path(best_path, path, prefer_no_std)
251 best_path = Some(new_path);
255 // If the item is declared inside a block expression, don't use a prefix, as we don't handle
256 // that correctly (FIXME).
257 if let Some(item_module) = item.as_module_def_id().and_then(|did| did.module(db)) {
258 if item_module.def_map(db).block_id().is_some() && prefixed.is_some() {
259 cov_mark::hit!(prefixed_in_block_expression);
260 prefixed = Some(PrefixKind::Plain);
264 if let Some(prefix) = prefixed.map(PrefixKind::prefix) {
265 best_path.or_else(|| {
266 scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name]))
273 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
274 if old_path.starts_with_std() && new_path.can_start_with_std() {
276 cov_mark::hit!(prefer_no_std_paths);
279 cov_mark::hit!(prefer_std_paths);
282 } else if new_path.starts_with_std() && old_path.can_start_with_std() {
284 cov_mark::hit!(prefer_no_std_paths);
287 cov_mark::hit!(prefer_std_paths);
290 } else if new_path.len() < old_path.len() {
297 /// Finds locations in `from.krate` from which `item` can be imported by `from`.
298 fn find_local_import_locations(
299 db: &dyn DefDatabase,
302 ) -> Vec<(ModuleId, Name)> {
303 let _p = profile::span("find_local_import_locations");
305 // `from` can import anything below `from` with visibility of at least `from`, and anything
306 // above `from` with any visibility. That means we do not need to descend into private siblings
307 // of `from` (and similar).
309 let def_map = from.def_map(db);
311 // Compute the initial worklist. We start with all direct child modules of `from` as well as all
312 // of its (recursive) parent modules.
313 let data = &def_map[from.local_id];
315 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>();
316 // FIXME: do we need to traverse out of block expressions here?
317 for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) {
318 worklist.push(ancestor);
321 let def_map = def_map.crate_root(db).def_map(db);
323 let mut seen: FxHashSet<_> = FxHashSet::default();
325 let mut locations = Vec::new();
326 while let Some(module) = worklist.pop() {
327 if !seen.insert(module) {
328 continue; // already processed this module
332 let data = if module.krate == from.krate {
333 if module.block.is_some() {
334 // Re-query the block's DefMap
335 ext_def_map = module.def_map(db);
336 &ext_def_map[module.local_id]
338 // Reuse the root DefMap
339 &def_map[module.local_id]
342 // The crate might reexport a module defined in another crate.
343 ext_def_map = module.def_map(db);
344 &ext_def_map[module.local_id]
347 if let Some((name, vis)) = data.scope.name_of(item) {
348 if vis.is_visible_from(db, from) {
349 let is_private = if let Visibility::Module(private_to) = vis {
350 private_to.local_id == module.local_id
354 let is_original_def = if let Some(module_def_id) = item.as_module_def_id() {
355 data.scope.declarations().any(|it| it == module_def_id)
360 // Ignore private imports. these could be used if we are
361 // in a submodule of this module, but that's usually not
362 // what the user wants; and if this module can import
363 // the item and we're a submodule of it, so can we.
364 // Also this keeps the cached data smaller.
365 if !is_private || is_original_def {
366 locations.push((module, name.clone()));
371 // Descend into all modules visible from `from`.
372 for (_, per_ns) in data.scope.entries() {
373 if let Some((ModuleDefId::ModuleId(module), vis)) = per_ns.take_types_vis() {
374 if vis.is_visible_from(db, from) {
375 worklist.push(module);
386 use base_db::fixture::WithFixture;
387 use hir_expand::hygiene::Hygiene;
388 use syntax::ast::AstNode;
390 use crate::test_db::TestDB;
394 /// `code` needs to contain a cursor marker; checks that `find_path` for the
395 /// item the `path` refers to returns that same path when called from the
396 /// module the cursor is in.
397 fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKind>) {
398 let (db, pos) = TestDB::with_position(ra_fixture);
399 let module = db.module_at_position(pos);
400 let parsed_path_file = syntax::SourceFile::parse(&format!("use {};", path));
402 parsed_path_file.syntax_node().descendants().find_map(syntax::ast::Path::cast).unwrap();
403 let mod_path = ModPath::from_src(&db, ast_path, &Hygiene::new_unhygienic()).unwrap();
405 let def_map = module.def_map(&db);
406 let resolved = def_map
411 crate::item_scope::BuiltinShadowMode::Module,
417 let mut visited_modules = FxHashSet::default();
418 let found_path = find_path_inner(
420 ItemInNs::Types(resolved),
424 &mut visited_modules,
426 assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind);
436 check_found_path_(ra_fixture, unprefixed, None);
437 check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain));
438 check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate));
439 check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf));
555 fn different_crate() {
558 //- /main.rs crate:main deps:std
560 //- /std.rs crate:std
571 fn different_crate_renamed() {
574 //- /main.rs crate:main deps:std
575 extern crate std as std_renamed;
577 //- /std.rs crate:std
588 fn partially_imported() {
589 cov_mark::check!(partially_imported);
590 // Tests that short paths are used even for external items, when parts of the path are
594 //- /main.rs crate:main deps:syntax
599 //- /lib.rs crate:syntax
601 pub enum ModuleItem {
607 "syntax::ast::ModuleItem",
608 "syntax::ast::ModuleItem",
609 "syntax::ast::ModuleItem",
614 //- /main.rs crate:main deps:syntax
617 //- /lib.rs crate:syntax
619 pub enum ModuleItem {
624 "syntax::ast::ModuleItem",
625 "syntax::ast::ModuleItem",
626 "syntax::ast::ModuleItem",
627 "syntax::ast::ModuleItem",
632 fn same_crate_reexport() {
636 mod foo { pub(super) struct S; }
637 pub(crate) use foo::*;
649 fn same_crate_reexport_rename() {
653 mod foo { pub(super) struct S; }
654 pub(crate) use foo::S as U;
666 fn different_crate_reexport() {
669 //- /main.rs crate:main deps:std
671 //- /std.rs crate:std deps:core
673 //- /core.rs crate:core
687 //- /main.rs crate:main deps:std
689 //- /std.rs crate:std
704 fn enum_variant_from_prelude() {
706 //- /main.rs crate:main deps:std
708 //- /std.rs crate:std
711 pub enum Option<T> { Some(T), None }
716 check_found_path(code, "None", "None", "None", "None");
717 check_found_path(code, "Some", "Some", "Some", "Some");
730 pub mod bar { pub struct S; }
732 pub use crate::foo::bar::S;
742 fn discount_private_imports() {
747 pub mod bar { pub struct S; }
752 // crate::S would be shorter, but using private imports seems wrong
784 fn prefer_std_paths_over_alloc() {
785 cov_mark::check!(prefer_std_paths);
788 //- /main.rs crate:main deps:alloc,std
791 //- /std.rs crate:std deps:alloc
793 pub use alloc::sync::Arc;
796 //- /zzz.rs crate:alloc
809 fn prefer_core_paths_over_std() {
810 cov_mark::check!(prefer_no_std_paths);
813 //- /main.rs crate:main deps:core,std
818 //- /std.rs crate:std deps:core
821 pub use core::fmt::Error;
824 //- /zzz.rs crate:core
838 fn prefer_alloc_paths_over_std() {
841 //- /main.rs crate:main deps:alloc,std
846 //- /std.rs crate:std deps:alloc
849 pub use alloc::sync::Arc;
852 //- /zzz.rs crate:alloc
866 fn prefer_shorter_paths_if_not_alloc() {
869 //- /main.rs crate:main deps:megaalloc,std
872 //- /std.rs crate:std deps:megaalloc
874 pub use megaalloc::sync::Arc;
877 //- /zzz.rs crate:megaalloc
888 fn builtins_are_in_scope() {
896 check_found_path(code, "u8", "u8", "u8", "u8");
897 check_found_path(code, "u16", "u16", "u16", "u16");
917 fn inner_items_from_outer_scope() {
935 fn inner_items_from_inner_module() {
936 cov_mark::check!(prefixed_in_block_expression);
956 fn outer_items_with_inner_items_present() {
960 pub struct CompleteMe;
968 // FIXME: these could use fewer/better prefixes
969 "module::CompleteMe",
970 "crate::module::CompleteMe",
971 "crate::module::CompleteMe",
972 "crate::module::CompleteMe",
977 fn from_inside_module() {
978 // This worked correctly, but the test suite logic was broken.
979 cov_mark::check!(submodule_in_testdb);
1000 fn from_inside_module_with_inner_items() {
1022 fn recursive_pub_mod_reexport() {
1023 cov_mark::check!(recursive_imports);
1027 let _ = 22_i32.as_name$0();
1032 fn as_name(&self) -> String;
1034 impl AsName for i32 {
1035 fn as_name(&self) -> String {
1036 format!("Name: {}", self)
1039 pub use crate::name;
1044 "crate::name::AsName",
1045 "self::name::AsName",
1053 //- /main.rs crate:main deps:dep
1055 //- /dep.rs crate:dep
1065 //- /main.rs crate:main deps:dep
1070 //- /dep.rs crate:dep
1080 fn prelude_with_inner_items() {
1083 //- /main.rs crate:main deps:std
1088 //- /std.rs crate:std
1091 pub enum Option { None }