1 //! A map of all publicly exported items in a crate.
3 use std::{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");
73 let mut import_map = collect_import_map(db, krate);
75 let mut importables = import_map.map.iter().collect::<Vec<_>>();
76 importables.sort_by_cached_key(|(_, import_info)| fst_path(&import_info.path));
78 // Build the FST, taking care not to insert duplicate values.
80 let mut builder = fst::MapBuilder::memory();
81 let mut last_batch_start = 0;
83 for idx in 0..importables.len() {
84 let key = fst_path(&importables[last_batch_start].1.path);
85 if let Some((_, next_import_info)) = importables.get(idx + 1) {
86 if key == fst_path(&next_import_info.path) {
91 builder.insert(key, last_batch_start as u64).unwrap();
93 last_batch_start = idx + 1;
96 import_map.fst = fst::Map::new(builder.into_inner().unwrap()).unwrap();
97 import_map.importables = importables.iter().map(|(item, _)| **item).collect();
102 /// Returns the `ModPath` needed to import/mention `item`, relative to this crate's root.
103 pub fn path_of(&self, item: ItemInNs) -> Option<&ImportPath> {
104 self.import_info_for(item).map(|it| &it.path)
107 pub fn import_info_for(&self, item: ItemInNs) -> Option<&ImportInfo> {
111 fn collect_trait_assoc_items(
113 db: &dyn DefDatabase,
116 original_import_info: &ImportInfo,
118 let _p = profile::span("collect_trait_assoc_items");
119 for (assoc_item_name, item) in &db.trait_data(tr).items {
120 let module_def_id = match item {
121 AssocItemId::FunctionId(f) => ModuleDefId::from(*f),
122 AssocItemId::ConstId(c) => ModuleDefId::from(*c),
123 // cannot use associated type aliases directly: need a `<Struct as Trait>::TypeAlias`
124 // qualifier, ergo no need to store it for imports in import_map
125 AssocItemId::TypeAliasId(_) => {
126 cov_mark::hit!(type_aliases_ignored);
130 let assoc_item = if is_type_in_ns {
131 ItemInNs::Types(module_def_id)
133 ItemInNs::Values(module_def_id)
136 let mut assoc_item_info = original_import_info.clone();
137 assoc_item_info.path.segments.push(assoc_item_name.to_owned());
138 assoc_item_info.is_trait_assoc_item = true;
139 self.map.insert(assoc_item, assoc_item_info);
144 fn collect_import_map(db: &dyn DefDatabase, krate: CrateId) -> ImportMap {
145 let _p = profile::span("collect_import_map");
147 let def_map = db.crate_def_map(krate);
148 let mut import_map = ImportMap::default();
150 // We look only into modules that are public(ly reexported), starting with the crate root.
151 let empty = ImportPath { segments: vec![] };
152 let root = def_map.module_id(def_map.root());
153 let mut worklist = vec![(root, empty)];
154 while let Some((module, mod_path)) = worklist.pop() {
156 let mod_data = if module.krate == krate {
157 &def_map[module.local_id]
159 // The crate might reexport a module defined in another crate.
160 ext_def_map = module.def_map(db);
161 &ext_def_map[module.local_id]
164 let visible_items = mod_data.scope.entries().filter_map(|(name, per_ns)| {
165 let per_ns = per_ns.filter_visibility(|vis| vis == Visibility::Public);
166 if per_ns.is_none() {
173 for (name, per_ns) in visible_items {
175 let mut path = mod_path.clone();
176 path.segments.push(name.clone());
180 for item in per_ns.iter_items() {
181 let path = mk_path();
182 let path_len = path.len();
184 ImportInfo { path, container: module, is_trait_assoc_item: false };
186 if let Some(ModuleDefId::TraitId(tr)) = item.as_module_def_id() {
187 import_map.collect_trait_assoc_items(
190 matches!(item, ItemInNs::Types(_)),
195 match import_map.map.entry(item) {
196 Entry::Vacant(entry) => {
197 entry.insert(import_info);
199 Entry::Occupied(mut entry) => {
200 // If the new path is shorter, prefer that one.
201 if path_len < entry.get().path.len() {
202 *entry.get_mut() = import_info;
209 // If we've just added a path to a module, descend into it. We might traverse
210 // modules multiple times, but only if the new path to it is shorter than the
211 // first (else we `continue` above).
212 if let Some(ModuleDefId::ModuleId(mod_id)) = item.as_module_def_id() {
213 worklist.push((mod_id, mk_path()));
222 impl PartialEq for ImportMap {
223 fn eq(&self, other: &Self) -> bool {
224 // `fst` and `importables` are built from `map`, so we don't need to compare them.
225 self.map == other.map
229 impl Eq for ImportMap {}
231 impl fmt::Debug for ImportMap {
232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233 let mut importable_paths: Vec<_> = self
236 .map(|(item, info)| {
237 let ns = match item {
238 ItemInNs::Types(_) => "t",
239 ItemInNs::Values(_) => "v",
240 ItemInNs::Macros(_) => "m",
242 format!("- {} ({})", info.path, ns)
246 importable_paths.sort();
247 f.write_str(&importable_paths.join("\n"))
251 fn fst_path(path: &ImportPath) -> String {
252 let _p = profile::span("fst_path");
253 let mut s = path.to_string();
254 s.make_ascii_lowercase();
258 #[derive(Debug, Eq, PartialEq, Hash)]
259 pub enum ImportKind {
272 /// A way to match import map contents against the search query.
274 pub enum SearchMode {
275 /// Import map entry should strictly match the query string.
277 /// Import map entry should contain the query string.
279 /// Import map entry should contain all letters from the query string,
280 /// in the same order, but not necessary adjacent.
289 assoc_items_only: bool,
290 search_mode: SearchMode,
291 case_sensitive: bool,
293 exclude_import_kinds: FxHashSet<ImportKind>,
297 pub fn new(query: String) -> Self {
298 let lowercased = query.to_lowercase();
303 assoc_items_only: false,
304 search_mode: SearchMode::Contains,
305 case_sensitive: false,
306 limit: usize::max_value(),
307 exclude_import_kinds: FxHashSet::default(),
311 /// Matches entries' names only, ignoring the rest of
313 /// Example: for `std::marker::PhantomData`, the name is `PhantomData`.
314 pub fn name_only(self) -> Self {
315 Self { name_only: true, ..self }
318 /// Matches only the entries that are associated items, ignoring the rest.
319 pub fn assoc_items_only(self) -> Self {
320 Self { assoc_items_only: true, ..self }
323 /// Specifies the way to search for the entries using the query.
324 pub fn search_mode(self, search_mode: SearchMode) -> Self {
325 Self { search_mode, ..self }
328 /// Limits the returned number of items to `limit`.
329 pub fn limit(self, limit: usize) -> Self {
330 Self { limit, ..self }
333 /// Respect casing of the query string when matching.
334 pub fn case_sensitive(self) -> Self {
335 Self { case_sensitive: true, ..self }
338 /// Do not include imports of the specified kind in the search results.
339 pub fn exclude_import_kind(mut self, import_kind: ImportKind) -> Self {
340 self.exclude_import_kinds.insert(import_kind);
344 fn import_matches(&self, import: &ImportInfo, enforce_lowercase: bool) -> bool {
345 let _p = profile::span("import_map::Query::import_matches");
346 if import.is_trait_assoc_item {
347 if self.exclude_import_kinds.contains(&ImportKind::AssociatedItem) {
350 } else if self.assoc_items_only {
354 let mut input = if import.is_trait_assoc_item || self.name_only {
355 import.path.segments.last().unwrap().to_string()
357 import.path.to_string()
359 if enforce_lowercase || !self.case_sensitive {
360 input.make_ascii_lowercase();
364 if !enforce_lowercase && self.case_sensitive { &self.query } else { &self.lowercased };
366 match self.search_mode {
367 SearchMode::Equals => &input == query_string,
368 SearchMode::Contains => input.contains(query_string),
369 SearchMode::Fuzzy => {
370 let mut unchecked_query_chars = query_string.chars();
371 let mut mismatching_query_char = unchecked_query_chars.next();
373 for input_char in input.chars() {
374 match mismatching_query_char {
376 Some(matching_query_char) if matching_query_char == input_char => {
377 mismatching_query_char = unchecked_query_chars.next();
382 mismatching_query_char.is_none()
388 /// Searches dependencies of `krate` for an importable path matching `query`.
390 /// This returns a list of items that could be imported from dependencies of `krate`.
391 pub fn search_dependencies<'a>(
392 db: &'a dyn DefDatabase,
395 ) -> FxHashSet<ItemInNs> {
396 let _p = profile::span("search_dependencies").detail(|| format!("{:?}", query));
398 let graph = db.crate_graph();
399 let import_maps: Vec<_> =
400 graph[krate].dependencies.iter().map(|dep| db.import_map(dep.crate_id)).collect();
402 let automaton = fst::automaton::Subsequence::new(&query.lowercased);
404 let mut op = fst::map::OpBuilder::new();
405 for map in &import_maps {
406 op = op.add(map.fst.search(&automaton));
409 let mut stream = op.union();
411 let mut all_indexed_values = FxHashSet::default();
412 while let Some((_, indexed_values)) = stream.next() {
413 all_indexed_values.extend(indexed_values.iter().copied());
416 let mut res = FxHashSet::default();
417 for indexed_value in all_indexed_values {
418 let import_map = &import_maps[indexed_value.index];
419 let importables = &import_map.importables[indexed_value.value as usize..];
421 let common_importable_data = &import_map.map[&importables[0]];
422 if !query.import_matches(common_importable_data, true) {
426 // Path shared by the importable items in this group.
427 let common_importables_path_fst = fst_path(&common_importable_data.path);
428 // Add the items from this `ModPath` group. Those are all subsequent items in
429 // `importables` whose paths match `path`.
430 let iter = importables
433 .take_while(|item| common_importables_path_fst == fst_path(&import_map.map[item].path))
434 .filter(|&item| match item_import_kind(item) {
435 Some(import_kind) => !query.exclude_import_kinds.contains(&import_kind),
439 !query.case_sensitive // we've already checked the common importables path case-insensitively
440 || query.import_matches(&import_map.map[item], false)
444 if res.len() >= query.limit {
452 fn item_import_kind(item: ItemInNs) -> Option<ImportKind> {
453 Some(match item.as_module_def_id()? {
454 ModuleDefId::ModuleId(_) => ImportKind::Module,
455 ModuleDefId::FunctionId(_) => ImportKind::Function,
456 ModuleDefId::AdtId(_) => ImportKind::Adt,
457 ModuleDefId::EnumVariantId(_) => ImportKind::EnumVariant,
458 ModuleDefId::ConstId(_) => ImportKind::Const,
459 ModuleDefId::StaticId(_) => ImportKind::Static,
460 ModuleDefId::TraitId(_) => ImportKind::Trait,
461 ModuleDefId::TypeAliasId(_) => ImportKind::TypeAlias,
462 ModuleDefId::BuiltinType(_) => ImportKind::BuiltinType,
468 use base_db::{fixture::WithFixture, SourceDatabase, Upcast};
469 use expect_test::{expect, Expect};
471 use crate::{test_db::TestDB, AssocContainerId, Lookup};
475 fn check_search(ra_fixture: &str, crate_name: &str, query: Query, expect: Expect) {
476 let db = TestDB::with_files(ra_fixture);
477 let crate_graph = db.crate_graph();
478 let krate = crate_graph
481 crate_graph[*krate].display_name.as_ref().map(|n| n.to_string())
482 == Some(crate_name.to_string())
486 let actual = search_dependencies(db.upcast(), krate, query)
488 .filter_map(|dependency| {
489 let dependency_krate = dependency.krate(db.upcast())?;
490 let dependency_imports = db.import_map(dependency_krate);
492 let (path, mark) = match assoc_item_path(&db, &dependency_imports, dependency) {
493 Some(assoc_item_path) => (assoc_item_path, "a"),
495 dependency_imports.path_of(dependency)?.to_string(),
497 ItemInNs::Types(ModuleDefId::FunctionId(_))
498 | ItemInNs::Values(ModuleDefId::FunctionId(_)) => "f",
499 ItemInNs::Types(_) => "t",
500 ItemInNs::Values(_) => "v",
501 ItemInNs::Macros(_) => "m",
508 crate_graph[dependency_krate].display_name.as_ref()?,
513 .collect::<String>();
514 expect.assert_eq(&actual)
518 db: &dyn DefDatabase,
519 dependency_imports: &ImportMap,
520 dependency: ItemInNs,
521 ) -> Option<String> {
522 let dependency_assoc_item_id = match dependency {
523 ItemInNs::Types(ModuleDefId::FunctionId(id))
524 | ItemInNs::Values(ModuleDefId::FunctionId(id)) => AssocItemId::from(id),
525 ItemInNs::Types(ModuleDefId::ConstId(id))
526 | ItemInNs::Values(ModuleDefId::ConstId(id)) => AssocItemId::from(id),
527 ItemInNs::Types(ModuleDefId::TypeAliasId(id))
528 | ItemInNs::Values(ModuleDefId::TypeAliasId(id)) => AssocItemId::from(id),
532 let trait_ = assoc_to_trait(db, dependency)?;
533 if let ModuleDefId::TraitId(tr) = trait_.as_module_def_id()? {
534 let trait_data = db.trait_data(tr);
535 let assoc_item_name =
536 trait_data.items.iter().find_map(|(assoc_item_name, assoc_item_id)| {
537 if &dependency_assoc_item_id == assoc_item_id {
538 Some(assoc_item_name)
543 return Some(format!("{}::{}", dependency_imports.path_of(trait_)?, assoc_item_name));
548 fn assoc_to_trait(db: &dyn DefDatabase, item: ItemInNs) -> Option<ItemInNs> {
549 let assoc: AssocItemId = match item {
550 ItemInNs::Types(it) | ItemInNs::Values(it) => match it {
551 ModuleDefId::TypeAliasId(it) => it.into(),
552 ModuleDefId::FunctionId(it) => it.into(),
553 ModuleDefId::ConstId(it) => it.into(),
559 let container = match assoc {
560 AssocItemId::FunctionId(it) => it.lookup(db).container,
561 AssocItemId::ConstId(it) => it.lookup(db).container,
562 AssocItemId::TypeAliasId(it) => it.lookup(db).container,
566 AssocContainerId::TraitId(it) => Some(ItemInNs::Types(it.into())),
571 fn check(ra_fixture: &str, expect: Expect) {
572 let db = TestDB::with_files(ra_fixture);
573 let crate_graph = db.crate_graph();
575 let actual = crate_graph
577 .filter_map(|krate| {
578 let cdata = &crate_graph[krate];
579 let name = cdata.display_name.as_ref()?;
581 let map = db.import_map(krate);
583 Some(format!("{}:\n{:?}\n", name, map))
585 .collect::<String>();
587 expect.assert_eq(&actual)
594 //- /main.rs crate:main deps:lib
598 pub struct InPrivateModule;
608 pub mod real_pu2 { // same path length as above
612 //- /lib.rs crate:lib
614 pub struct Pub2; // t + v
632 fn prefers_shortest_path() {
635 //- /main.rs crate:main
642 pub use super::sub::subsub::Def;
655 fn type_reexport_cross_crate() {
656 // Reexports need to be visible from a crate, even if the original crate exports the item
657 // at a shorter path.
660 //- /main.rs crate:main deps:lib
664 //- /lib.rs crate:lib
680 fn macro_reexport() {
683 //- /main.rs crate:main deps:lib
685 pub use lib::pub_macro;
687 //- /lib.rs crate:lib
689 macro_rules! pub_macro {
704 fn module_reexport() {
705 // Reexporting modules from a dependency adds all contents to the import map.
708 //- /main.rs crate:main deps:lib
709 pub use lib::module as reexported_module;
710 //- /lib.rs crate:lib
717 - reexported_module (t)
718 - reexported_module::S (t)
719 - reexported_module::S (v)
729 fn cyclic_module_reexport() {
730 // A cyclic reexport does not hang.
733 //- /lib.rs crate:lib
736 pub use super::sub::*;
740 pub use super::module;
757 //- /lib.rs crate:lib
758 macro_rules! private_macro {
773 //- /lib.rs crate:lib
774 pub struct Thing; // t + v
776 macro_rules! Thing { // m
790 //- /lib.rs crate:lib
791 pub mod Thing {} // t
793 macro_rules! Thing { // m
806 fn fuzzy_import_trait_and_assoc_items() {
807 cov_mark::check!(type_aliases_ignored);
809 //- /main.rs crate:main deps:dep
810 //- /dep.rs crate:dep
814 const FMT_CONST: bool;
816 fn format_function();
817 fn format_method(&self);
825 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
828 dep::fmt::Display::format_method (a)
829 dep::fmt::Display (t)
830 dep::fmt::Display::FMT_CONST (a)
831 dep::fmt::Display::format_function (a)
837 fn assoc_items_filtering() {
839 //- /main.rs crate:main deps:dep
840 //- /dep.rs crate:dep
844 const FMT_CONST: bool;
846 fn format_function();
847 fn format_method(&self);
855 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy).assoc_items_only(),
857 dep::fmt::Display::format_method (a)
858 dep::fmt::Display::FMT_CONST (a)
859 dep::fmt::Display::format_function (a)
866 Query::new("fmt".to_string())
867 .search_mode(SearchMode::Fuzzy)
868 .exclude_import_kind(ImportKind::AssociatedItem),
871 dep::fmt::Display (t)
878 Query::new("fmt".to_string())
879 .search_mode(SearchMode::Fuzzy)
881 .exclude_import_kind(ImportKind::AssociatedItem),
889 //- /main.rs crate:main deps:dep
890 //- /dep.rs crate:dep deps:tdep
891 use tdep::fmt as fmt_dep;
906 //- /tdep.rs crate:tdep
908 pub struct NotImportableFromMain;
915 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
922 dep::fmt::Display::fmt (a)
923 dep::fmt::Display (t)
930 Query::new("fmt".to_string()).search_mode(SearchMode::Equals),
936 dep::fmt::Display::fmt (a)
943 Query::new("fmt".to_string()).search_mode(SearchMode::Contains),
949 dep::fmt::Display::fmt (a)
950 dep::fmt::Display (t)
958 //- /main.rs crate:main deps:dep
959 //- /dep.rs crate:dep deps:tdep
960 use tdep::fmt as fmt_dep;
975 //- /tdep.rs crate:tdep
977 pub struct NotImportableFromMain;
984 Query::new("fmt".to_string()),
990 dep::fmt::Display::fmt (a)
991 dep::fmt::Display (t)
998 Query::new("fmt".to_string()).name_only(),
1004 dep::fmt::Display::fmt (a)
1010 fn search_casing() {
1011 let ra_fixture = r#"
1012 //- /main.rs crate:main deps:dep
1013 //- /dep.rs crate:dep
1022 Query::new("FMT".to_string()),
1034 Query::new("FMT".to_string()).case_sensitive(),
1046 //- /main.rs crate:main deps:dep
1047 //- /dep.rs crate:dep
1063 Query::new("".to_string()).limit(2),
1074 fn search_exclusions() {
1075 let ra_fixture = r#"
1076 //- /main.rs crate:main deps:dep
1077 //- /dep.rs crate:dep
1086 Query::new("FMT".to_string()),
1098 Query::new("FMT".to_string()).exclude_import_kind(ImportKind::Adt),