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 = def_map.module_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 = module.def_map(db);
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) => ModuleDefId::from(*f),
191 AssocItemId::ConstId(c) => ModuleDefId::from(*c),
192 // cannot use associated type aliases directly: need a `<Struct as Trait>::TypeAlias`
193 // qualifier, ergo no need to store it for imports in import_map
194 AssocItemId::TypeAliasId(_) => {
195 cov_mark::hit!(type_aliases_ignored);
199 let assoc_item = if is_type_in_ns {
200 ItemInNs::Types(module_def_id)
202 ItemInNs::Values(module_def_id)
205 let mut assoc_item_info = original_import_info.clone();
206 assoc_item_info.path.segments.push(assoc_item_name.to_owned());
207 assoc_item_info.is_trait_assoc_item = true;
208 self.map.insert(assoc_item, assoc_item_info);
213 impl PartialEq for ImportMap {
214 fn eq(&self, other: &Self) -> bool {
215 // `fst` and `importables` are built from `map`, so we don't need to compare them.
216 self.map == other.map
220 impl Eq for ImportMap {}
222 impl fmt::Debug for ImportMap {
223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 let mut importable_paths: Vec<_> = self
227 .map(|(item, info)| {
228 let ns = match item {
229 ItemInNs::Types(_) => "t",
230 ItemInNs::Values(_) => "v",
231 ItemInNs::Macros(_) => "m",
233 format!("- {} ({})", info.path, ns)
237 importable_paths.sort();
238 f.write_str(&importable_paths.join("\n"))
242 fn fst_path(path: &ImportPath) -> String {
243 let mut s = path.to_string();
244 s.make_ascii_lowercase();
248 fn cmp((_, lhs): &(&ItemInNs, &ImportInfo), (_, rhs): &(&ItemInNs, &ImportInfo)) -> Ordering {
249 let lhs_str = fst_path(&lhs.path);
250 let rhs_str = fst_path(&rhs.path);
251 lhs_str.cmp(&rhs_str)
254 #[derive(Debug, Eq, PartialEq, Hash)]
255 pub enum ImportKind {
268 /// A way to match import map contents against the search query.
270 pub enum SearchMode {
271 /// Import map entry should strictly match the query string.
273 /// Import map entry should contain the query string.
275 /// Import map entry should contain all letters from the query string,
276 /// in the same order, but not necessary adjacent.
285 assoc_items_only: bool,
286 search_mode: SearchMode,
287 case_sensitive: bool,
289 exclude_import_kinds: FxHashSet<ImportKind>,
293 pub fn new(query: String) -> Self {
294 let lowercased = query.to_lowercase();
299 assoc_items_only: false,
300 search_mode: SearchMode::Contains,
301 case_sensitive: false,
302 limit: usize::max_value(),
303 exclude_import_kinds: FxHashSet::default(),
307 /// Matches entries' names only, ignoring the rest of
309 /// Example: for `std::marker::PhantomData`, the name is `PhantomData`.
310 pub fn name_only(self) -> Self {
311 Self { name_only: true, ..self }
314 /// Matches only the entries that are associated items, ignoring the rest.
315 pub fn assoc_items_only(self) -> Self {
316 Self { assoc_items_only: true, ..self }
319 /// Specifies the way to search for the entries using the query.
320 pub fn search_mode(self, search_mode: SearchMode) -> Self {
321 Self { search_mode, ..self }
324 /// Limits the returned number of items to `limit`.
325 pub fn limit(self, limit: usize) -> Self {
326 Self { limit, ..self }
329 /// Respect casing of the query string when matching.
330 pub fn case_sensitive(self) -> Self {
331 Self { case_sensitive: true, ..self }
334 /// Do not include imports of the specified kind in the search results.
335 pub fn exclude_import_kind(mut self, import_kind: ImportKind) -> Self {
336 self.exclude_import_kinds.insert(import_kind);
340 fn import_matches(&self, import: &ImportInfo, enforce_lowercase: bool) -> bool {
341 if import.is_trait_assoc_item {
342 if self.exclude_import_kinds.contains(&ImportKind::AssociatedItem) {
345 } else if self.assoc_items_only {
349 let mut input = if import.is_trait_assoc_item || self.name_only {
350 import.path.segments.last().unwrap().to_string()
352 import.path.to_string()
354 if enforce_lowercase || !self.case_sensitive {
355 input.make_ascii_lowercase();
359 if !enforce_lowercase && self.case_sensitive { &self.query } else { &self.lowercased };
361 match self.search_mode {
362 SearchMode::Equals => &input == query_string,
363 SearchMode::Contains => input.contains(query_string),
364 SearchMode::Fuzzy => {
365 let mut unchecked_query_chars = query_string.chars();
366 let mut mismatching_query_char = unchecked_query_chars.next();
368 for input_char in input.chars() {
369 match mismatching_query_char {
371 Some(matching_query_char) if matching_query_char == input_char => {
372 mismatching_query_char = unchecked_query_chars.next();
377 mismatching_query_char.is_none()
383 /// Searches dependencies of `krate` for an importable path matching `query`.
385 /// This returns a list of items that could be imported from dependencies of `krate`.
386 pub fn search_dependencies<'a>(
387 db: &'a dyn DefDatabase,
390 ) -> FxHashSet<ItemInNs> {
391 let _p = profile::span("search_dependencies").detail(|| format!("{:?}", query));
393 let graph = db.crate_graph();
394 let import_maps: Vec<_> =
395 graph[krate].dependencies.iter().map(|dep| db.import_map(dep.crate_id)).collect();
397 let automaton = fst::automaton::Subsequence::new(&query.lowercased);
399 let mut op = fst::map::OpBuilder::new();
400 for map in &import_maps {
401 op = op.add(map.fst.search(&automaton));
404 let mut stream = op.union();
406 let mut all_indexed_values = FxHashSet::default();
407 while let Some((_, indexed_values)) = stream.next() {
408 all_indexed_values.extend(indexed_values.iter().copied());
411 let mut res = FxHashSet::default();
412 for indexed_value in all_indexed_values {
413 let import_map = &import_maps[indexed_value.index];
414 let importables = &import_map.importables[indexed_value.value as usize..];
416 let common_importable_data = &import_map.map[&importables[0]];
417 if !query.import_matches(common_importable_data, true) {
421 // Path shared by the importable items in this group.
422 let common_importables_path_fst = fst_path(&common_importable_data.path);
423 // Add the items from this `ModPath` group. Those are all subsequent items in
424 // `importables` whose paths match `path`.
425 let iter = importables
428 .take_while(|item| common_importables_path_fst == fst_path(&import_map.map[item].path))
429 .filter(|&item| match item_import_kind(item) {
430 Some(import_kind) => !query.exclude_import_kinds.contains(&import_kind),
434 !query.case_sensitive // we've already checked the common importables path case-insensitively
435 || query.import_matches(&import_map.map[item], false)
439 if res.len() >= 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};
466 use crate::{test_db::TestDB, AssocContainerId, Lookup};
470 fn check_search(ra_fixture: &str, crate_name: &str, query: Query, expect: Expect) {
471 let db = TestDB::with_files(ra_fixture);
472 let crate_graph = db.crate_graph();
473 let krate = crate_graph
476 crate_graph[*krate].display_name.as_ref().map(|n| n.to_string())
477 == Some(crate_name.to_string())
481 let actual = search_dependencies(db.upcast(), krate, query)
483 .filter_map(|dependency| {
484 let dependency_krate = dependency.krate(db.upcast())?;
485 let dependency_imports = db.import_map(dependency_krate);
487 let (path, mark) = match assoc_item_path(&db, &dependency_imports, dependency) {
488 Some(assoc_item_path) => (assoc_item_path, "a"),
490 dependency_imports.path_of(dependency)?.to_string(),
492 ItemInNs::Types(ModuleDefId::FunctionId(_))
493 | ItemInNs::Values(ModuleDefId::FunctionId(_)) => "f",
494 ItemInNs::Types(_) => "t",
495 ItemInNs::Values(_) => "v",
496 ItemInNs::Macros(_) => "m",
503 crate_graph[dependency_krate].display_name.as_ref()?,
508 .collect::<String>();
509 expect.assert_eq(&actual)
513 db: &dyn DefDatabase,
514 dependency_imports: &ImportMap,
515 dependency: ItemInNs,
516 ) -> Option<String> {
517 let dependency_assoc_item_id = match dependency {
518 ItemInNs::Types(ModuleDefId::FunctionId(id))
519 | ItemInNs::Values(ModuleDefId::FunctionId(id)) => AssocItemId::from(id),
520 ItemInNs::Types(ModuleDefId::ConstId(id))
521 | ItemInNs::Values(ModuleDefId::ConstId(id)) => AssocItemId::from(id),
522 ItemInNs::Types(ModuleDefId::TypeAliasId(id))
523 | ItemInNs::Values(ModuleDefId::TypeAliasId(id)) => AssocItemId::from(id),
527 let trait_ = assoc_to_trait(db, dependency)?;
528 if let ModuleDefId::TraitId(tr) = trait_.as_module_def_id()? {
529 let trait_data = db.trait_data(tr);
530 let assoc_item_name =
531 trait_data.items.iter().find_map(|(assoc_item_name, assoc_item_id)| {
532 if &dependency_assoc_item_id == assoc_item_id {
533 Some(assoc_item_name)
538 return Some(format!("{}::{}", dependency_imports.path_of(trait_)?, assoc_item_name));
543 fn assoc_to_trait(db: &dyn DefDatabase, item: ItemInNs) -> Option<ItemInNs> {
544 let assoc: AssocItemId = match item {
545 ItemInNs::Types(it) | ItemInNs::Values(it) => match it {
546 ModuleDefId::TypeAliasId(it) => it.into(),
547 ModuleDefId::FunctionId(it) => it.into(),
548 ModuleDefId::ConstId(it) => it.into(),
554 let container = match assoc {
555 AssocItemId::FunctionId(it) => it.lookup(db).container,
556 AssocItemId::ConstId(it) => it.lookup(db).container,
557 AssocItemId::TypeAliasId(it) => it.lookup(db).container,
561 AssocContainerId::TraitId(it) => Some(ItemInNs::Types(it.into())),
566 fn check(ra_fixture: &str, expect: Expect) {
567 let db = TestDB::with_files(ra_fixture);
568 let crate_graph = db.crate_graph();
570 let actual = crate_graph
572 .filter_map(|krate| {
573 let cdata = &crate_graph[krate];
574 let name = cdata.display_name.as_ref()?;
576 let map = db.import_map(krate);
578 Some(format!("{}:\n{:?}\n", name, map))
580 .collect::<String>();
582 expect.assert_eq(&actual)
589 //- /main.rs crate:main deps:lib
593 pub struct InPrivateModule;
603 pub mod real_pu2 { // same path length as above
607 //- /lib.rs crate:lib
609 pub struct Pub2; // t + v
627 fn prefers_shortest_path() {
630 //- /main.rs crate:main
637 pub use super::sub::subsub::Def;
650 fn type_reexport_cross_crate() {
651 // Reexports need to be visible from a crate, even if the original crate exports the item
652 // at a shorter path.
655 //- /main.rs crate:main deps:lib
659 //- /lib.rs crate:lib
675 fn macro_reexport() {
678 //- /main.rs crate:main deps:lib
680 pub use lib::pub_macro;
682 //- /lib.rs crate:lib
684 macro_rules! pub_macro {
699 fn module_reexport() {
700 // Reexporting modules from a dependency adds all contents to the import map.
703 //- /main.rs crate:main deps:lib
704 pub use lib::module as reexported_module;
705 //- /lib.rs crate:lib
712 - reexported_module (t)
713 - reexported_module::S (t)
714 - reexported_module::S (v)
724 fn cyclic_module_reexport() {
725 // A cyclic reexport does not hang.
728 //- /lib.rs crate:lib
731 pub use super::sub::*;
735 pub use super::module;
752 //- /lib.rs crate:lib
753 macro_rules! private_macro {
768 //- /lib.rs crate:lib
769 pub struct Thing; // t + v
771 macro_rules! Thing { // m
785 //- /lib.rs crate:lib
786 pub mod Thing {} // t
788 macro_rules! Thing { // m
801 fn fuzzy_import_trait_and_assoc_items() {
802 cov_mark::check!(type_aliases_ignored);
804 //- /main.rs crate:main deps:dep
805 //- /dep.rs crate:dep
809 const FMT_CONST: bool;
811 fn format_function();
812 fn format_method(&self);
820 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
823 dep::fmt::Display::format_method (a)
824 dep::fmt::Display (t)
825 dep::fmt::Display::FMT_CONST (a)
826 dep::fmt::Display::format_function (a)
832 fn assoc_items_filtering() {
834 //- /main.rs crate:main deps:dep
835 //- /dep.rs crate:dep
839 const FMT_CONST: bool;
841 fn format_function();
842 fn format_method(&self);
850 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy).assoc_items_only(),
852 dep::fmt::Display::format_method (a)
853 dep::fmt::Display::FMT_CONST (a)
854 dep::fmt::Display::format_function (a)
861 Query::new("fmt".to_string())
862 .search_mode(SearchMode::Fuzzy)
863 .exclude_import_kind(ImportKind::AssociatedItem),
866 dep::fmt::Display (t)
873 Query::new("fmt".to_string())
874 .search_mode(SearchMode::Fuzzy)
876 .exclude_import_kind(ImportKind::AssociatedItem),
884 //- /main.rs crate:main deps:dep
885 //- /dep.rs crate:dep deps:tdep
886 use tdep::fmt as fmt_dep;
901 //- /tdep.rs crate:tdep
903 pub struct NotImportableFromMain;
910 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
915 dep::fmt::Display (t)
917 dep::fmt::Display::fmt (a)
925 Query::new("fmt".to_string()).search_mode(SearchMode::Equals),
930 dep::fmt::Display::fmt (a)
938 Query::new("fmt".to_string()).search_mode(SearchMode::Contains),
942 dep::fmt::Display (t)
944 dep::fmt::Display::fmt (a)
953 //- /main.rs crate:main deps:dep
954 //- /dep.rs crate:dep deps:tdep
955 use tdep::fmt as fmt_dep;
970 //- /tdep.rs crate:tdep
972 pub struct NotImportableFromMain;
979 Query::new("fmt".to_string()),
983 dep::fmt::Display (t)
985 dep::fmt::Display::fmt (a)
993 Query::new("fmt".to_string()).name_only(),
998 dep::fmt::Display::fmt (a)
1005 fn search_casing() {
1006 let ra_fixture = r#"
1007 //- /main.rs crate:main deps:dep
1008 //- /dep.rs crate:dep
1017 Query::new("FMT".to_string()),
1029 Query::new("FMT".to_string()).case_sensitive(),
1041 //- /main.rs crate:main deps:dep
1042 //- /dep.rs crate:dep
1058 Query::new("".to_string()).limit(2),
1069 fn search_exclusions() {
1070 let ra_fixture = r#"
1071 //- /main.rs crate:main deps:dep
1072 //- /dep.rs crate:dep
1081 Query::new("FMT".to_string()),
1093 Query::new("FMT".to_string()).exclude_import_kind(ImportKind::Adt),