1 //! A map of all publicly exported items in a crate.
3 use std::{cmp::Ordering, fmt, hash::BuildHasherDefault, sync::Arc};
6 use fst::{self, Streamer};
7 use hir_expand::name::Name;
8 use indexmap::{map::Entry, IndexMap};
9 use itertools::Itertools;
10 use rustc_hash::{FxHashSet, FxHasher};
13 db::DefDatabase, item_scope::ItemInNs, visibility::Visibility, AssocItemId, ModuleDefId,
17 type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<FxHasher>>;
19 /// Item import details stored in the `ImportMap`.
20 #[derive(Debug, Clone, Eq, PartialEq)]
21 pub struct ImportInfo {
22 /// A path that can be used to import the item, relative to the crate's root.
24 /// The module containing this item.
25 pub container: ModuleId,
26 /// Whether the import is a trait associated item or not.
27 pub is_trait_assoc_item: bool,
30 #[derive(Debug, Clone, Eq, PartialEq)]
31 pub struct ImportPath {
32 pub segments: Vec<Name>,
35 impl fmt::Display for ImportPath {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 fmt::Display::fmt(&self.segments.iter().format("::"), f)
42 fn len(&self) -> usize {
47 /// A map from publicly exported items to the path needed to import/name them from a downstream
50 /// Reexports of items are taken into account, ie. if something is exported under multiple
51 /// names, the one with the shortest import path will be used.
53 /// Note that all paths are relative to the containing crate's root, so the crate name still needs
54 /// to be prepended to the `ModPath` before the path is valid.
56 pub struct ImportMap {
57 map: FxIndexMap<ItemInNs, ImportInfo>,
59 /// List of keys stored in `map`, sorted lexicographically by their `ModPath`. Indexed by the
60 /// values returned by running `fst`.
62 /// Since a path can refer to multiple items due to namespacing, we store all items with the
63 /// same path right after each other. This allows us to find all items after the FST gives us
64 /// the index of the first one.
65 importables: Vec<ItemInNs>,
66 fst: fst::Map<Vec<u8>>,
70 pub fn import_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<Self> {
71 let _p = profile::span("import_map_query");
72 let def_map = db.crate_def_map(krate);
73 let mut import_map = Self::default();
75 // We look only into modules that are public(ly reexported), starting with the crate root.
76 let empty = ImportPath { segments: vec![] };
77 let root = ModuleId { krate, local_id: def_map.root };
78 let mut worklist = vec![(root, empty)];
79 while let Some((module, mod_path)) = worklist.pop() {
81 let mod_data = if module.krate == krate {
82 &def_map[module.local_id]
84 // The crate might reexport a module defined in another crate.
85 ext_def_map = db.crate_def_map(module.krate);
86 &ext_def_map[module.local_id]
89 let visible_items = mod_data.scope.entries().filter_map(|(name, per_ns)| {
90 let per_ns = per_ns.filter_visibility(|vis| vis == Visibility::Public);
98 for (name, per_ns) in visible_items {
100 let mut path = mod_path.clone();
101 path.segments.push(name.clone());
105 for item in per_ns.iter_items() {
106 let path = mk_path();
107 let path_len = path.len();
109 ImportInfo { path, container: module, is_trait_assoc_item: false };
111 if let Some(ModuleDefId::TraitId(tr)) = item.as_module_def_id() {
112 import_map.collect_trait_assoc_items(
115 matches!(item, ItemInNs::Types(_)),
120 match import_map.map.entry(item) {
121 Entry::Vacant(entry) => {
122 entry.insert(import_info);
124 Entry::Occupied(mut entry) => {
125 // If the new path is shorter, prefer that one.
126 if path_len < entry.get().path.len() {
127 *entry.get_mut() = import_info;
134 // If we've just added a path to a module, descend into it. We might traverse
135 // modules multiple times, but only if the new path to it is shorter than the
136 // first (else we `continue` above).
137 if let Some(ModuleDefId::ModuleId(mod_id)) = item.as_module_def_id() {
138 worklist.push((mod_id, mk_path()));
144 let mut importables = import_map.map.iter().collect::<Vec<_>>();
146 importables.sort_by(cmp);
148 // Build the FST, taking care not to insert duplicate values.
150 let mut builder = fst::MapBuilder::memory();
151 let mut last_batch_start = 0;
153 for idx in 0..importables.len() {
154 if let Some(next_item) = importables.get(idx + 1) {
155 if cmp(&importables[last_batch_start], next_item) == Ordering::Equal {
160 let key = fst_path(&importables[last_batch_start].1.path);
161 builder.insert(key, last_batch_start as u64).unwrap();
163 last_batch_start = idx + 1;
166 import_map.fst = fst::Map::new(builder.into_inner().unwrap()).unwrap();
167 import_map.importables = importables.iter().map(|(item, _)| **item).collect();
172 /// Returns the `ModPath` needed to import/mention `item`, relative to this crate's root.
173 pub fn path_of(&self, item: ItemInNs) -> Option<&ImportPath> {
174 self.import_info_for(item).map(|it| &it.path)
177 pub fn import_info_for(&self, item: ItemInNs) -> Option<&ImportInfo> {
181 fn collect_trait_assoc_items(
183 db: &dyn DefDatabase,
186 original_import_info: &ImportInfo,
188 for (assoc_item_name, item) in &db.trait_data(tr).items {
189 let module_def_id = match *item {
190 AssocItemId::FunctionId(f) => f.into(),
191 AssocItemId::ConstId(c) => c.into(),
192 AssocItemId::TypeAliasId(t) => t.into(),
194 let assoc_item = if is_type_in_ns {
195 ItemInNs::Types(module_def_id)
197 ItemInNs::Values(module_def_id)
200 let mut assoc_item_info = original_import_info.to_owned();
201 assoc_item_info.path.segments.push(assoc_item_name.to_owned());
202 assoc_item_info.is_trait_assoc_item = true;
203 self.map.insert(assoc_item, assoc_item_info);
208 impl PartialEq for ImportMap {
209 fn eq(&self, other: &Self) -> bool {
210 // `fst` and `importables` are built from `map`, so we don't need to compare them.
211 self.map == other.map
215 impl Eq for ImportMap {}
217 impl fmt::Debug for ImportMap {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 let mut importable_paths: Vec<_> = self
222 .map(|(item, info)| {
223 let ns = match item {
224 ItemInNs::Types(_) => "t",
225 ItemInNs::Values(_) => "v",
226 ItemInNs::Macros(_) => "m",
228 format!("- {} ({})", info.path, ns)
232 importable_paths.sort();
233 f.write_str(&importable_paths.join("\n"))
237 fn fst_path(path: &ImportPath) -> String {
238 let mut s = path.to_string();
239 s.make_ascii_lowercase();
243 fn cmp((_, lhs): &(&ItemInNs, &ImportInfo), (_, rhs): &(&ItemInNs, &ImportInfo)) -> Ordering {
244 let lhs_str = fst_path(&lhs.path);
245 let rhs_str = fst_path(&rhs.path);
246 lhs_str.cmp(&rhs_str)
249 #[derive(Debug, Eq, PartialEq, Hash)]
250 pub enum ImportKind {
262 /// A way to match import map contents against the search query.
264 pub enum SearchMode {
265 /// Import map entry should strictly match the query string.
267 /// Import map entry should contain the query string.
269 /// Import map entry should contain all letters from the query string,
270 /// in the same order, but not necessary adjacent.
279 search_mode: SearchMode,
280 case_sensitive: bool,
282 exclude_import_kinds: FxHashSet<ImportKind>,
286 pub fn new(query: String) -> Self {
287 let lowercased = query.to_lowercase();
292 search_mode: SearchMode::Contains,
293 case_sensitive: false,
294 limit: usize::max_value(),
295 exclude_import_kinds: FxHashSet::default(),
299 /// Matches entries' names only, ignoring the rest of
301 /// Example: for `std::marker::PhantomData`, the name is `PhantomData`.
302 pub fn name_only(self) -> Self {
303 Self { name_only: true, ..self }
306 /// Specifies the way to search for the entries using the query.
307 pub fn search_mode(self, search_mode: SearchMode) -> Self {
308 Self { search_mode, ..self }
311 /// Limits the returned number of items to `limit`.
312 pub fn limit(self, limit: usize) -> Self {
313 Self { limit, ..self }
316 /// Respect casing of the query string when matching.
317 pub fn case_sensitive(self) -> Self {
318 Self { case_sensitive: true, ..self }
321 /// Do not include imports of the specified kind in the search results.
322 pub fn exclude_import_kind(mut self, import_kind: ImportKind) -> Self {
323 self.exclude_import_kinds.insert(import_kind);
328 fn import_matches_query(import: &ImportInfo, query: &Query, enforce_lowercase: bool) -> bool {
329 let mut input = if import.is_trait_assoc_item || query.name_only {
330 import.path.segments.last().unwrap().to_string()
332 import.path.to_string()
334 if enforce_lowercase || !query.case_sensitive {
335 input.make_ascii_lowercase();
339 if !enforce_lowercase && query.case_sensitive { &query.query } else { &query.lowercased };
341 match query.search_mode {
342 SearchMode::Equals => &input == query_string,
343 SearchMode::Contains => input.contains(query_string),
344 SearchMode::Fuzzy => {
345 let mut unchecked_query_chars = query_string.chars();
346 let mut mismatching_query_char = unchecked_query_chars.next();
348 for input_char in input.chars() {
349 match mismatching_query_char {
351 Some(matching_query_char) if matching_query_char == input_char => {
352 mismatching_query_char = unchecked_query_chars.next();
357 mismatching_query_char.is_none()
362 /// Searches dependencies of `krate` for an importable path matching `query`.
364 /// This returns a list of items that could be imported from dependencies of `krate`.
365 pub fn search_dependencies<'a>(
366 db: &'a dyn DefDatabase,
370 let _p = profile::span("search_dependencies").detail(|| format!("{:?}", query));
372 let graph = db.crate_graph();
373 let import_maps: Vec<_> =
374 graph[krate].dependencies.iter().map(|dep| db.import_map(dep.crate_id)).collect();
376 let automaton = fst::automaton::Subsequence::new(&query.lowercased);
378 let mut op = fst::map::OpBuilder::new();
379 for map in &import_maps {
380 op = op.add(map.fst.search(&automaton));
383 let mut stream = op.union();
384 let mut res = Vec::new();
385 while let Some((_, indexed_values)) = stream.next() {
386 for indexed_value in indexed_values {
387 let import_map = &import_maps[indexed_value.index];
388 let importables = &import_map.importables[indexed_value.value as usize..];
390 let common_importable_data = &import_map.map[&importables[0]];
391 if !import_matches_query(common_importable_data, &query, true) {
395 // Path shared by the importable items in this group.
396 let common_importables_path_fst = fst_path(&common_importable_data.path);
397 // Add the items from this `ModPath` group. Those are all subsequent items in
398 // `importables` whose paths match `path`.
399 let iter = importables
403 common_importables_path_fst == fst_path(&import_map.map[item].path)
405 .filter(|&item| match item_import_kind(item) {
406 Some(import_kind) => !query.exclude_import_kinds.contains(&import_kind),
410 !query.case_sensitive // we've already checked the common importables path case-insensitively
411 || import_matches_query(&import_map.map[item], &query, false)
415 if res.len() >= query.limit {
416 res.truncate(query.limit);
425 fn item_import_kind(item: ItemInNs) -> Option<ImportKind> {
426 Some(match item.as_module_def_id()? {
427 ModuleDefId::ModuleId(_) => ImportKind::Module,
428 ModuleDefId::FunctionId(_) => ImportKind::Function,
429 ModuleDefId::AdtId(_) => ImportKind::Adt,
430 ModuleDefId::EnumVariantId(_) => ImportKind::EnumVariant,
431 ModuleDefId::ConstId(_) => ImportKind::Const,
432 ModuleDefId::StaticId(_) => ImportKind::Static,
433 ModuleDefId::TraitId(_) => ImportKind::Trait,
434 ModuleDefId::TypeAliasId(_) => ImportKind::TypeAlias,
435 ModuleDefId::BuiltinType(_) => ImportKind::BuiltinType,
441 use base_db::{fixture::WithFixture, SourceDatabase, Upcast};
442 use expect_test::{expect, Expect};
444 use crate::{test_db::TestDB, AssocContainerId, Lookup};
448 fn check_search(ra_fixture: &str, crate_name: &str, query: Query, expect: Expect) {
449 let db = TestDB::with_files(ra_fixture);
450 let crate_graph = db.crate_graph();
451 let krate = crate_graph
454 crate_graph[*krate].display_name.as_ref().map(|n| n.to_string())
455 == Some(crate_name.to_string())
459 let actual = search_dependencies(db.upcast(), krate, query)
461 .filter_map(|dependency| {
462 let dependency_krate = dependency.krate(db.upcast())?;
463 let dependency_imports = db.import_map(dependency_krate);
465 let (path, mark) = match assoc_item_path(&db, &dependency_imports, dependency) {
466 Some(assoc_item_path) => (assoc_item_path, "a"),
468 dependency_imports.path_of(dependency)?.to_string(),
470 ItemInNs::Types(ModuleDefId::FunctionId(_))
471 | ItemInNs::Values(ModuleDefId::FunctionId(_)) => "f",
472 ItemInNs::Types(_) => "t",
473 ItemInNs::Values(_) => "v",
474 ItemInNs::Macros(_) => "m",
481 crate_graph[dependency_krate].display_name.as_ref()?,
486 .collect::<String>();
487 expect.assert_eq(&actual)
491 db: &dyn DefDatabase,
492 dependency_imports: &ImportMap,
493 dependency: ItemInNs,
494 ) -> Option<String> {
495 let dependency_assoc_item_id = match dependency {
496 ItemInNs::Types(ModuleDefId::FunctionId(id))
497 | ItemInNs::Values(ModuleDefId::FunctionId(id)) => AssocItemId::from(id),
498 ItemInNs::Types(ModuleDefId::ConstId(id))
499 | ItemInNs::Values(ModuleDefId::ConstId(id)) => AssocItemId::from(id),
500 ItemInNs::Types(ModuleDefId::TypeAliasId(id))
501 | ItemInNs::Values(ModuleDefId::TypeAliasId(id)) => AssocItemId::from(id),
505 let trait_ = assoc_to_trait(db, dependency)?;
506 if let ModuleDefId::TraitId(tr) = trait_.as_module_def_id()? {
507 let trait_data = db.trait_data(tr);
508 let assoc_item_name =
509 trait_data.items.iter().find_map(|(assoc_item_name, assoc_item_id)| {
510 if &dependency_assoc_item_id == assoc_item_id {
511 Some(assoc_item_name)
516 return Some(format!("{}::{}", dependency_imports.path_of(trait_)?, assoc_item_name));
521 fn assoc_to_trait(db: &dyn DefDatabase, item: ItemInNs) -> Option<ItemInNs> {
522 let assoc: AssocItemId = match item {
523 ItemInNs::Types(it) | ItemInNs::Values(it) => match it {
524 ModuleDefId::TypeAliasId(it) => it.into(),
525 ModuleDefId::FunctionId(it) => it.into(),
526 ModuleDefId::ConstId(it) => it.into(),
532 let container = match assoc {
533 AssocItemId::FunctionId(it) => it.lookup(db).container,
534 AssocItemId::ConstId(it) => it.lookup(db).container,
535 AssocItemId::TypeAliasId(it) => it.lookup(db).container,
539 AssocContainerId::TraitId(it) => Some(ItemInNs::Types(it.into())),
544 fn check(ra_fixture: &str, expect: Expect) {
545 let db = TestDB::with_files(ra_fixture);
546 let crate_graph = db.crate_graph();
548 let actual = crate_graph
550 .filter_map(|krate| {
551 let cdata = &crate_graph[krate];
552 let name = cdata.display_name.as_ref()?;
554 let map = db.import_map(krate);
556 Some(format!("{}:\n{:?}\n", name, map))
558 .collect::<String>();
560 expect.assert_eq(&actual)
567 //- /main.rs crate:main deps:lib
571 pub struct InPrivateModule;
581 pub mod real_pu2 { // same path length as above
585 //- /lib.rs crate:lib
587 pub struct Pub2; // t + v
605 fn prefers_shortest_path() {
608 //- /main.rs crate:main
615 pub use super::sub::subsub::Def;
628 fn type_reexport_cross_crate() {
629 // Reexports need to be visible from a crate, even if the original crate exports the item
630 // at a shorter path.
633 //- /main.rs crate:main deps:lib
637 //- /lib.rs crate:lib
653 fn macro_reexport() {
656 //- /main.rs crate:main deps:lib
658 pub use lib::pub_macro;
660 //- /lib.rs crate:lib
662 macro_rules! pub_macro {
677 fn module_reexport() {
678 // Reexporting modules from a dependency adds all contents to the import map.
681 //- /main.rs crate:main deps:lib
682 pub use lib::module as reexported_module;
683 //- /lib.rs crate:lib
690 - reexported_module (t)
691 - reexported_module::S (t)
692 - reexported_module::S (v)
702 fn cyclic_module_reexport() {
703 // A cyclic reexport does not hang.
706 //- /lib.rs crate:lib
709 pub use super::sub::*;
713 pub use super::module;
730 //- /lib.rs crate:lib
731 macro_rules! private_macro {
746 //- /lib.rs crate:lib
747 pub struct Thing; // t + v
749 macro_rules! Thing { // m
763 //- /lib.rs crate:lib
764 pub mod Thing {} // t
766 macro_rules! Thing { // m
779 fn fuzzy_import_trait_and_assoc_items() {
781 //- /main.rs crate:main deps:dep
782 //- /dep.rs crate:dep
786 const FMT_CONST: bool;
788 fn format_function();
789 fn format_method(&self);
797 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
800 dep::fmt::Display (t)
801 dep::fmt::Display::FMT_CONST (a)
802 dep::fmt::Display::FmtTypeAlias (a)
803 dep::fmt::Display::format_function (a)
804 dep::fmt::Display::format_method (a)
812 //- /main.rs crate:main deps:dep
813 //- /dep.rs crate:dep deps:tdep
814 use tdep::fmt as fmt_dep;
829 //- /tdep.rs crate:tdep
831 pub struct NotImportableFromMain;
838 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
844 dep::fmt::Display (t)
845 dep::fmt::Display::fmt (a)
853 Query::new("fmt".to_string()).search_mode(SearchMode::Equals),
859 dep::fmt::Display::fmt (a)
866 Query::new("fmt".to_string()).search_mode(SearchMode::Contains),
872 dep::fmt::Display (t)
873 dep::fmt::Display::fmt (a)
881 //- /main.rs crate:main deps:dep
882 //- /dep.rs crate:dep deps:tdep
883 use tdep::fmt as fmt_dep;
898 //- /tdep.rs crate:tdep
900 pub struct NotImportableFromMain;
907 Query::new("fmt".to_string()),
913 dep::fmt::Display (t)
914 dep::fmt::Display::fmt (a)
921 Query::new("fmt".to_string()).name_only(),
927 dep::fmt::Display::fmt (a)
935 //- /main.rs crate:main deps:dep
936 //- /dep.rs crate:dep
945 Query::new("FMT".to_string()),
957 Query::new("FMT".to_string()).case_sensitive(),
969 //- /main.rs crate:main deps:dep
970 //- /dep.rs crate:dep
986 Query::new("".to_string()).limit(2),
995 fn search_exclusions() {
997 //- /main.rs crate:main deps:dep
998 //- /dep.rs crate:dep
1007 Query::new("FMT".to_string()),
1019 Query::new("FMT".to_string()).exclude_import_kind(ImportKind::Adt),