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 = db.crate_def_map(module.krate);
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 {
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 search_mode: SearchMode,
286 case_sensitive: bool,
288 exclude_import_kinds: FxHashSet<ImportKind>,
292 pub fn new(query: String) -> Self {
293 let lowercased = query.to_lowercase();
298 search_mode: SearchMode::Contains,
299 case_sensitive: false,
300 limit: usize::max_value(),
301 exclude_import_kinds: FxHashSet::default(),
305 /// Matches entries' names only, ignoring the rest of
307 /// Example: for `std::marker::PhantomData`, the name is `PhantomData`.
308 pub fn name_only(self) -> Self {
309 Self { name_only: true, ..self }
312 /// Specifies the way to search for the entries using the query.
313 pub fn search_mode(self, search_mode: SearchMode) -> Self {
314 Self { search_mode, ..self }
317 /// Limits the returned number of items to `limit`.
318 pub fn limit(self, limit: usize) -> Self {
319 Self { limit, ..self }
322 /// Respect casing of the query string when matching.
323 pub fn case_sensitive(self) -> Self {
324 Self { case_sensitive: true, ..self }
327 /// Do not include imports of the specified kind in the search results.
328 pub fn exclude_import_kind(mut self, import_kind: ImportKind) -> Self {
329 self.exclude_import_kinds.insert(import_kind);
333 fn import_matches(&self, import: &ImportInfo, enforce_lowercase: bool) -> bool {
334 let mut input = if import.is_trait_assoc_item || self.name_only {
335 import.path.segments.last().unwrap().to_string()
337 import.path.to_string()
339 if enforce_lowercase || !self.case_sensitive {
340 input.make_ascii_lowercase();
344 if !enforce_lowercase && self.case_sensitive { &self.query } else { &self.lowercased };
346 match self.search_mode {
347 SearchMode::Equals => &input == query_string,
348 SearchMode::Contains => input.contains(query_string),
349 SearchMode::Fuzzy => {
350 let mut unchecked_query_chars = query_string.chars();
351 let mut mismatching_query_char = unchecked_query_chars.next();
353 for input_char in input.chars() {
354 match mismatching_query_char {
356 Some(matching_query_char) if matching_query_char == input_char => {
357 mismatching_query_char = unchecked_query_chars.next();
362 mismatching_query_char.is_none()
368 /// Searches dependencies of `krate` for an importable path matching `query`.
370 /// This returns a list of items that could be imported from dependencies of `krate`.
371 pub fn search_dependencies<'a>(
372 db: &'a dyn DefDatabase,
376 let _p = profile::span("search_dependencies").detail(|| format!("{:?}", query));
378 let graph = db.crate_graph();
379 let import_maps: Vec<_> =
380 graph[krate].dependencies.iter().map(|dep| db.import_map(dep.crate_id)).collect();
382 let automaton = fst::automaton::Subsequence::new(&query.lowercased);
384 let mut op = fst::map::OpBuilder::new();
385 for map in &import_maps {
386 op = op.add(map.fst.search(&automaton));
389 let mut stream = op.union();
390 let mut res = Vec::new();
391 while let Some((_, indexed_values)) = stream.next() {
392 for indexed_value in indexed_values {
393 let import_map = &import_maps[indexed_value.index];
394 let importables = &import_map.importables[indexed_value.value as usize..];
396 let common_importable_data = &import_map.map[&importables[0]];
397 if !query.import_matches(common_importable_data, true) {
401 // Path shared by the importable items in this group.
402 let common_importables_path_fst = fst_path(&common_importable_data.path);
403 // Add the items from this `ModPath` group. Those are all subsequent items in
404 // `importables` whose paths match `path`.
405 let iter = importables
409 common_importables_path_fst == fst_path(&import_map.map[item].path)
411 .filter(|&item| match item_import_kind(item) {
412 Some(import_kind) => !query.exclude_import_kinds.contains(&import_kind),
416 !query.case_sensitive // we've already checked the common importables path case-insensitively
417 || query.import_matches(&import_map.map[item], false)
421 if res.len() >= query.limit {
422 res.truncate(query.limit);
431 fn item_import_kind(item: ItemInNs) -> Option<ImportKind> {
432 Some(match item.as_module_def_id()? {
433 ModuleDefId::ModuleId(_) => ImportKind::Module,
434 ModuleDefId::FunctionId(_) => ImportKind::Function,
435 ModuleDefId::AdtId(_) => ImportKind::Adt,
436 ModuleDefId::EnumVariantId(_) => ImportKind::EnumVariant,
437 ModuleDefId::ConstId(_) => ImportKind::Const,
438 ModuleDefId::StaticId(_) => ImportKind::Static,
439 ModuleDefId::TraitId(_) => ImportKind::Trait,
440 ModuleDefId::TypeAliasId(_) => ImportKind::TypeAlias,
441 ModuleDefId::BuiltinType(_) => ImportKind::BuiltinType,
447 use base_db::{fixture::WithFixture, SourceDatabase, Upcast};
448 use expect_test::{expect, Expect};
449 use test_utils::mark;
451 use crate::{test_db::TestDB, AssocContainerId, Lookup};
455 fn check_search(ra_fixture: &str, crate_name: &str, query: Query, expect: Expect) {
456 let db = TestDB::with_files(ra_fixture);
457 let crate_graph = db.crate_graph();
458 let krate = crate_graph
461 crate_graph[*krate].display_name.as_ref().map(|n| n.to_string())
462 == Some(crate_name.to_string())
466 let actual = search_dependencies(db.upcast(), krate, query)
468 .filter_map(|dependency| {
469 let dependency_krate = dependency.krate(db.upcast())?;
470 let dependency_imports = db.import_map(dependency_krate);
472 let (path, mark) = match assoc_item_path(&db, &dependency_imports, dependency) {
473 Some(assoc_item_path) => (assoc_item_path, "a"),
475 dependency_imports.path_of(dependency)?.to_string(),
477 ItemInNs::Types(ModuleDefId::FunctionId(_))
478 | ItemInNs::Values(ModuleDefId::FunctionId(_)) => "f",
479 ItemInNs::Types(_) => "t",
480 ItemInNs::Values(_) => "v",
481 ItemInNs::Macros(_) => "m",
488 crate_graph[dependency_krate].display_name.as_ref()?,
493 .collect::<String>();
494 expect.assert_eq(&actual)
498 db: &dyn DefDatabase,
499 dependency_imports: &ImportMap,
500 dependency: ItemInNs,
501 ) -> Option<String> {
502 let dependency_assoc_item_id = match dependency {
503 ItemInNs::Types(ModuleDefId::FunctionId(id))
504 | ItemInNs::Values(ModuleDefId::FunctionId(id)) => AssocItemId::from(id),
505 ItemInNs::Types(ModuleDefId::ConstId(id))
506 | ItemInNs::Values(ModuleDefId::ConstId(id)) => AssocItemId::from(id),
507 ItemInNs::Types(ModuleDefId::TypeAliasId(id))
508 | ItemInNs::Values(ModuleDefId::TypeAliasId(id)) => AssocItemId::from(id),
512 let trait_ = assoc_to_trait(db, dependency)?;
513 if let ModuleDefId::TraitId(tr) = trait_.as_module_def_id()? {
514 let trait_data = db.trait_data(tr);
515 let assoc_item_name =
516 trait_data.items.iter().find_map(|(assoc_item_name, assoc_item_id)| {
517 if &dependency_assoc_item_id == assoc_item_id {
518 Some(assoc_item_name)
523 return Some(format!("{}::{}", dependency_imports.path_of(trait_)?, assoc_item_name));
528 fn assoc_to_trait(db: &dyn DefDatabase, item: ItemInNs) -> Option<ItemInNs> {
529 let assoc: AssocItemId = match item {
530 ItemInNs::Types(it) | ItemInNs::Values(it) => match it {
531 ModuleDefId::TypeAliasId(it) => it.into(),
532 ModuleDefId::FunctionId(it) => it.into(),
533 ModuleDefId::ConstId(it) => it.into(),
539 let container = match assoc {
540 AssocItemId::FunctionId(it) => it.lookup(db).container,
541 AssocItemId::ConstId(it) => it.lookup(db).container,
542 AssocItemId::TypeAliasId(it) => it.lookup(db).container,
546 AssocContainerId::TraitId(it) => Some(ItemInNs::Types(it.into())),
551 fn check(ra_fixture: &str, expect: Expect) {
552 let db = TestDB::with_files(ra_fixture);
553 let crate_graph = db.crate_graph();
555 let actual = crate_graph
557 .filter_map(|krate| {
558 let cdata = &crate_graph[krate];
559 let name = cdata.display_name.as_ref()?;
561 let map = db.import_map(krate);
563 Some(format!("{}:\n{:?}\n", name, map))
565 .collect::<String>();
567 expect.assert_eq(&actual)
574 //- /main.rs crate:main deps:lib
578 pub struct InPrivateModule;
588 pub mod real_pu2 { // same path length as above
592 //- /lib.rs crate:lib
594 pub struct Pub2; // t + v
612 fn prefers_shortest_path() {
615 //- /main.rs crate:main
622 pub use super::sub::subsub::Def;
635 fn type_reexport_cross_crate() {
636 // Reexports need to be visible from a crate, even if the original crate exports the item
637 // at a shorter path.
640 //- /main.rs crate:main deps:lib
644 //- /lib.rs crate:lib
660 fn macro_reexport() {
663 //- /main.rs crate:main deps:lib
665 pub use lib::pub_macro;
667 //- /lib.rs crate:lib
669 macro_rules! pub_macro {
684 fn module_reexport() {
685 // Reexporting modules from a dependency adds all contents to the import map.
688 //- /main.rs crate:main deps:lib
689 pub use lib::module as reexported_module;
690 //- /lib.rs crate:lib
697 - reexported_module (t)
698 - reexported_module::S (t)
699 - reexported_module::S (v)
709 fn cyclic_module_reexport() {
710 // A cyclic reexport does not hang.
713 //- /lib.rs crate:lib
716 pub use super::sub::*;
720 pub use super::module;
737 //- /lib.rs crate:lib
738 macro_rules! private_macro {
753 //- /lib.rs crate:lib
754 pub struct Thing; // t + v
756 macro_rules! Thing { // m
770 //- /lib.rs crate:lib
771 pub mod Thing {} // t
773 macro_rules! Thing { // m
786 fn fuzzy_import_trait_and_assoc_items() {
787 mark::check!(type_aliases_ignored);
789 //- /main.rs crate:main deps:dep
790 //- /dep.rs crate:dep
794 const FMT_CONST: bool;
796 fn format_function();
797 fn format_method(&self);
805 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
808 dep::fmt::Display (t)
809 dep::fmt::Display::FMT_CONST (a)
810 dep::fmt::Display::format_function (a)
811 dep::fmt::Display::format_method (a)
819 //- /main.rs crate:main deps:dep
820 //- /dep.rs crate:dep deps:tdep
821 use tdep::fmt as fmt_dep;
836 //- /tdep.rs crate:tdep
838 pub struct NotImportableFromMain;
845 Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
851 dep::fmt::Display (t)
852 dep::fmt::Display::fmt (a)
860 Query::new("fmt".to_string()).search_mode(SearchMode::Equals),
866 dep::fmt::Display::fmt (a)
873 Query::new("fmt".to_string()).search_mode(SearchMode::Contains),
879 dep::fmt::Display (t)
880 dep::fmt::Display::fmt (a)
888 //- /main.rs crate:main deps:dep
889 //- /dep.rs crate:dep deps:tdep
890 use tdep::fmt as fmt_dep;
905 //- /tdep.rs crate:tdep
907 pub struct NotImportableFromMain;
914 Query::new("fmt".to_string()),
920 dep::fmt::Display (t)
921 dep::fmt::Display::fmt (a)
928 Query::new("fmt".to_string()).name_only(),
934 dep::fmt::Display::fmt (a)
942 //- /main.rs crate:main deps:dep
943 //- /dep.rs crate:dep
952 Query::new("FMT".to_string()),
964 Query::new("FMT".to_string()).case_sensitive(),
976 //- /main.rs crate:main deps:dep
977 //- /dep.rs crate:dep
993 Query::new("".to_string()).limit(2),
1002 fn search_exclusions() {
1003 let ra_fixture = r#"
1004 //- /main.rs crate:main deps:dep
1005 //- /dep.rs crate:dep
1014 Query::new("FMT".to_string()),
1026 Query::new("FMT".to_string()).exclude_import_kind(ImportKind::Adt),