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};
14 db::DefDatabase, item_scope::ItemInNs, visibility::Visibility, AssocItemId, ModuleDefId,
18 type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<FxHasher>>;
20 /// Item import details stored in the `ImportMap`.
21 #[derive(Debug, Clone, Eq, PartialEq)]
22 pub struct ImportInfo {
23 /// A path that can be used to import the item, relative to the crate's root.
25 /// The module containing this item.
26 pub container: ModuleId,
27 /// Whether the import is a trait associated item or not.
28 pub is_trait_assoc_item: bool,
31 #[derive(Debug, Clone, Eq, PartialEq)]
32 pub struct ImportPath {
33 pub segments: Vec<Name>,
36 impl fmt::Display for ImportPath {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 fmt::Display::fmt(&self.segments.iter().format("::"), f)
43 fn len(&self) -> usize {
48 /// A map from publicly exported items to the path needed to import/name them from a downstream
51 /// Reexports of items are taken into account, ie. if something is exported under multiple
52 /// names, the one with the shortest import path will be used.
54 /// Note that all paths are relative to the containing crate's root, so the crate name still needs
55 /// to be prepended to the `ModPath` before the path is valid.
57 pub struct ImportMap {
58 map: FxIndexMap<ItemInNs, ImportInfo>,
60 /// List of keys stored in `map`, sorted lexicographically by their `ModPath`. Indexed by the
61 /// values returned by running `fst`.
63 /// Since a path can refer to multiple items due to namespacing, we store all items with the
64 /// same path right after each other. This allows us to find all items after the FST gives us
65 /// the index of the first one.
66 importables: Vec<ItemInNs>,
67 fst: fst::Map<Vec<u8>>,
71 pub fn import_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<Self> {
72 let _p = profile::span("import_map_query");
73 let def_map = db.crate_def_map(krate);
74 let mut import_map = Self::default();
76 // We look only into modules that are public(ly reexported), starting with the crate root.
77 let empty = ImportPath { segments: vec![] };
78 let root = ModuleId { krate, local_id: def_map.root() };
79 let mut worklist = vec![(root, empty)];
80 while let Some((module, mod_path)) = worklist.pop() {
82 let mod_data = if module.krate == krate {
83 &def_map[module.local_id]
85 // The crate might reexport a module defined in another crate.
86 ext_def_map = module.def_map(db);
87 &ext_def_map[module.local_id]
90 let visible_items = mod_data.scope.entries().filter_map(|(name, per_ns)| {
91 let per_ns = per_ns.filter_visibility(|vis| vis == Visibility::Public);
99 for (name, per_ns) in visible_items {
101 let mut path = mod_path.clone();
102 path.segments.push(name.clone());
106 for item in per_ns.iter_items() {
107 let path = mk_path();
108 let path_len = path.len();
110 ImportInfo { path, container: module, is_trait_assoc_item: false };
112 if let Some(ModuleDefId::TraitId(tr)) = item.as_module_def_id() {
113 import_map.collect_trait_assoc_items(
116 matches!(item, ItemInNs::Types(_)),
121 match import_map.map.entry(item) {
122 Entry::Vacant(entry) => {
123 entry.insert(import_info);
125 Entry::Occupied(mut entry) => {
126 // If the new path is shorter, prefer that one.
127 if path_len < entry.get().path.len() {
128 *entry.get_mut() = import_info;
135 // If we've just added a path to a module, descend into it. We might traverse
136 // modules multiple times, but only if the new path to it is shorter than the
137 // first (else we `continue` above).
138 if let Some(ModuleDefId::ModuleId(mod_id)) = item.as_module_def_id() {
139 worklist.push((mod_id, mk_path()));
145 let mut importables = import_map.map.iter().collect::<Vec<_>>();
147 importables.sort_by(cmp);
149 // Build the FST, taking care not to insert duplicate values.
151 let mut builder = fst::MapBuilder::memory();
152 let mut last_batch_start = 0;
154 for idx in 0..importables.len() {
155 if let Some(next_item) = importables.get(idx + 1) {
156 if cmp(&importables[last_batch_start], next_item) == Ordering::Equal {
161 let key = fst_path(&importables[last_batch_start].1.path);
162 builder.insert(key, last_batch_start as u64).unwrap();
164 last_batch_start = idx + 1;
167 import_map.fst = fst::Map::new(builder.into_inner().unwrap()).unwrap();
168 import_map.importables = importables.iter().map(|(item, _)| **item).collect();
173 /// Returns the `ModPath` needed to import/mention `item`, relative to this crate's root.
174 pub fn path_of(&self, item: ItemInNs) -> Option<&ImportPath> {
175 self.import_info_for(item).map(|it| &it.path)
178 pub fn import_info_for(&self, item: ItemInNs) -> Option<&ImportInfo> {
182 fn collect_trait_assoc_items(
184 db: &dyn DefDatabase,
187 original_import_info: &ImportInfo,
189 for (assoc_item_name, item) in &db.trait_data(tr).items {
190 let module_def_id = match item {
191 AssocItemId::FunctionId(f) => ModuleDefId::from(*f),
192 AssocItemId::ConstId(c) => ModuleDefId::from(*c),
193 // cannot use associated type aliases directly: need a `<Struct as Trait>::TypeAlias`
194 // qualifier, ergo no need to store it for imports in import_map
195 AssocItemId::TypeAliasId(_) => {
196 mark::hit!(type_aliases_ignored);
200 let assoc_item = if is_type_in_ns {
201 ItemInNs::Types(module_def_id)
203 ItemInNs::Values(module_def_id)
206 let mut assoc_item_info = original_import_info.clone();
207 assoc_item_info.path.segments.push(assoc_item_name.to_owned());
208 assoc_item_info.is_trait_assoc_item = true;
209 self.map.insert(assoc_item, assoc_item_info);
214 impl PartialEq for ImportMap {
215 fn eq(&self, other: &Self) -> bool {
216 // `fst` and `importables` are built from `map`, so we don't need to compare them.
217 self.map == other.map
221 impl Eq for ImportMap {}
223 impl fmt::Debug for ImportMap {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 let mut importable_paths: Vec<_> = self
228 .map(|(item, info)| {
229 let ns = match item {
230 ItemInNs::Types(_) => "t",
231 ItemInNs::Values(_) => "v",
232 ItemInNs::Macros(_) => "m",
234 format!("- {} ({})", info.path, ns)
238 importable_paths.sort();
239 f.write_str(&importable_paths.join("\n"))
243 fn fst_path(path: &ImportPath) -> String {
244 let mut s = path.to_string();
245 s.make_ascii_lowercase();
249 fn cmp((_, lhs): &(&ItemInNs, &ImportInfo), (_, rhs): &(&ItemInNs, &ImportInfo)) -> Ordering {
250 let lhs_str = fst_path(&lhs.path);
251 let rhs_str = fst_path(&rhs.path);
252 lhs_str.cmp(&rhs_str)
255 #[derive(Debug, Eq, PartialEq, Hash)]
256 pub enum ImportKind {
269 /// A way to match import map contents against the search query.
271 pub enum SearchMode {
272 /// Import map entry should strictly match the query string.
274 /// Import map entry should contain the query string.
276 /// Import map entry should contain all letters from the query string,
277 /// in the same order, but not necessary adjacent.
286 assoc_items_only: bool,
287 search_mode: SearchMode,
288 case_sensitive: bool,
290 exclude_import_kinds: FxHashSet<ImportKind>,
294 pub fn new(query: String) -> Self {
295 let lowercased = query.to_lowercase();
300 assoc_items_only: false,
301 search_mode: SearchMode::Contains,
302 case_sensitive: false,
303 limit: usize::max_value(),
304 exclude_import_kinds: FxHashSet::default(),
308 /// Matches entries' names only, ignoring the rest of
310 /// Example: for `std::marker::PhantomData`, the name is `PhantomData`.
311 pub fn name_only(self) -> Self {
312 Self { name_only: true, ..self }
315 /// Matches only the entries that are associated items, ignoring the rest.
316 pub fn assoc_items_only(self) -> Self {
317 Self { assoc_items_only: true, ..self }
320 /// Specifies the way to search for the entries using the query.
321 pub fn search_mode(self, search_mode: SearchMode) -> Self {
322 Self { search_mode, ..self }
325 /// Limits the returned number of items to `limit`.
326 pub fn limit(self, limit: usize) -> Self {
327 Self { limit, ..self }
330 /// Respect casing of the query string when matching.
331 pub fn case_sensitive(self) -> Self {
332 Self { case_sensitive: true, ..self }
335 /// Do not include imports of the specified kind in the search results.
336 pub fn exclude_import_kind(mut self, import_kind: ImportKind) -> Self {
337 self.exclude_import_kinds.insert(import_kind);
341 fn import_matches(&self, import: &ImportInfo, enforce_lowercase: bool) -> bool {
342 if import.is_trait_assoc_item {
343 if self.exclude_import_kinds.contains(&ImportKind::AssociatedItem) {
346 } else if self.assoc_items_only {
350 let mut input = if import.is_trait_assoc_item || self.name_only {
351 import.path.segments.last().unwrap().to_string()
353 import.path.to_string()
355 if enforce_lowercase || !self.case_sensitive {
356 input.make_ascii_lowercase();
360 if !enforce_lowercase && self.case_sensitive { &self.query } else { &self.lowercased };
362 match self.search_mode {
363 SearchMode::Equals => &input == query_string,
364 SearchMode::Contains => input.contains(query_string),
365 SearchMode::Fuzzy => {
366 let mut unchecked_query_chars = query_string.chars();
367 let mut mismatching_query_char = unchecked_query_chars.next();
369 for input_char in input.chars() {
370 match mismatching_query_char {
372 Some(matching_query_char) if matching_query_char == input_char => {
373 mismatching_query_char = unchecked_query_chars.next();
378 mismatching_query_char.is_none()
384 /// Searches dependencies of `krate` for an importable path matching `query`.
386 /// This returns a list of items that could be imported from dependencies of `krate`.
387 pub fn search_dependencies<'a>(
388 db: &'a dyn DefDatabase,
392 let _p = profile::span("search_dependencies").detail(|| format!("{:?}", query));
394 let graph = db.crate_graph();
395 let import_maps: Vec<_> =
396 graph[krate].dependencies.iter().map(|dep| db.import_map(dep.crate_id)).collect();
398 let automaton = fst::automaton::Subsequence::new(&query.lowercased);
400 let mut op = fst::map::OpBuilder::new();
401 for map in &import_maps {
402 op = op.add(map.fst.search(&automaton));
405 let mut stream = op.union();
406 let mut res = Vec::new();
407 while let Some((_, indexed_values)) = stream.next() {
408 for indexed_value in indexed_values {
409 let import_map = &import_maps[indexed_value.index];
410 let importables = &import_map.importables[indexed_value.value as usize..];
412 let common_importable_data = &import_map.map[&importables[0]];
413 if !query.import_matches(common_importable_data, true) {
417 // Path shared by the importable items in this group.
418 let common_importables_path_fst = fst_path(&common_importable_data.path);
419 // Add the items from this `ModPath` group. Those are all subsequent items in
420 // `importables` whose paths match `path`.
421 let iter = importables
425 common_importables_path_fst == fst_path(&import_map.map[item].path)
427 .filter(|&item| match item_import_kind(item) {
428 Some(import_kind) => !query.exclude_import_kinds.contains(&import_kind),
432 !query.case_sensitive // we've already checked the common importables path case-insensitively
433 || query.import_matches(&import_map.map[item], false)
437 if res.len() >= query.limit {
438 res.truncate(query.limit);
447 fn item_import_kind(item: ItemInNs) -> Option<ImportKind> {
448 Some(match item.as_module_def_id()? {
449 ModuleDefId::ModuleId(_) => ImportKind::Module,
450 ModuleDefId::FunctionId(_) => ImportKind::Function,
451 ModuleDefId::AdtId(_) => ImportKind::Adt,
452 ModuleDefId::EnumVariantId(_) => ImportKind::EnumVariant,
453 ModuleDefId::ConstId(_) => ImportKind::Const,
454 ModuleDefId::StaticId(_) => ImportKind::Static,
455 ModuleDefId::TraitId(_) => ImportKind::Trait,
456 ModuleDefId::TypeAliasId(_) => ImportKind::TypeAlias,
457 ModuleDefId::BuiltinType(_) => ImportKind::BuiltinType,
463 use base_db::{fixture::WithFixture, SourceDatabase, Upcast};
464 use expect_test::{expect, Expect};
465 use test_utils::mark;
467 use crate::{test_db::TestDB, AssocContainerId, Lookup};
471 fn check_search(ra_fixture: &str, crate_name: &str, query: Query, expect: Expect) {
472 let db = TestDB::with_files(ra_fixture);
473 let crate_graph = db.crate_graph();
474 let krate = crate_graph
477 crate_graph[*krate].display_name.as_ref().map(|n| n.to_string())
478 == Some(crate_name.to_string())
482 let actual = search_dependencies(db.upcast(), krate, query)
484 .filter_map(|dependency| {
485 let dependency_krate = dependency.krate(db.upcast())?;
486 let dependency_imports = db.import_map(dependency_krate);
488 let (path, mark) = match assoc_item_path(&db, &dependency_imports, dependency) {
489 Some(assoc_item_path) => (assoc_item_path, "a"),
491 dependency_imports.path_of(dependency)?.to_string(),
493 ItemInNs::Types(ModuleDefId::FunctionId(_))
494 | ItemInNs::Values(ModuleDefId::FunctionId(_)) => "f",
495 ItemInNs::Types(_) => "t",
496 ItemInNs::Values(_) => "v",
497 ItemInNs::Macros(_) => "m",
504 crate_graph[dependency_krate].display_name.as_ref()?,
509 .collect::<String>();
510 expect.assert_eq(&actual)
514 db: &dyn DefDatabase,
515 dependency_imports: &ImportMap,
516 dependency: ItemInNs,
517 ) -> Option<String> {
518 let dependency_assoc_item_id = match dependency {
519 ItemInNs::Types(ModuleDefId::FunctionId(id))
520 | ItemInNs::Values(ModuleDefId::FunctionId(id)) => AssocItemId::from(id),
521 ItemInNs::Types(ModuleDefId::ConstId(id))
522 | ItemInNs::Values(ModuleDefId::ConstId(id)) => AssocItemId::from(id),
523 ItemInNs::Types(ModuleDefId::TypeAliasId(id))
524 | ItemInNs::Values(ModuleDefId::TypeAliasId(id)) => AssocItemId::from(id),
528 let trait_ = assoc_to_trait(db, dependency)?;
529 if let ModuleDefId::TraitId(tr) = trait_.as_module_def_id()? {
530 let trait_data = db.trait_data(tr);
531 let assoc_item_name =
532 trait_data.items.iter().find_map(|(assoc_item_name, assoc_item_id)| {
533 if &dependency_assoc_item_id == assoc_item_id {
534 Some(assoc_item_name)
539 return Some(format!("{}::{}", dependency_imports.path_of(trait_)?, assoc_item_name));
544 fn assoc_to_trait(db: &dyn DefDatabase, item: ItemInNs) -> Option<ItemInNs> {
545 let assoc: AssocItemId = match item {
546 ItemInNs::Types(it) | ItemInNs::Values(it) => match it {
547 ModuleDefId::TypeAliasId(it) => it.into(),
548 ModuleDefId::FunctionId(it) => it.into(),
549 ModuleDefId::ConstId(it) => it.into(),
555 let container = match assoc {
556 AssocItemId::FunctionId(it) => it.lookup(db).container,
557 AssocItemId::ConstId(it) => it.lookup(db).container,
558 AssocItemId::TypeAliasId(it) => it.lookup(db).container,
562 AssocContainerId::TraitId(it) => Some(ItemInNs::Types(it.into())),
567 fn check(ra_fixture: &str, expect: Expect) {
568 let db = TestDB::with_files(ra_fixture);
569 let crate_graph = db.crate_graph();
571 let actual = crate_graph
573 .filter_map(|krate| {
574 let cdata = &crate_graph[krate];
575 let name = cdata.display_name.as_ref()?;
577 let map = db.import_map(krate);
579 Some(format!("{}:\n{:?}\n", name, map))
581 .collect::<String>();
583 expect.assert_eq(&actual)
590 //- /main.rs crate:main deps:lib
594 pub struct InPrivateModule;
604 pub mod real_pu2 { // same path length as above
608 //- /lib.rs crate:lib
610 pub struct Pub2; // t + v
628 fn prefers_shortest_path() {
631 //- /main.rs crate:main
638 pub use super::sub::subsub::Def;
651 fn type_reexport_cross_crate() {
652 // Reexports need to be visible from a crate, even if the original crate exports the item
653 // at a shorter path.
656 //- /main.rs crate:main deps:lib
660 //- /lib.rs crate:lib
676 fn macro_reexport() {
679 //- /main.rs crate:main deps:lib
681 pub use lib::pub_macro;
683 //- /lib.rs crate:lib
685 macro_rules! pub_macro {
700 fn module_reexport() {
701 // Reexporting modules from a dependency adds all contents to the import map.
704 //- /main.rs crate:main deps:lib
705 pub use lib::module as reexported_module;
706 //- /lib.rs crate:lib
713 - reexported_module (t)
714 - reexported_module::S (t)
715 - reexported_module::S (v)
725 fn cyclic_module_reexport() {
726 // A cyclic reexport does not hang.
729 //- /lib.rs crate:lib
732 pub use super::sub::*;
736 pub use super::module;
753 //- /lib.rs crate:lib
754 macro_rules! private_macro {
769 //- /lib.rs crate:lib
770 pub struct Thing; // t + v
772 macro_rules! Thing { // m
786 //- /lib.rs crate:lib
787 pub mod Thing {} // t
789 macro_rules! Thing { // m
802 fn fuzzy_import_trait_and_assoc_items() {
803 mark::check!(type_aliases_ignored);
805 //- /main.rs crate:main deps:dep
806 //- /dep.rs crate:dep
810 const FMT_CONST: bool;
812 fn format_function();
813 fn format_method(&self);
821 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
824 dep::fmt::Display (t)
825 dep::fmt::Display::FMT_CONST (a)
826 dep::fmt::Display::format_function (a)
827 dep::fmt::Display::format_method (a)
833 fn assoc_items_filtering() {
835 //- /main.rs crate:main deps:dep
836 //- /dep.rs crate:dep
840 const FMT_CONST: bool;
842 fn format_function();
843 fn format_method(&self);
851 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy).assoc_items_only(),
853 dep::fmt::Display::FMT_CONST (a)
854 dep::fmt::Display::format_function (a)
855 dep::fmt::Display::format_method (a)
862 Query::new("fmt".to_string())
863 .search_mode(SearchMode::Fuzzy)
864 .exclude_import_kind(ImportKind::AssociatedItem),
867 dep::fmt::Display (t)
874 Query::new("fmt".to_string())
875 .search_mode(SearchMode::Fuzzy)
877 .exclude_import_kind(ImportKind::AssociatedItem),
885 //- /main.rs crate:main deps:dep
886 //- /dep.rs crate:dep deps:tdep
887 use tdep::fmt as fmt_dep;
902 //- /tdep.rs crate:tdep
904 pub struct NotImportableFromMain;
911 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
917 dep::fmt::Display (t)
918 dep::fmt::Display::fmt (a)
926 Query::new("fmt".to_string()).search_mode(SearchMode::Equals),
932 dep::fmt::Display::fmt (a)
939 Query::new("fmt".to_string()).search_mode(SearchMode::Contains),
945 dep::fmt::Display (t)
946 dep::fmt::Display::fmt (a)
954 //- /main.rs crate:main deps:dep
955 //- /dep.rs crate:dep deps:tdep
956 use tdep::fmt as fmt_dep;
971 //- /tdep.rs crate:tdep
973 pub struct NotImportableFromMain;
980 Query::new("fmt".to_string()),
986 dep::fmt::Display (t)
987 dep::fmt::Display::fmt (a)
994 Query::new("fmt".to_string()).name_only(),
1000 dep::fmt::Display::fmt (a)
1006 fn search_casing() {
1007 let ra_fixture = r#"
1008 //- /main.rs crate:main deps:dep
1009 //- /dep.rs crate:dep
1018 Query::new("FMT".to_string()),
1030 Query::new("FMT".to_string()).case_sensitive(),
1042 //- /main.rs crate:main deps:dep
1043 //- /dep.rs crate:dep
1059 Query::new("".to_string()).limit(2),
1068 fn search_exclusions() {
1069 let ra_fixture = r#"
1070 //- /main.rs crate:main deps:dep
1071 //- /dep.rs crate:dep
1080 Query::new("FMT".to_string()),
1092 Query::new("FMT".to_string()).exclude_import_kind(ImportKind::Adt),