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) => 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(_) => continue,
196 let assoc_item = if is_type_in_ns {
197 ItemInNs::Types(module_def_id)
199 ItemInNs::Values(module_def_id)
202 let mut assoc_item_info = original_import_info.to_owned();
203 assoc_item_info.path.segments.push(assoc_item_name.to_owned());
204 assoc_item_info.is_trait_assoc_item = true;
205 self.map.insert(assoc_item, assoc_item_info);
210 impl PartialEq for ImportMap {
211 fn eq(&self, other: &Self) -> bool {
212 // `fst` and `importables` are built from `map`, so we don't need to compare them.
213 self.map == other.map
217 impl Eq for ImportMap {}
219 impl fmt::Debug for ImportMap {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 let mut importable_paths: Vec<_> = self
224 .map(|(item, info)| {
225 let ns = match item {
226 ItemInNs::Types(_) => "t",
227 ItemInNs::Values(_) => "v",
228 ItemInNs::Macros(_) => "m",
230 format!("- {} ({})", info.path, ns)
234 importable_paths.sort();
235 f.write_str(&importable_paths.join("\n"))
239 fn fst_path(path: &ImportPath) -> String {
240 let mut s = path.to_string();
241 s.make_ascii_lowercase();
245 fn cmp((_, lhs): &(&ItemInNs, &ImportInfo), (_, rhs): &(&ItemInNs, &ImportInfo)) -> Ordering {
246 let lhs_str = fst_path(&lhs.path);
247 let rhs_str = fst_path(&rhs.path);
248 lhs_str.cmp(&rhs_str)
251 #[derive(Debug, Eq, PartialEq, Hash)]
252 pub enum ImportKind {
264 /// A way to match import map contents against the search query.
266 pub enum SearchMode {
267 /// Import map entry should strictly match the query string.
269 /// Import map entry should contain the query string.
271 /// Import map entry should contain all letters from the query string,
272 /// in the same order, but not necessary adjacent.
281 search_mode: SearchMode,
282 case_sensitive: bool,
284 exclude_import_kinds: FxHashSet<ImportKind>,
288 pub fn new(query: String) -> Self {
289 let lowercased = query.to_lowercase();
294 search_mode: SearchMode::Contains,
295 case_sensitive: false,
296 limit: usize::max_value(),
297 exclude_import_kinds: FxHashSet::default(),
301 /// Matches entries' names only, ignoring the rest of
303 /// Example: for `std::marker::PhantomData`, the name is `PhantomData`.
304 pub fn name_only(self) -> Self {
305 Self { name_only: true, ..self }
308 /// Specifies the way to search for the entries using the query.
309 pub fn search_mode(self, search_mode: SearchMode) -> Self {
310 Self { search_mode, ..self }
313 /// Limits the returned number of items to `limit`.
314 pub fn limit(self, limit: usize) -> Self {
315 Self { limit, ..self }
318 /// Respect casing of the query string when matching.
319 pub fn case_sensitive(self) -> Self {
320 Self { case_sensitive: true, ..self }
323 /// Do not include imports of the specified kind in the search results.
324 pub fn exclude_import_kind(mut self, import_kind: ImportKind) -> Self {
325 self.exclude_import_kinds.insert(import_kind);
330 fn import_matches_query(import: &ImportInfo, query: &Query, enforce_lowercase: bool) -> bool {
331 let mut input = if import.is_trait_assoc_item || query.name_only {
332 import.path.segments.last().unwrap().to_string()
334 import.path.to_string()
336 if enforce_lowercase || !query.case_sensitive {
337 input.make_ascii_lowercase();
341 if !enforce_lowercase && query.case_sensitive { &query.query } else { &query.lowercased };
343 match query.search_mode {
344 SearchMode::Equals => &input == query_string,
345 SearchMode::Contains => input.contains(query_string),
346 SearchMode::Fuzzy => {
347 let mut unchecked_query_chars = query_string.chars();
348 let mut mismatching_query_char = unchecked_query_chars.next();
350 for input_char in input.chars() {
351 match mismatching_query_char {
353 Some(matching_query_char) if matching_query_char == input_char => {
354 mismatching_query_char = unchecked_query_chars.next();
359 mismatching_query_char.is_none()
364 /// Searches dependencies of `krate` for an importable path matching `query`.
366 /// This returns a list of items that could be imported from dependencies of `krate`.
367 pub fn search_dependencies<'a>(
368 db: &'a dyn DefDatabase,
372 let _p = profile::span("search_dependencies").detail(|| format!("{:?}", query));
374 let graph = db.crate_graph();
375 let import_maps: Vec<_> =
376 graph[krate].dependencies.iter().map(|dep| db.import_map(dep.crate_id)).collect();
378 let automaton = fst::automaton::Subsequence::new(&query.lowercased);
380 let mut op = fst::map::OpBuilder::new();
381 for map in &import_maps {
382 op = op.add(map.fst.search(&automaton));
385 let mut stream = op.union();
386 let mut res = Vec::new();
387 while let Some((_, indexed_values)) = stream.next() {
388 for indexed_value in indexed_values {
389 let import_map = &import_maps[indexed_value.index];
390 let importables = &import_map.importables[indexed_value.value as usize..];
392 let common_importable_data = &import_map.map[&importables[0]];
393 if !import_matches_query(common_importable_data, &query, true) {
397 // Path shared by the importable items in this group.
398 let common_importables_path_fst = fst_path(&common_importable_data.path);
399 // Add the items from this `ModPath` group. Those are all subsequent items in
400 // `importables` whose paths match `path`.
401 let iter = importables
405 common_importables_path_fst == fst_path(&import_map.map[item].path)
407 .filter(|&item| match item_import_kind(item) {
408 Some(import_kind) => !query.exclude_import_kinds.contains(&import_kind),
412 !query.case_sensitive // we've already checked the common importables path case-insensitively
413 || import_matches_query(&import_map.map[item], &query, false)
417 if res.len() >= query.limit {
418 res.truncate(query.limit);
427 fn item_import_kind(item: ItemInNs) -> Option<ImportKind> {
428 Some(match item.as_module_def_id()? {
429 ModuleDefId::ModuleId(_) => ImportKind::Module,
430 ModuleDefId::FunctionId(_) => ImportKind::Function,
431 ModuleDefId::AdtId(_) => ImportKind::Adt,
432 ModuleDefId::EnumVariantId(_) => ImportKind::EnumVariant,
433 ModuleDefId::ConstId(_) => ImportKind::Const,
434 ModuleDefId::StaticId(_) => ImportKind::Static,
435 ModuleDefId::TraitId(_) => ImportKind::Trait,
436 ModuleDefId::TypeAliasId(_) => ImportKind::TypeAlias,
437 ModuleDefId::BuiltinType(_) => ImportKind::BuiltinType,
443 use base_db::{fixture::WithFixture, SourceDatabase, Upcast};
444 use expect_test::{expect, Expect};
446 use crate::{test_db::TestDB, AssocContainerId, Lookup};
450 fn check_search(ra_fixture: &str, crate_name: &str, query: Query, expect: Expect) {
451 let db = TestDB::with_files(ra_fixture);
452 let crate_graph = db.crate_graph();
453 let krate = crate_graph
456 crate_graph[*krate].display_name.as_ref().map(|n| n.to_string())
457 == Some(crate_name.to_string())
461 let actual = search_dependencies(db.upcast(), krate, query)
463 .filter_map(|dependency| {
464 let dependency_krate = dependency.krate(db.upcast())?;
465 let dependency_imports = db.import_map(dependency_krate);
467 let (path, mark) = match assoc_item_path(&db, &dependency_imports, dependency) {
468 Some(assoc_item_path) => (assoc_item_path, "a"),
470 dependency_imports.path_of(dependency)?.to_string(),
472 ItemInNs::Types(ModuleDefId::FunctionId(_))
473 | ItemInNs::Values(ModuleDefId::FunctionId(_)) => "f",
474 ItemInNs::Types(_) => "t",
475 ItemInNs::Values(_) => "v",
476 ItemInNs::Macros(_) => "m",
483 crate_graph[dependency_krate].display_name.as_ref()?,
488 .collect::<String>();
489 expect.assert_eq(&actual)
493 db: &dyn DefDatabase,
494 dependency_imports: &ImportMap,
495 dependency: ItemInNs,
496 ) -> Option<String> {
497 let dependency_assoc_item_id = match dependency {
498 ItemInNs::Types(ModuleDefId::FunctionId(id))
499 | ItemInNs::Values(ModuleDefId::FunctionId(id)) => AssocItemId::from(id),
500 ItemInNs::Types(ModuleDefId::ConstId(id))
501 | ItemInNs::Values(ModuleDefId::ConstId(id)) => AssocItemId::from(id),
502 ItemInNs::Types(ModuleDefId::TypeAliasId(id))
503 | ItemInNs::Values(ModuleDefId::TypeAliasId(id)) => AssocItemId::from(id),
507 let trait_ = assoc_to_trait(db, dependency)?;
508 if let ModuleDefId::TraitId(tr) = trait_.as_module_def_id()? {
509 let trait_data = db.trait_data(tr);
510 let assoc_item_name =
511 trait_data.items.iter().find_map(|(assoc_item_name, assoc_item_id)| {
512 if &dependency_assoc_item_id == assoc_item_id {
513 Some(assoc_item_name)
518 return Some(format!("{}::{}", dependency_imports.path_of(trait_)?, assoc_item_name));
523 fn assoc_to_trait(db: &dyn DefDatabase, item: ItemInNs) -> Option<ItemInNs> {
524 let assoc: AssocItemId = match item {
525 ItemInNs::Types(it) | ItemInNs::Values(it) => match it {
526 ModuleDefId::TypeAliasId(it) => it.into(),
527 ModuleDefId::FunctionId(it) => it.into(),
528 ModuleDefId::ConstId(it) => it.into(),
534 let container = match assoc {
535 AssocItemId::FunctionId(it) => it.lookup(db).container,
536 AssocItemId::ConstId(it) => it.lookup(db).container,
537 AssocItemId::TypeAliasId(it) => it.lookup(db).container,
541 AssocContainerId::TraitId(it) => Some(ItemInNs::Types(it.into())),
546 fn check(ra_fixture: &str, expect: Expect) {
547 let db = TestDB::with_files(ra_fixture);
548 let crate_graph = db.crate_graph();
550 let actual = crate_graph
552 .filter_map(|krate| {
553 let cdata = &crate_graph[krate];
554 let name = cdata.display_name.as_ref()?;
556 let map = db.import_map(krate);
558 Some(format!("{}:\n{:?}\n", name, map))
560 .collect::<String>();
562 expect.assert_eq(&actual)
569 //- /main.rs crate:main deps:lib
573 pub struct InPrivateModule;
583 pub mod real_pu2 { // same path length as above
587 //- /lib.rs crate:lib
589 pub struct Pub2; // t + v
607 fn prefers_shortest_path() {
610 //- /main.rs crate:main
617 pub use super::sub::subsub::Def;
630 fn type_reexport_cross_crate() {
631 // Reexports need to be visible from a crate, even if the original crate exports the item
632 // at a shorter path.
635 //- /main.rs crate:main deps:lib
639 //- /lib.rs crate:lib
655 fn macro_reexport() {
658 //- /main.rs crate:main deps:lib
660 pub use lib::pub_macro;
662 //- /lib.rs crate:lib
664 macro_rules! pub_macro {
679 fn module_reexport() {
680 // Reexporting modules from a dependency adds all contents to the import map.
683 //- /main.rs crate:main deps:lib
684 pub use lib::module as reexported_module;
685 //- /lib.rs crate:lib
692 - reexported_module (t)
693 - reexported_module::S (t)
694 - reexported_module::S (v)
704 fn cyclic_module_reexport() {
705 // A cyclic reexport does not hang.
708 //- /lib.rs crate:lib
711 pub use super::sub::*;
715 pub use super::module;
732 //- /lib.rs crate:lib
733 macro_rules! private_macro {
748 //- /lib.rs crate:lib
749 pub struct Thing; // t + v
751 macro_rules! Thing { // m
765 //- /lib.rs crate:lib
766 pub mod Thing {} // t
768 macro_rules! Thing { // m
781 fn fuzzy_import_trait_and_assoc_items() {
783 //- /main.rs crate:main deps:dep
784 //- /dep.rs crate:dep
788 const FMT_CONST: bool;
790 fn format_function();
791 fn format_method(&self);
799 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
802 dep::fmt::Display (t)
803 dep::fmt::Display::FMT_CONST (a)
804 dep::fmt::Display::format_function (a)
805 dep::fmt::Display::format_method (a)
813 //- /main.rs crate:main deps:dep
814 //- /dep.rs crate:dep deps:tdep
815 use tdep::fmt as fmt_dep;
830 //- /tdep.rs crate:tdep
832 pub struct NotImportableFromMain;
839 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
845 dep::fmt::Display (t)
846 dep::fmt::Display::fmt (a)
854 Query::new("fmt".to_string()).search_mode(SearchMode::Equals),
860 dep::fmt::Display::fmt (a)
867 Query::new("fmt".to_string()).search_mode(SearchMode::Contains),
873 dep::fmt::Display (t)
874 dep::fmt::Display::fmt (a)
882 //- /main.rs crate:main deps:dep
883 //- /dep.rs crate:dep deps:tdep
884 use tdep::fmt as fmt_dep;
899 //- /tdep.rs crate:tdep
901 pub struct NotImportableFromMain;
908 Query::new("fmt".to_string()),
914 dep::fmt::Display (t)
915 dep::fmt::Display::fmt (a)
922 Query::new("fmt".to_string()).name_only(),
928 dep::fmt::Display::fmt (a)
936 //- /main.rs crate:main deps:dep
937 //- /dep.rs crate:dep
946 Query::new("FMT".to_string()),
958 Query::new("FMT".to_string()).case_sensitive(),
970 //- /main.rs crate:main deps:dep
971 //- /dep.rs crate:dep
987 Query::new("".to_string()).limit(2),
996 fn search_exclusions() {
998 //- /main.rs crate:main deps:dep
999 //- /dep.rs crate:dep
1008 Query::new("FMT".to_string()),
1020 Query::new("FMT".to_string()).exclude_import_kind(ImportKind::Adt),