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 // When std library is present, paths starting with `std::`
47 // should be preferred over paths starting with `core::` and `alloc::`
48 fn can_start_with_std(&self) -> bool {
49 let first_segment = self.segments().first();
50 first_segment == Some(&known::alloc) || first_segment == Some(&known::core)
54 fn check_self_super(def_map: &DefMap, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
55 if item == ItemInNs::Types(from.into()) {
56 // - if the item is the module we're in, use `self`
57 Some(ModPath::from_segments(PathKind::Super(0), None))
58 } else if let Some(parent_id) = def_map[from.local_id].parent {
59 // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
60 let parent_id = def_map.module_id(parent_id);
61 if item == ItemInNs::Types(ModuleDefId::ModuleId(parent_id)) {
62 Some(ModPath::from_segments(PathKind::Super(1), None))
71 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
73 /// Causes paths to always start with either `self`, `super`, `crate` or a crate-name.
74 /// This is the same as plain, just that paths will start with `self` iprepended f the path
75 /// starts with an identifier that is not a crate.
77 /// Causes paths to ignore imports in the local module.
79 /// Causes paths to start with `crate` where applicable, effectively forcing paths to be absolute.
85 fn prefix(self) -> PathKind {
87 PrefixKind::BySelf => PathKind::Super(0),
88 PrefixKind::Plain => PathKind::Plain,
89 PrefixKind::ByCrate => PathKind::Crate,
94 fn is_absolute(&self) -> bool {
95 self == &PrefixKind::ByCrate
98 /// Attempts to find a path to refer to the given `item` visible from the `from` ModuleId
100 db: &dyn DefDatabase,
103 prefixed: Option<PrefixKind>,
104 ) -> Option<ModPath> {
105 // FIXME: Do fast path for std/core libs?
107 let mut visited_modules = FxHashSet::default();
108 let def_map = from.def_map(db);
109 find_path_inner_(db, &def_map, from, item, MAX_PATH_LEN, prefixed, &mut visited_modules)
113 db: &dyn DefDatabase,
118 mut prefixed: Option<PrefixKind>,
119 visited_modules: &mut FxHashSet<ModuleId>,
120 ) -> Option<ModPath> {
127 // - if the item is already in scope, return the name under which it is
128 let scope_name = def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
129 def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone())
131 if prefixed.is_none() {
132 if let Some(scope_name) = scope_name {
133 return Some(ModPath::from_segments(PathKind::Plain, Some(scope_name)));
137 // - if the item is a builtin, it's in scope
138 if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
139 return Some(ModPath::from_segments(PathKind::Plain, Some(builtin.as_name())));
142 // - if the item is the crate root, return `crate`
143 let crate_root = def_map.crate_root(db);
144 if item == ItemInNs::Types(ModuleDefId::ModuleId(crate_root)) {
145 return Some(ModPath::from_segments(PathKind::Crate, None));
148 if prefixed.filter(PrefixKind::is_absolute).is_none() {
149 if let modpath @ Some(_) = check_self_super(&def_map, item, from) {
154 // - if the item is the crate root of a dependency crate, return the name from the extern prelude
155 let root_def_map = crate_root.def_map(db);
156 if let ItemInNs::Types(ModuleDefId::ModuleId(item)) = item {
157 for (name, &def_id) in root_def_map.extern_prelude() {
159 let name = scope_name.unwrap_or_else(|| name.clone());
161 let name_already_occupied_in_type_ns = def_map
162 .with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
166 .filter(|&(id, _)| id != ModuleDefId::ModuleId(def_id))
169 let kind = if name_already_occupied_in_type_ns {
170 cov_mark::hit!(ambiguous_crate_start);
175 return Some(ModPath::from_segments(kind, Some(name)));
180 // - if the item is in the prelude, return the name from there
181 if let Some(prelude_module) = root_def_map.prelude() {
182 // Preludes in block DefMaps are ignored, only the crate DefMap is searched
183 let prelude_def_map = prelude_module.def_map(db);
184 let prelude_scope = &prelude_def_map[prelude_module.local_id].scope;
185 if let Some((name, vis)) = prelude_scope.name_of(item) {
186 if vis.is_visible_from(db, from) {
187 return Some(ModPath::from_segments(PathKind::Plain, Some(name.clone())));
193 // - if the item is an enum variant, refer to it via the enum
194 if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
195 if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) {
196 let data = db.enum_data(variant.parent);
197 path.push_segment(data.variants[variant.local_id].name.clone());
200 // If this doesn't work, it seems we have no way of referring to the
201 // enum; that's very weird, but there might still be a reexport of the
205 // - otherwise, look for modules containing (reexporting) it and import it from one of those
206 let prefer_no_std = db.attrs(crate_root.into()).by_key("no_std").exists();
207 let mut best_path = None;
208 let mut best_path_len = max_len;
210 if item.krate(db) == Some(from.krate) {
211 // Item was defined in the same crate that wants to import it. It cannot be found in any
212 // dependency in this case.
213 // FIXME: this should have a fast path that doesn't look through the prelude again?
214 for (module_id, name) in find_local_import_locations(db, item, from) {
215 if !visited_modules.insert(module_id) {
216 cov_mark::hit!(recursive_imports);
219 if let Some(mut path) = find_path_inner_(
223 ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
228 path.push_segment(name);
230 let new_path = match best_path {
231 Some(best_path) => select_best_path(best_path, path, prefer_no_std),
234 best_path_len = new_path.len();
235 best_path = Some(new_path);
239 // Item was defined in some upstream crate. This means that it must be exported from one,
240 // too (unless we can't name it at all). It could *also* be (re)exported by the same crate
241 // that wants to import it here, but we always prefer to use the external path here.
243 let crate_graph = db.crate_graph();
244 let extern_paths = crate_graph[from.krate].dependencies.iter().filter_map(|dep| {
245 let import_map = db.import_map(dep.crate_id);
246 import_map.import_info_for(item).and_then(|info| {
247 // Determine best path for containing module and append last segment from `info`.
248 // FIXME: we should guide this to look up the path locally, or from the same crate again?
249 let mut path = find_path_inner_(
253 ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
258 cov_mark::hit!(partially_imported);
259 path.push_segment(info.path.segments.last()?.clone());
264 for path in extern_paths {
265 let new_path = match best_path {
266 Some(best_path) => select_best_path(best_path, path, prefer_no_std),
269 best_path = Some(new_path);
273 // If the item is declared inside a block expression, don't use a prefix, as we don't handle
274 // that correctly (FIXME).
275 if let Some(item_module) = item.as_module_def_id().and_then(|did| did.module(db)) {
276 if item_module.def_map(db).block_id().is_some() && prefixed.is_some() {
277 cov_mark::hit!(prefixed_in_block_expression);
278 prefixed = Some(PrefixKind::Plain);
282 match prefixed.map(PrefixKind::prefix) {
283 Some(prefix) => best_path.or_else(|| {
284 scope_name.map(|scope_name| ModPath::from_segments(prefix, Some(scope_name)))
290 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
291 if old_path.starts_with_std() && new_path.can_start_with_std() {
293 cov_mark::hit!(prefer_no_std_paths);
296 cov_mark::hit!(prefer_std_paths);
299 } else if new_path.starts_with_std() && old_path.can_start_with_std() {
301 cov_mark::hit!(prefer_no_std_paths);
304 cov_mark::hit!(prefer_std_paths);
307 } else if new_path.len() < old_path.len() {
314 /// Finds locations in `from.krate` from which `item` can be imported by `from`.
315 fn find_local_import_locations(
316 db: &dyn DefDatabase,
319 ) -> Vec<(ModuleId, Name)> {
320 let _p = profile::span("find_local_import_locations");
322 // `from` can import anything below `from` with visibility of at least `from`, and anything
323 // above `from` with any visibility. That means we do not need to descend into private siblings
324 // of `from` (and similar).
326 let def_map = from.def_map(db);
328 // Compute the initial worklist. We start with all direct child modules of `from` as well as all
329 // of its (recursive) parent modules.
330 let data = &def_map[from.local_id];
332 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>();
333 // FIXME: do we need to traverse out of block expressions here?
334 for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) {
335 worklist.push(ancestor);
338 let def_map = def_map.crate_root(db).def_map(db);
340 let mut seen: FxHashSet<_> = FxHashSet::default();
342 let mut locations = Vec::new();
343 while let Some(module) = worklist.pop() {
344 if !seen.insert(module) {
345 continue; // already processed this module
349 let data = if module.krate == from.krate {
350 if module.block.is_some() {
351 // Re-query the block's DefMap
352 ext_def_map = module.def_map(db);
353 &ext_def_map[module.local_id]
355 // Reuse the root DefMap
356 &def_map[module.local_id]
359 // The crate might reexport a module defined in another crate.
360 ext_def_map = module.def_map(db);
361 &ext_def_map[module.local_id]
364 if let Some((name, vis)) = data.scope.name_of(item) {
365 if vis.is_visible_from(db, from) {
366 let is_private = match vis {
367 Visibility::Module(private_to) => private_to.local_id == module.local_id,
368 Visibility::Public => false,
370 let is_original_def = match item.as_module_def_id() {
371 Some(module_def_id) => data.scope.declarations().any(|it| it == module_def_id),
375 // Ignore private imports. these could be used if we are
376 // in a submodule of this module, but that's usually not
377 // what the user wants; and if this module can import
378 // the item and we're a submodule of it, so can we.
379 // Also this keeps the cached data smaller.
380 if !is_private || is_original_def {
381 locations.push((module, name.clone()));
386 // Descend into all modules visible from `from`.
387 for (ty, vis) in data.scope.types() {
388 if let ModuleDefId::ModuleId(module) = ty {
389 if vis.is_visible_from(db, from) {
390 worklist.push(module);
401 use base_db::fixture::WithFixture;
402 use hir_expand::hygiene::Hygiene;
403 use syntax::ast::AstNode;
405 use crate::test_db::TestDB;
409 /// `code` needs to contain a cursor marker; checks that `find_path` for the
410 /// item the `path` refers to returns that same path when called from the
411 /// module the cursor is in.
412 fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKind>) {
413 let (db, pos) = TestDB::with_position(ra_fixture);
414 let module = db.module_at_position(pos);
415 let parsed_path_file = syntax::SourceFile::parse(&format!("use {};", path));
417 parsed_path_file.syntax_node().descendants().find_map(syntax::ast::Path::cast).unwrap();
418 let mod_path = ModPath::from_src(&db, ast_path, &Hygiene::new_unhygienic()).unwrap();
420 let def_map = module.def_map(&db);
421 let resolved = def_map
426 crate::item_scope::BuiltinShadowMode::Module,
432 let found_path = find_path_inner(&db, ItemInNs::Types(resolved), module, prefix_kind);
433 assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind);
443 check_found_path_(ra_fixture, unprefixed, None);
444 check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain));
445 check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate));
446 check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf));
562 fn different_crate() {
565 //- /main.rs crate:main deps:std
567 //- /std.rs crate:std
578 fn different_crate_renamed() {
581 //- /main.rs crate:main deps:std
582 extern crate std as std_renamed;
584 //- /std.rs crate:std
595 fn partially_imported() {
596 cov_mark::check!(partially_imported);
597 // Tests that short paths are used even for external items, when parts of the path are
601 //- /main.rs crate:main deps:syntax
606 //- /lib.rs crate:syntax
608 pub enum ModuleItem {
614 "syntax::ast::ModuleItem",
615 "syntax::ast::ModuleItem",
616 "syntax::ast::ModuleItem",
621 //- /main.rs crate:main deps:syntax
624 //- /lib.rs crate:syntax
626 pub enum ModuleItem {
631 "syntax::ast::ModuleItem",
632 "syntax::ast::ModuleItem",
633 "syntax::ast::ModuleItem",
634 "syntax::ast::ModuleItem",
639 fn same_crate_reexport() {
643 mod foo { pub(super) struct S; }
644 pub(crate) use foo::*;
656 fn same_crate_reexport_rename() {
660 mod foo { pub(super) struct S; }
661 pub(crate) use foo::S as U;
673 fn different_crate_reexport() {
676 //- /main.rs crate:main deps:std
678 //- /std.rs crate:std deps:core
680 //- /core.rs crate:core
694 //- /main.rs crate:main deps:std
696 //- /std.rs crate:std
711 fn enum_variant_from_prelude() {
713 //- /main.rs crate:main deps:std
715 //- /std.rs crate:std
718 pub enum Option<T> { Some(T), None }
723 check_found_path(code, "None", "None", "None", "None");
724 check_found_path(code, "Some", "Some", "Some", "Some");
737 pub mod bar { pub struct S; }
739 pub use crate::foo::bar::S;
749 fn discount_private_imports() {
754 pub mod bar { pub struct S; }
759 // crate::S would be shorter, but using private imports seems wrong
791 fn prefer_std_paths_over_alloc() {
792 cov_mark::check!(prefer_std_paths);
795 //- /main.rs crate:main deps:alloc,std
798 //- /std.rs crate:std deps:alloc
800 pub use alloc::sync::Arc;
803 //- /zzz.rs crate:alloc
816 fn prefer_core_paths_over_std() {
817 cov_mark::check!(prefer_no_std_paths);
820 //- /main.rs crate:main deps:core,std
825 //- /std.rs crate:std deps:core
828 pub use core::fmt::Error;
831 //- /zzz.rs crate:core
845 fn prefer_alloc_paths_over_std() {
848 //- /main.rs crate:main deps:alloc,std
853 //- /std.rs crate:std deps:alloc
856 pub use alloc::sync::Arc;
859 //- /zzz.rs crate:alloc
873 fn prefer_shorter_paths_if_not_alloc() {
876 //- /main.rs crate:main deps:megaalloc,std
879 //- /std.rs crate:std deps:megaalloc
881 pub use megaalloc::sync::Arc;
884 //- /zzz.rs crate:megaalloc
895 fn builtins_are_in_scope() {
903 check_found_path(code, "u8", "u8", "u8", "u8");
904 check_found_path(code, "u16", "u16", "u16", "u16");
924 fn inner_items_from_outer_scope() {
942 fn inner_items_from_inner_module() {
943 cov_mark::check!(prefixed_in_block_expression);
963 fn outer_items_with_inner_items_present() {
967 pub struct CompleteMe;
975 // FIXME: these could use fewer/better prefixes
976 "module::CompleteMe",
977 "crate::module::CompleteMe",
978 "crate::module::CompleteMe",
979 "crate::module::CompleteMe",
984 fn from_inside_module() {
985 // This worked correctly, but the test suite logic was broken.
986 cov_mark::check!(submodule_in_testdb);
1007 fn from_inside_module_with_inner_items() {
1029 fn recursive_pub_mod_reexport() {
1030 cov_mark::check!(recursive_imports);
1034 let _ = 22_i32.as_name$0();
1039 fn as_name(&self) -> String;
1041 impl AsName for i32 {
1042 fn as_name(&self) -> String {
1043 format!("Name: {}", self)
1046 pub use crate::name;
1051 "crate::name::AsName",
1052 "self::name::AsName",
1060 //- /main.rs crate:main deps:dep
1062 //- /dep.rs crate:dep
1072 //- /main.rs crate:main deps:dep
1077 //- /dep.rs crate:dep
1087 fn prelude_with_inner_items() {
1090 //- /main.rs crate:main deps:std
1095 //- /std.rs crate:std
1098 pub enum Option { None }