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;
8 use crate::nameres::DefMap;
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)) && def_map.block_id().is_none() {
123 // FIXME: the `block_id()` check should be unnecessary, but affects the result
124 return Some(ModPath::from_segments(PathKind::Crate, Vec::new()));
127 if prefixed.filter(PrefixKind::is_absolute).is_none() {
128 if let modpath @ Some(_) = check_self_super(&def_map, item, from) {
133 // - if the item is the crate root of a dependency crate, return the name from the extern prelude
134 for (name, def_id) in def_map.extern_prelude() {
135 if item == ItemInNs::Types(*def_id) {
136 let name = scope_name.unwrap_or_else(|| name.clone());
137 return Some(ModPath::from_segments(PathKind::Plain, vec![name]));
141 // - if the item is in the prelude, return the name from there
142 if let Some(prelude_module) = def_map.prelude() {
143 let prelude_def_map = prelude_module.def_map(db);
144 let prelude_scope: &crate::item_scope::ItemScope =
145 &prelude_def_map[prelude_module.local_id].scope;
146 if let Some((name, vis)) = prelude_scope.name_of(item) {
147 if vis.is_visible_from(db, from) {
148 return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
153 // - if the item is a builtin, it's in scope
154 if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
155 return Some(ModPath::from_segments(PathKind::Plain, vec![builtin.as_name()]));
159 // - if the item is an enum variant, refer to it via the enum
160 if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
161 if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) {
162 let data = db.enum_data(variant.parent);
163 path.push_segment(data.variants[variant.local_id].name.clone());
166 // If this doesn't work, it seems we have no way of referring to the
167 // enum; that's very weird, but there might still be a reexport of the
171 // - otherwise, look for modules containing (reexporting) it and import it from one of those
173 let crate_root = def_map.crate_root(db);
174 let crate_attrs = db.attrs(crate_root.into());
175 let prefer_no_std = crate_attrs.by_key("no_std").exists();
176 let mut best_path = None;
177 let mut best_path_len = max_len;
179 if item.krate(db) == Some(from.krate) {
180 // Item was defined in the same crate that wants to import it. It cannot be found in any
181 // dependency in this case.
182 for (module_id, name) in find_local_import_locations(db, item, from) {
183 if !visited_modules.insert(module_id) {
184 cov_mark::hit!(recursive_imports);
187 if let Some(mut path) = find_path_inner(
189 ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
195 path.push_segment(name);
197 let new_path = if let Some(best_path) = best_path {
198 select_best_path(best_path, path, prefer_no_std)
202 best_path_len = new_path.len();
203 best_path = Some(new_path);
207 // Item was defined in some upstream crate. This means that it must be exported from one,
208 // too (unless we can't name it at all). It could *also* be (re)exported by the same crate
209 // that wants to import it here, but we always prefer to use the external path here.
211 let crate_graph = db.crate_graph();
212 let extern_paths = crate_graph[from.krate].dependencies.iter().filter_map(|dep| {
213 let import_map = db.import_map(dep.crate_id);
214 import_map.import_info_for(item).and_then(|info| {
215 // Determine best path for containing module and append last segment from `info`.
216 let mut path = find_path_inner(
218 ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
224 cov_mark::hit!(partially_imported);
225 path.push_segment(info.path.segments.last().unwrap().clone());
230 for path in extern_paths {
231 let new_path = if let Some(best_path) = best_path {
232 select_best_path(best_path, path, prefer_no_std)
236 best_path = Some(new_path);
240 // If the item is declared inside a block expression, don't use a prefix, as we don't handle
241 // that correctly (FIXME).
242 if let Some(item_module) = item.as_module_def_id().and_then(|did| did.module(db)) {
243 if item_module.def_map(db).block_id().is_some() && prefixed.is_some() {
244 cov_mark::hit!(prefixed_in_block_expression);
245 prefixed = Some(PrefixKind::Plain);
249 if let Some(prefix) = prefixed.map(PrefixKind::prefix) {
250 best_path.or_else(|| {
251 scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name]))
258 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
259 if old_path.starts_with_std() && new_path.can_start_with_std() {
261 cov_mark::hit!(prefer_no_std_paths);
264 cov_mark::hit!(prefer_std_paths);
267 } else if new_path.starts_with_std() && old_path.can_start_with_std() {
269 cov_mark::hit!(prefer_no_std_paths);
272 cov_mark::hit!(prefer_std_paths);
275 } else if new_path.len() < old_path.len() {
282 /// Finds locations in `from.krate` from which `item` can be imported by `from`.
283 fn find_local_import_locations(
284 db: &dyn DefDatabase,
287 ) -> Vec<(ModuleId, Name)> {
288 let _p = profile::span("find_local_import_locations");
290 // `from` can import anything below `from` with visibility of at least `from`, and anything
291 // above `from` with any visibility. That means we do not need to descend into private siblings
292 // of `from` (and similar).
294 let def_map = from.def_map(db);
296 // Compute the initial worklist. We start with all direct child modules of `from` as well as all
297 // of its (recursive) parent modules.
298 let data = &def_map[from.local_id];
300 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>();
301 for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) {
302 worklist.push(ancestor);
305 let def_map = def_map.crate_root(db).def_map(db);
307 let mut seen: FxHashSet<_> = FxHashSet::default();
309 let mut locations = Vec::new();
310 while let Some(module) = worklist.pop() {
311 if !seen.insert(module) {
312 continue; // already processed this module
316 let data = if module.krate == from.krate {
317 if module.block.is_some() {
318 // Re-query the block's DefMap
319 ext_def_map = module.def_map(db);
320 &ext_def_map[module.local_id]
322 // Reuse the root DefMap
323 &def_map[module.local_id]
326 // The crate might reexport a module defined in another crate.
327 ext_def_map = module.def_map(db);
328 &ext_def_map[module.local_id]
331 if let Some((name, vis)) = data.scope.name_of(item) {
332 if vis.is_visible_from(db, from) {
333 let is_private = if let Visibility::Module(private_to) = vis {
334 private_to.local_id == module.local_id
338 let is_original_def = if let Some(module_def_id) = item.as_module_def_id() {
339 data.scope.declarations().any(|it| it == module_def_id)
344 // Ignore private imports. these could be used if we are
345 // in a submodule of this module, but that's usually not
346 // what the user wants; and if this module can import
347 // the item and we're a submodule of it, so can we.
348 // Also this keeps the cached data smaller.
349 if !is_private || is_original_def {
350 locations.push((module, name.clone()));
355 // Descend into all modules visible from `from`.
356 for (_, per_ns) in data.scope.entries() {
357 if let Some((ModuleDefId::ModuleId(module), vis)) = per_ns.take_types_vis() {
358 if vis.is_visible_from(db, from) {
359 worklist.push(module);
370 use base_db::fixture::WithFixture;
371 use hir_expand::hygiene::Hygiene;
372 use syntax::ast::AstNode;
374 use crate::test_db::TestDB;
378 /// `code` needs to contain a cursor marker; checks that `find_path` for the
379 /// item the `path` refers to returns that same path when called from the
380 /// module the cursor is in.
381 fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKind>) {
382 let (db, pos) = TestDB::with_position(ra_fixture);
383 let module = db.module_at_position(pos);
384 let parsed_path_file = syntax::SourceFile::parse(&format!("use {};", path));
386 parsed_path_file.syntax_node().descendants().find_map(syntax::ast::Path::cast).unwrap();
387 let mod_path = ModPath::from_src(ast_path, &Hygiene::new_unhygienic()).unwrap();
389 let def_map = module.def_map(&db);
390 let resolved = def_map
395 crate::item_scope::BuiltinShadowMode::Module,
401 let mut visited_modules = FxHashSet::default();
402 let found_path = find_path_inner(
404 ItemInNs::Types(resolved),
408 &mut visited_modules,
410 assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind);
420 check_found_path_(ra_fixture, unprefixed, None);
421 check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain));
422 check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate));
423 check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf));
539 fn different_crate() {
542 //- /main.rs crate:main deps:std
544 //- /std.rs crate:std
555 fn different_crate_renamed() {
558 //- /main.rs crate:main deps:std
559 extern crate std as std_renamed;
561 //- /std.rs crate:std
572 fn partially_imported() {
573 cov_mark::check!(partially_imported);
574 // Tests that short paths are used even for external items, when parts of the path are
578 //- /main.rs crate:main deps:syntax
583 //- /lib.rs crate:syntax
585 pub enum ModuleItem {
591 "syntax::ast::ModuleItem",
592 "syntax::ast::ModuleItem",
593 "syntax::ast::ModuleItem",
598 //- /main.rs crate:main deps:syntax
601 //- /lib.rs crate:syntax
603 pub enum ModuleItem {
608 "syntax::ast::ModuleItem",
609 "syntax::ast::ModuleItem",
610 "syntax::ast::ModuleItem",
611 "syntax::ast::ModuleItem",
616 fn same_crate_reexport() {
620 mod foo { pub(super) struct S; }
621 pub(crate) use foo::*;
633 fn same_crate_reexport_rename() {
637 mod foo { pub(super) struct S; }
638 pub(crate) use foo::S as U;
650 fn different_crate_reexport() {
653 //- /main.rs crate:main deps:std
655 //- /std.rs crate:std deps:core
657 //- /core.rs crate:core
671 //- /main.rs crate:main deps:std
673 //- /std.rs crate:std
674 pub mod prelude { pub struct S; }
686 fn enum_variant_from_prelude() {
688 //- /main.rs crate:main deps:std
690 //- /std.rs crate:std
692 pub enum Option<T> { Some(T), None }
698 check_found_path(code, "None", "None", "None", "None");
699 check_found_path(code, "Some", "Some", "Some", "Some");
712 pub mod bar { pub struct S; }
714 pub use crate::foo::bar::S;
724 fn discount_private_imports() {
729 pub mod bar { pub struct S; }
734 // crate::S would be shorter, but using private imports seems wrong
766 fn prefer_std_paths_over_alloc() {
767 cov_mark::check!(prefer_std_paths);
770 //- /main.rs crate:main deps:alloc,std
773 //- /std.rs crate:std deps:alloc
775 pub use alloc::sync::Arc;
778 //- /zzz.rs crate:alloc
791 fn prefer_core_paths_over_std() {
792 cov_mark::check!(prefer_no_std_paths);
795 //- /main.rs crate:main deps:core,std
800 //- /std.rs crate:std deps:core
803 pub use core::fmt::Error;
806 //- /zzz.rs crate:core
820 fn prefer_alloc_paths_over_std() {
823 //- /main.rs crate:main deps:alloc,std
828 //- /std.rs crate:std deps:alloc
831 pub use alloc::sync::Arc;
834 //- /zzz.rs crate:alloc
848 fn prefer_shorter_paths_if_not_alloc() {
851 //- /main.rs crate:main deps:megaalloc,std
854 //- /std.rs crate:std deps:megaalloc
856 pub use megaalloc::sync::Arc;
859 //- /zzz.rs crate:megaalloc
870 fn builtins_are_in_scope() {
878 check_found_path(code, "u8", "u8", "u8", "u8");
879 check_found_path(code, "u16", "u16", "u16", "u16");
899 fn inner_items_from_outer_scope() {
917 fn inner_items_from_inner_module() {
918 cov_mark::check!(prefixed_in_block_expression);
938 fn outer_items_with_inner_items_present() {
942 pub struct CompleteMe;
950 "module::CompleteMe",
951 "module::CompleteMe",
952 "crate::module::CompleteMe",
953 "self::module::CompleteMe",
958 fn recursive_pub_mod_reexport() {
959 cov_mark::check!(recursive_imports);
963 let _ = 22_i32.as_name$0();
968 fn as_name(&self) -> String;
970 impl AsName for i32 {
971 fn as_name(&self) -> String {
972 format!("Name: {}", self)
980 "crate::name::AsName",
981 "self::name::AsName",