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 find_path_inner(db, item, from, MAX_PATH_LEN, 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, MAX_PATH_LEN, Some(prefix_kind))
34 const MAX_PATH_LEN: usize = 15;
37 fn starts_with_std(&self) -> bool {
38 self.segments().first() == Some(&known::std)
41 // When std library is present, paths starting with `std::`
42 // should be preferred over paths starting with `core::` and `alloc::`
43 fn can_start_with_std(&self) -> bool {
44 let first_segment = self.segments().first();
45 first_segment == Some(&known::alloc) || first_segment == Some(&known::core)
49 fn check_self_super(def_map: &DefMap, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
50 if item == ItemInNs::Types(from.into()) {
51 // - if the item is the module we're in, use `self`
52 Some(ModPath::from_segments(PathKind::Super(0), Vec::new()))
53 } else if let Some(parent_id) = def_map[from.local_id].parent {
54 // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
55 let parent_id = def_map.module_id(parent_id);
56 if item == ItemInNs::Types(ModuleDefId::ModuleId(parent_id)) {
57 Some(ModPath::from_segments(PathKind::Super(1), Vec::new()))
66 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
68 /// Causes paths to always start with either `self`, `super`, `crate` or a crate-name.
69 /// This is the same as plain, just that paths will start with `self` iprepended f the path
70 /// starts with an identifier that is not a crate.
72 /// Causes paths to ignore imports in the local module.
74 /// Causes paths to start with `crate` where applicable, effectively forcing paths to be absolute.
80 fn prefix(self) -> PathKind {
82 PrefixKind::BySelf => PathKind::Super(0),
83 PrefixKind::Plain => PathKind::Plain,
84 PrefixKind::ByCrate => PathKind::Crate,
89 fn is_absolute(&self) -> bool {
90 self == &PrefixKind::ByCrate
99 mut prefixed: Option<PrefixKind>,
100 ) -> Option<ModPath> {
107 // - if the item is already in scope, return the name under which it is
108 let def_map = from.def_map(db);
109 let scope_name = def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
110 def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone())
112 if prefixed.is_none() && scope_name.is_some() {
114 .map(|scope_name| ModPath::from_segments(PathKind::Plain, vec![scope_name]));
117 // - if the item is the crate root, return `crate`
118 let root = def_map.crate_root(db);
119 if item == ItemInNs::Types(ModuleDefId::ModuleId(root)) && def_map.block_id().is_none() {
120 // FIXME: the `block_id()` check should be unnecessary, but affects the result
121 return Some(ModPath::from_segments(PathKind::Crate, Vec::new()));
124 if prefixed.filter(PrefixKind::is_absolute).is_none() {
125 if let modpath @ Some(_) = check_self_super(&def_map, item, from) {
130 // - if the item is the crate root of a dependency crate, return the name from the extern prelude
131 for (name, def_id) in def_map.extern_prelude() {
132 if item == ItemInNs::Types(*def_id) {
133 let name = scope_name.unwrap_or_else(|| name.clone());
134 return Some(ModPath::from_segments(PathKind::Plain, vec![name]));
138 // - if the item is in the prelude, return the name from there
139 if let Some(prelude_module) = def_map.prelude() {
140 let prelude_def_map = prelude_module.def_map(db);
141 let prelude_scope: &crate::item_scope::ItemScope =
142 &prelude_def_map[prelude_module.local_id].scope;
143 if let Some((name, vis)) = prelude_scope.name_of(item) {
144 if vis.is_visible_from(db, from) {
145 return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
150 // - if the item is a builtin, it's in scope
151 if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
152 return Some(ModPath::from_segments(PathKind::Plain, vec![builtin.as_name()]));
156 // - if the item is an enum variant, refer to it via the enum
157 if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
158 if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) {
159 let data = db.enum_data(variant.parent);
160 path.push_segment(data.variants[variant.local_id].name.clone());
163 // If this doesn't work, it seems we have no way of referring to the
164 // enum; that's very weird, but there might still be a reexport of the
168 // - otherwise, look for modules containing (reexporting) it and import it from one of those
170 let crate_root = def_map.crate_root(db);
171 let crate_attrs = db.attrs(crate_root.into());
172 let prefer_no_std = crate_attrs.by_key("no_std").exists();
173 let mut best_path = None;
174 let mut best_path_len = max_len;
176 if item.krate(db) == Some(from.krate) {
177 // Item was defined in the same crate that wants to import it. It cannot be found in any
178 // dependency in this case.
180 let local_imports = find_local_import_locations(db, item, from);
181 for (module_id, name) in local_imports {
182 if let Some(mut path) = find_path_inner(
184 ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
189 path.push_segment(name);
191 let new_path = if let Some(best_path) = best_path {
192 select_best_path(best_path, path, prefer_no_std)
196 best_path_len = new_path.len();
197 best_path = Some(new_path);
201 // Item was defined in some upstream crate. This means that it must be exported from one,
202 // too (unless we can't name it at all). It could *also* be (re)exported by the same crate
203 // that wants to import it here, but we always prefer to use the external path here.
205 let crate_graph = db.crate_graph();
206 let extern_paths = crate_graph[from.krate].dependencies.iter().filter_map(|dep| {
207 let import_map = db.import_map(dep.crate_id);
208 import_map.import_info_for(item).and_then(|info| {
209 // Determine best path for containing module and append last segment from `info`.
210 let mut path = find_path_inner(
212 ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
217 cov_mark::hit!(partially_imported);
218 path.push_segment(info.path.segments.last().unwrap().clone());
223 for path in extern_paths {
224 let new_path = if let Some(best_path) = best_path {
225 select_best_path(best_path, path, prefer_no_std)
229 best_path = Some(new_path);
233 // If the item is declared inside a block expression, don't use a prefix, as we don't handle
234 // that correctly (FIXME).
235 if let Some(item_module) = item.as_module_def_id().and_then(|did| did.module(db)) {
236 if item_module.def_map(db).block_id().is_some() && prefixed.is_some() {
237 cov_mark::hit!(prefixed_in_block_expression);
238 prefixed = Some(PrefixKind::Plain);
242 if let Some(prefix) = prefixed.map(PrefixKind::prefix) {
243 best_path.or_else(|| {
244 scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name]))
251 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
252 if old_path.starts_with_std() && new_path.can_start_with_std() {
254 cov_mark::hit!(prefer_no_std_paths);
257 cov_mark::hit!(prefer_std_paths);
260 } else if new_path.starts_with_std() && old_path.can_start_with_std() {
262 cov_mark::hit!(prefer_no_std_paths);
265 cov_mark::hit!(prefer_std_paths);
268 } else if new_path.len() < old_path.len() {
275 /// Finds locations in `from.krate` from which `item` can be imported by `from`.
276 fn find_local_import_locations(
277 db: &dyn DefDatabase,
280 ) -> Vec<(ModuleId, Name)> {
281 let _p = profile::span("find_local_import_locations");
283 // `from` can import anything below `from` with visibility of at least `from`, and anything
284 // above `from` with any visibility. That means we do not need to descend into private siblings
285 // of `from` (and similar).
287 let def_map = from.def_map(db);
289 // Compute the initial worklist. We start with all direct child modules of `from` as well as all
290 // of its (recursive) parent modules.
291 let data = &def_map[from.local_id];
293 data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>();
294 for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) {
295 worklist.push(ancestor);
298 let def_map = def_map.crate_root(db).def_map(db);
300 let mut seen: FxHashSet<_> = FxHashSet::default();
302 let mut locations = Vec::new();
303 while let Some(module) = worklist.pop() {
304 if !seen.insert(module) {
305 continue; // already processed this module
309 let data = if module.krate == from.krate {
310 if module.block.is_some() {
311 // Re-query the block's DefMap
312 ext_def_map = module.def_map(db);
313 &ext_def_map[module.local_id]
315 // Reuse the root DefMap
316 &def_map[module.local_id]
319 // The crate might reexport a module defined in another crate.
320 ext_def_map = module.def_map(db);
321 &ext_def_map[module.local_id]
324 if let Some((name, vis)) = data.scope.name_of(item) {
325 if vis.is_visible_from(db, from) {
326 let is_private = if let Visibility::Module(private_to) = vis {
327 private_to.local_id == module.local_id
331 let is_original_def = if let Some(module_def_id) = item.as_module_def_id() {
332 data.scope.declarations().any(|it| it == module_def_id)
337 // Ignore private imports. these could be used if we are
338 // in a submodule of this module, but that's usually not
339 // what the user wants; and if this module can import
340 // the item and we're a submodule of it, so can we.
341 // Also this keeps the cached data smaller.
342 if !is_private || is_original_def {
343 locations.push((module, name.clone()));
348 // Descend into all modules visible from `from`.
349 for (_, per_ns) in data.scope.entries() {
350 if let Some((ModuleDefId::ModuleId(module), vis)) = per_ns.take_types_vis() {
351 if vis.is_visible_from(db, from) {
352 worklist.push(module);
363 use base_db::fixture::WithFixture;
364 use hir_expand::hygiene::Hygiene;
365 use syntax::ast::AstNode;
367 use crate::test_db::TestDB;
371 /// `code` needs to contain a cursor marker; checks that `find_path` for the
372 /// item the `path` refers to returns that same path when called from the
373 /// module the cursor is in.
374 fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKind>) {
375 let (db, pos) = TestDB::with_position(ra_fixture);
376 let module = db.module_at_position(pos);
377 let parsed_path_file = syntax::SourceFile::parse(&format!("use {};", path));
379 parsed_path_file.syntax_node().descendants().find_map(syntax::ast::Path::cast).unwrap();
380 let mod_path = ModPath::from_src(ast_path, &Hygiene::new_unhygienic()).unwrap();
382 let def_map = module.def_map(&db);
383 let resolved = def_map
388 crate::item_scope::BuiltinShadowMode::Module,
395 find_path_inner(&db, ItemInNs::Types(resolved), module, MAX_PATH_LEN, prefix_kind);
396 assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind);
406 check_found_path_(ra_fixture, unprefixed, None);
407 check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain));
408 check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate));
409 check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf));
419 check_found_path(code, "S", "S", "crate::S", "self::S");
429 check_found_path(code, "E::A", "E::A", "E::A", "E::A");
441 check_found_path(code, "foo::S", "foo::S", "crate::foo::S", "self::foo::S");
455 check_found_path(code, "super::S", "super::S", "crate::foo::S", "super::S");
466 check_found_path(code, "self", "self", "crate::foo", "self");
477 check_found_path(code, "crate", "crate", "crate", "crate");
489 check_found_path(code, "crate::S", "crate::S", "crate::S", "crate::S");
493 fn different_crate() {
495 //- /main.rs crate:main deps:std
497 //- /std.rs crate:std
500 check_found_path(code, "std::S", "std::S", "std::S", "std::S");
504 fn different_crate_renamed() {
506 //- /main.rs crate:main deps:std
507 extern crate std as std_renamed;
509 //- /std.rs crate:std
522 fn partially_imported() {
523 cov_mark::check!(partially_imported);
524 // Tests that short paths are used even for external items, when parts of the path are
527 //- /main.rs crate:main deps:syntax
532 //- /lib.rs crate:syntax
534 pub enum ModuleItem {
542 "syntax::ast::ModuleItem",
543 "syntax::ast::ModuleItem",
544 "syntax::ast::ModuleItem",
548 //- /main.rs crate:main deps:syntax
552 //- /lib.rs crate:syntax
554 pub enum ModuleItem {
561 "syntax::ast::ModuleItem",
562 "syntax::ast::ModuleItem",
563 "syntax::ast::ModuleItem",
564 "syntax::ast::ModuleItem",
569 fn same_crate_reexport() {
573 mod foo { pub(super) struct S; }
574 pub(crate) use foo::*;
578 check_found_path(code, "bar::S", "bar::S", "crate::bar::S", "self::bar::S");
582 fn same_crate_reexport_rename() {
586 mod foo { pub(super) struct S; }
587 pub(crate) use foo::S as U;
591 check_found_path(code, "bar::U", "bar::U", "crate::bar::U", "self::bar::U");
595 fn different_crate_reexport() {
597 //- /main.rs crate:main deps:std
599 //- /std.rs crate:std deps:core
601 //- /core.rs crate:core
604 check_found_path(code, "std::S", "std::S", "std::S", "std::S");
610 //- /main.rs crate:main deps:std
612 //- /std.rs crate:std
613 pub mod prelude { pub struct S; }
617 check_found_path(code, "S", "S", "S", "S");
621 fn enum_variant_from_prelude() {
623 //- /main.rs crate:main deps:std
625 //- /std.rs crate:std
627 pub enum Option<T> { Some(T), None }
633 check_found_path(code, "None", "None", "None", "None");
634 check_found_path(code, "Some", "Some", "Some", "Some");
646 pub mod bar { pub struct S; }
648 pub use crate::foo::bar::S;
650 check_found_path(code, "baz::S", "baz::S", "crate::baz::S", "self::baz::S");
654 fn discount_private_imports() {
658 pub mod bar { pub struct S; }
663 // crate::S would be shorter, but using private imports seems wrong
664 check_found_path(code, "crate::bar::S", "crate::bar::S", "crate::bar::S", "crate::bar::S");
682 check_found_path(code, "crate::foo::S", "crate::foo::S", "crate::foo::S", "crate::foo::S");
686 fn prefer_std_paths_over_alloc() {
687 cov_mark::check!(prefer_std_paths);
689 //- /main.rs crate:main deps:alloc,std
692 //- /std.rs crate:std deps:alloc
694 pub use alloc::sync::Arc;
697 //- /zzz.rs crate:alloc
712 fn prefer_core_paths_over_std() {
713 cov_mark::check!(prefer_no_std_paths);
715 //- /main.rs crate:main deps:core,std
720 //- /std.rs crate:std deps:core
723 pub use core::fmt::Error;
726 //- /zzz.rs crate:core
742 fn prefer_alloc_paths_over_std() {
744 //- /main.rs crate:main deps:alloc,std
749 //- /std.rs crate:std deps:alloc
752 pub use alloc::sync::Arc;
755 //- /zzz.rs crate:alloc
771 fn prefer_shorter_paths_if_not_alloc() {
773 //- /main.rs crate:main deps:megaalloc,std
776 //- /std.rs crate:std deps:megaalloc
778 pub use megaalloc::sync::Arc;
781 //- /zzz.rs crate:megaalloc
794 fn builtins_are_in_scope() {
803 check_found_path(code, "u8", "u8", "u8", "u8");
804 check_found_path(code, "u16", "u16", "u16", "u16");
824 fn inner_items_from_outer_scope() {
842 fn inner_items_from_inner_module() {
843 cov_mark::check!(prefixed_in_block_expression);
863 fn outer_items_with_inner_items_present() {
867 pub struct CompleteMe;
875 "module::CompleteMe",
876 "module::CompleteMe",
877 "crate::module::CompleteMe",
878 "self::module::CompleteMe",