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 fn can_start_with_std(&self) -> bool;
43 impl ModPathExt for ModPath {
44 fn starts_with_std(&self) -> bool {
45 self.segments().first() == Some(&known::std)
48 // When std library is present, paths starting with `std::`
49 // should be preferred over paths starting with `core::` and `alloc::`
50 fn can_start_with_std(&self) -> bool {
51 let first_segment = self.segments().first();
52 first_segment == Some(&known::alloc) || first_segment == Some(&known::core)
56 fn check_self_super(def_map: &DefMap, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
57 if item == ItemInNs::Types(from.into()) {
58 // - if the item is the module we're in, use `self`
59 Some(ModPath::from_segments(PathKind::Super(0), Vec::new()))
60 } else if let Some(parent_id) = def_map[from.local_id].parent {
61 // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
62 let parent_id = def_map.module_id(parent_id);
63 if item == ItemInNs::Types(ModuleDefId::ModuleId(parent_id)) {
64 Some(ModPath::from_segments(PathKind::Super(1), Vec::new()))
73 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
75 /// Causes paths to always start with either `self`, `super`, `crate` or a crate-name.
76 /// This is the same as plain, just that paths will start with `self` iprepended f the path
77 /// starts with an identifier that is not a crate.
79 /// Causes paths to ignore imports in the local module.
81 /// Causes paths to start with `crate` where applicable, effectively forcing paths to be absolute.
87 fn prefix(self) -> PathKind {
89 PrefixKind::BySelf => PathKind::Super(0),
90 PrefixKind::Plain => PathKind::Plain,
91 PrefixKind::ByCrate => PathKind::Crate,
96 fn is_absolute(&self) -> bool {
97 self == &PrefixKind::ByCrate
102 db: &dyn DefDatabase,
106 mut prefixed: Option<PrefixKind>,
107 visited_modules: &mut FxHashSet<ModuleId>,
108 ) -> Option<ModPath> {
115 // - if the item is already in scope, return the name under which it is
116 let def_map = from.def_map(db);
117 let scope_name = def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
118 def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone())
120 if prefixed.is_none() && scope_name.is_some() {
122 .map(|scope_name| ModPath::from_segments(PathKind::Plain, vec![scope_name]));
125 // - if the item is the crate root, return `crate`
126 let root = def_map.crate_root(db);
127 if item == ItemInNs::Types(ModuleDefId::ModuleId(root)) {
128 return Some(ModPath::from_segments(PathKind::Crate, Vec::new()));
131 if prefixed.filter(PrefixKind::is_absolute).is_none() {
132 if let modpath @ Some(_) = check_self_super(&def_map, item, from) {
137 // - if the item is the crate root of a dependency crate, return the name from the extern prelude
138 let root_def_map = root.def_map(db);
139 for (name, def_id) in root_def_map.extern_prelude() {
140 if item == ItemInNs::Types(*def_id) {
141 let name = scope_name.unwrap_or_else(|| name.clone());
143 let name_already_occupied_in_type_ns = def_map
144 .with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
145 def_map[local_id].scope.get(&name).take_types().filter(|&id| id != *def_id)
148 return Some(ModPath::from_segments(
149 if name_already_occupied_in_type_ns {
150 cov_mark::hit!(ambiguous_crate_start);
160 // - if the item is in the prelude, return the name from there
161 if let Some(prelude_module) = root_def_map.prelude() {
162 // Preludes in block DefMaps are ignored, only the crate DefMap is searched
163 let prelude_def_map = prelude_module.def_map(db);
164 let prelude_scope: &crate::item_scope::ItemScope =
165 &prelude_def_map[prelude_module.local_id].scope;
166 if let Some((name, vis)) = prelude_scope.name_of(item) {
167 if vis.is_visible_from(db, from) {
168 return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
173 // - if the item is a builtin, it's in scope
174 if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
175 return Some(ModPath::from_segments(PathKind::Plain, vec![builtin.as_name()]));
179 // - if the item is an enum variant, refer to it via the enum
180 if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
181 if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) {
182 let data = db.enum_data(variant.parent);
183 path.push_segment(data.variants[variant.local_id].name.clone());
186 // If this doesn't work, it seems we have no way of referring to the
187 // enum; that's very weird, but there might still be a reexport of the
191 // - otherwise, look for modules containing (reexporting) it and import it from one of those
193 let crate_root = def_map.crate_root(db);
194 let crate_attrs = db.attrs(crate_root.into());
195 let prefer_no_std = crate_attrs.by_key("no_std").exists();
196 let mut best_path = None;
197 let mut best_path_len = max_len;
199 if item.krate(db) == Some(from.krate) {
200 // Item was defined in the same crate that wants to import it. It cannot be found in any
201 // dependency in this case.
202 for (module_id, name) in find_local_import_locations(db, item, from) {
203 if !visited_modules.insert(module_id) {
204 cov_mark::hit!(recursive_imports);
207 if let Some(mut path) = find_path_inner(
209 ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
215 path.push_segment(name);
217 let new_path = match best_path {
218 Some(best_path) => select_best_path(best_path, path, prefer_no_std),
221 best_path_len = new_path.len();
222 best_path = Some(new_path);
226 // Item was defined in some upstream crate. This means that it must be exported from one,
227 // too (unless we can't name it at all). It could *also* be (re)exported by the same crate
228 // that wants to import it here, but we always prefer to use the external path here.
230 let crate_graph = db.crate_graph();
231 let extern_paths = crate_graph[from.krate].dependencies.iter().filter_map(|dep| {
232 let import_map = db.import_map(dep.crate_id);
233 import_map.import_info_for(item).and_then(|info| {
234 // Determine best path for containing module and append last segment from `info`.
235 let mut path = find_path_inner(
237 ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
243 cov_mark::hit!(partially_imported);
244 path.push_segment(info.path.segments.last().unwrap().clone());
249 for path in extern_paths {
250 let new_path = match best_path {
251 Some(best_path) => select_best_path(best_path, path, prefer_no_std),
254 best_path = Some(new_path);
258 // If the item is declared inside a block expression, don't use a prefix, as we don't handle
259 // that correctly (FIXME).
260 if let Some(item_module) = item.as_module_def_id().and_then(|did| did.module(db)) {
261 if item_module.def_map(db).block_id().is_some() && prefixed.is_some() {
262 cov_mark::hit!(prefixed_in_block_expression);
263 prefixed = Some(PrefixKind::Plain);
267 match prefixed.map(PrefixKind::prefix) {
268 Some(prefix) => best_path.or_else(|| {
269 scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name]))
275 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
276 if old_path.starts_with_std() && new_path.can_start_with_std() {
278 cov_mark::hit!(prefer_no_std_paths);
281 cov_mark::hit!(prefer_std_paths);
284 } else if new_path.starts_with_std() && old_path.can_start_with_std() {
286 cov_mark::hit!(prefer_no_std_paths);
289 cov_mark::hit!(prefer_std_paths);
292 } else if new_path.len() < old_path.len() {
299 /// Finds locations in `from.krate` from which `item` can be imported by `from`.
300 fn find_local_import_locations(
301 db: &dyn DefDatabase,
304 ) -> Vec<(ModuleId, Name)> {
305 let _p = profile::span("find_local_import_locations");
307 // `from` can import anything below `from` with visibility of at least `from`, and anything
308 // above `from` with any visibility. That means we do not need to descend into private siblings
309 // of `from` (and similar).
311 let def_map = from.def_map(db);
313 // Compute the initial worklist. We start with all direct child modules of `from` as well as all
314 // of its (recursive) parent modules.
315 let data = &def_map[from.local_id];
317 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>();
318 // FIXME: do we need to traverse out of block expressions here?
319 for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) {
320 worklist.push(ancestor);
323 let def_map = def_map.crate_root(db).def_map(db);
325 let mut seen: FxHashSet<_> = FxHashSet::default();
327 let mut locations = Vec::new();
328 while let Some(module) = worklist.pop() {
329 if !seen.insert(module) {
330 continue; // already processed this module
334 let data = if module.krate == from.krate {
335 if module.block.is_some() {
336 // Re-query the block's DefMap
337 ext_def_map = module.def_map(db);
338 &ext_def_map[module.local_id]
340 // Reuse the root DefMap
341 &def_map[module.local_id]
344 // The crate might reexport a module defined in another crate.
345 ext_def_map = module.def_map(db);
346 &ext_def_map[module.local_id]
349 if let Some((name, vis)) = data.scope.name_of(item) {
350 if vis.is_visible_from(db, from) {
351 let is_private = match vis {
352 Visibility::Module(private_to) => private_to.local_id == module.local_id,
353 Visibility::Public => false,
355 let is_original_def = match item.as_module_def_id() {
356 Some(module_def_id) => 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 }