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::{FxHashMap, FxHashSet, FxHasher};
11 use smallvec::SmallVec;
15 db::DefDatabase, item_scope::ItemInNs, visibility::Visibility, AssocItemId, ModuleDefId,
19 type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<FxHasher>>;
21 /// Item import details stored in the `ImportMap`.
22 #[derive(Debug, Clone, Eq, PartialEq)]
23 pub struct ImportInfo {
24 /// A path that can be used to import the item, relative to the crate's root.
26 /// The module containing this item.
27 pub container: ModuleId,
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>>,
68 /// Maps names of associated items to the item's ID. Only includes items whose defining trait is
70 assoc_map: FxHashMap<SmolStr, SmallVec<[AssocItemId; 1]>>,
74 pub fn import_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<Self> {
75 let _p = profile::span("import_map_query");
76 let def_map = db.crate_def_map(krate);
77 let mut import_map = Self::default();
79 // We look only into modules that are public(ly reexported), starting with the crate root.
80 let empty = ImportPath { segments: vec![] };
81 let root = ModuleId { krate, local_id: def_map.root };
82 let mut worklist = vec![(root, empty)];
83 while let Some((module, mod_path)) = worklist.pop() {
85 let mod_data = if module.krate == krate {
86 &def_map[module.local_id]
88 // The crate might reexport a module defined in another crate.
89 ext_def_map = db.crate_def_map(module.krate);
90 &ext_def_map[module.local_id]
93 let visible_items = mod_data.scope.entries().filter_map(|(name, per_ns)| {
94 let per_ns = per_ns.filter_visibility(|vis| vis == Visibility::Public);
102 for (name, per_ns) in visible_items {
104 let mut path = mod_path.clone();
105 path.segments.push(name.clone());
109 for item in per_ns.iter_items() {
110 let path = mk_path();
111 match import_map.map.entry(item) {
112 Entry::Vacant(entry) => {
113 entry.insert(ImportInfo { path, container: module });
115 Entry::Occupied(mut entry) => {
116 // If the new path is shorter, prefer that one.
117 if path.len() < entry.get().path.len() {
118 *entry.get_mut() = ImportInfo { path, container: module };
125 // If we've just added a path to a module, descend into it. We might traverse
126 // modules multiple times, but only if the new path to it is shorter than the
127 // first (else we `continue` above).
128 if let Some(ModuleDefId::ModuleId(mod_id)) = item.as_module_def_id() {
129 worklist.push((mod_id, mk_path()));
132 // If we've added a path to a trait, add the trait's methods to the method map.
133 if let Some(ModuleDefId::TraitId(tr)) = item.as_module_def_id() {
134 import_map.collect_trait_methods(db, tr);
140 let mut importables = import_map.map.iter().collect::<Vec<_>>();
142 importables.sort_by(cmp);
144 // Build the FST, taking care not to insert duplicate values.
146 let mut builder = fst::MapBuilder::memory();
147 let mut last_batch_start = 0;
149 for idx in 0..importables.len() {
150 if let Some(next_item) = importables.get(idx + 1) {
151 if cmp(&importables[last_batch_start], next_item) == Ordering::Equal {
156 let start = last_batch_start;
157 last_batch_start = idx + 1;
159 let key = fst_string(&importables[start].1.path);
160 builder.insert(key, start as u64).unwrap();
163 import_map.fst = fst::Map::new(builder.into_inner().unwrap()).unwrap();
164 import_map.importables = importables.iter().map(|(item, _)| **item).collect();
169 /// Returns the `ModPath` needed to import/mention `item`, relative to this crate's root.
170 pub fn path_of(&self, item: ItemInNs) -> Option<&ImportPath> {
171 self.import_info_for(item).map(|it| &it.path)
174 pub fn import_info_for(&self, item: ItemInNs) -> Option<&ImportInfo> {
178 fn collect_trait_methods(&mut self, db: &dyn DefDatabase, tr: TraitId) {
179 let data = db.trait_data(tr);
180 for (name, item) in data.items.iter() {
181 self.assoc_map.entry(name.to_string().into()).or_default().push(*item);
186 impl PartialEq for ImportMap {
187 fn eq(&self, other: &Self) -> bool {
188 // `fst` and `importables` are built from `map`, so we don't need to compare them.
189 self.map == other.map
193 impl Eq for ImportMap {}
195 impl fmt::Debug for ImportMap {
196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197 let mut importable_paths: Vec<_> = self
200 .map(|(item, info)| {
201 let ns = match item {
202 ItemInNs::Types(_) => "t",
203 ItemInNs::Values(_) => "v",
204 ItemInNs::Macros(_) => "m",
206 format!("- {} ({})", info.path, ns)
210 importable_paths.sort();
211 f.write_str(&importable_paths.join("\n"))
215 fn fst_string<T: ToString>(t: &T) -> String {
216 let mut s = t.to_string();
217 s.make_ascii_lowercase();
221 fn cmp((_, lhs): &(&ItemInNs, &ImportInfo), (_, rhs): &(&ItemInNs, &ImportInfo)) -> Ordering {
222 let lhs_str = fst_string(&lhs.path);
223 let rhs_str = fst_string(&rhs.path);
224 lhs_str.cmp(&rhs_str)
227 #[derive(Debug, Eq, PartialEq, Hash)]
228 pub enum ImportKind {
244 // TODO kb use enums instead?
247 strict_include: bool,
248 case_sensitive: bool,
250 exclude_import_kinds: FxHashSet<ImportKind>,
254 pub fn new(query: &str) -> Self {
256 lowercased: query.to_lowercase(),
257 query: query.to_string(),
260 strict_include: false,
261 case_sensitive: false,
262 limit: usize::max_value(),
263 exclude_import_kinds: FxHashSet::default(),
267 pub fn name_end(self) -> Self {
268 Self { name_end: true, ..self }
272 pub fn name_only(self) -> Self {
273 Self { name_only: true, ..self }
277 pub fn strict_include(self) -> Self {
278 Self { strict_include: true, ..self }
281 /// Limits the returned number of items to `limit`.
282 pub fn limit(self, limit: usize) -> Self {
283 Self { limit, ..self }
286 /// Respect casing of the query string when matching.
287 pub fn case_sensitive(self) -> Self {
288 Self { case_sensitive: true, ..self }
291 /// Do not include imports of the specified kind in the search results.
292 pub fn exclude_import_kind(mut self, import_kind: ImportKind) -> Self {
293 self.exclude_import_kinds.insert(import_kind);
298 // TODO kb: ugly with a special `return true` case and the `enforce_lowercase` one.
299 fn contains_query(query: &Query, input_path: &ImportPath, enforce_lowercase: bool) -> bool {
300 let mut input = if query.name_only {
301 input_path.segments.last().unwrap().to_string()
303 input_path.to_string()
305 if enforce_lowercase || !query.case_sensitive {
306 input.make_ascii_lowercase();
310 if !enforce_lowercase && query.case_sensitive { &query.query } else { &query.lowercased };
312 if query.strict_include {
314 &input == query_string
316 input.contains(query_string)
318 } else if query.name_end {
319 input.ends_with(query_string)
321 let input_chars = input.chars().collect::<FxHashSet<_>>();
322 // TODO kb actually check for the order and the quantity
323 query_string.chars().all(|query_char| input_chars.contains(&query_char))
327 /// Searches dependencies of `krate` for an importable path matching `query`.
329 /// This returns a list of items that could be imported from dependencies of `krate`.
330 pub fn search_dependencies<'a>(
331 db: &'a dyn DefDatabase,
335 let _p = profile::span("search_dependencies").detail(|| format!("{:?}", query));
337 let graph = db.crate_graph();
338 let import_maps: Vec<_> =
339 graph[krate].dependencies.iter().map(|dep| db.import_map(dep.crate_id)).collect();
341 let automaton = fst::automaton::Subsequence::new(&query.lowercased);
343 let mut op = fst::map::OpBuilder::new();
344 for map in &import_maps {
345 op = op.add(map.fst.search(&automaton));
348 let mut stream = op.union();
349 let mut res = Vec::new();
350 while let Some((_, indexed_values)) = stream.next() {
351 for indexed_value in indexed_values {
352 let import_map = &import_maps[indexed_value.index];
353 let importables = &import_map.importables[indexed_value.value as usize..];
355 // Path shared by the importable items in this group.
356 let common_importables_path = &import_map.map[&importables[0]].path;
357 if !contains_query(&query, common_importables_path, true) {
361 let common_importables_path_fst = fst_string(common_importables_path);
362 // Add the items from this `ModPath` group. Those are all subsequent items in
363 // `importables` whose paths match `path`.
364 let iter = importables
368 common_importables_path_fst == fst_string(&import_map.map[item].path)
370 .filter(|&item| match item_import_kind(item) {
371 Some(import_kind) => !query.exclude_import_kinds.contains(&import_kind),
374 .filter(|item| contains_query(&query, &import_map.map[item].path, false));
377 if res.len() >= query.limit {
378 res.truncate(query.limit);
384 // Add all exported associated items whose names match the query (exactly).
385 for map in &import_maps {
386 if let Some(v) = map.assoc_map.get(&*query.query) {
387 res.extend(v.iter().map(|&assoc| {
388 ItemInNs::Types(match assoc {
389 AssocItemId::FunctionId(it) => it.into(),
390 AssocItemId::ConstId(it) => it.into(),
391 AssocItemId::TypeAliasId(it) => it.into(),
400 fn item_import_kind(item: ItemInNs) -> Option<ImportKind> {
401 Some(match item.as_module_def_id()? {
402 ModuleDefId::ModuleId(_) => ImportKind::Module,
403 ModuleDefId::FunctionId(_) => ImportKind::Function,
404 ModuleDefId::AdtId(_) => ImportKind::Adt,
405 ModuleDefId::EnumVariantId(_) => ImportKind::EnumVariant,
406 ModuleDefId::ConstId(_) => ImportKind::Const,
407 ModuleDefId::StaticId(_) => ImportKind::Static,
408 ModuleDefId::TraitId(_) => ImportKind::Trait,
409 ModuleDefId::TypeAliasId(_) => ImportKind::TypeAlias,
410 ModuleDefId::BuiltinType(_) => ImportKind::BuiltinType,
416 use base_db::{fixture::WithFixture, SourceDatabase, Upcast};
417 use expect_test::{expect, Expect};
419 use crate::{test_db::TestDB, AssocContainerId, Lookup};
423 fn check_search(ra_fixture: &str, crate_name: &str, query: Query, expect: Expect) {
424 let db = TestDB::with_files(ra_fixture);
425 let crate_graph = db.crate_graph();
426 let krate = crate_graph
429 crate_graph[*krate].display_name.as_ref().map(|n| n.to_string())
430 == Some(crate_name.to_string())
434 let actual = search_dependencies(db.upcast(), krate, query)
437 let mark = match item {
438 ItemInNs::Types(_) => "t",
439 ItemInNs::Values(_) => "v",
440 ItemInNs::Macros(_) => "m",
442 let item = assoc_to_trait(&db, item);
443 item.krate(db.upcast()).map(|krate| {
444 let map = db.import_map(krate);
445 let path = map.path_of(item).unwrap();
448 crate_graph[krate].display_name.as_ref().unwrap(),
454 .collect::<String>();
455 expect.assert_eq(&actual)
458 fn assoc_to_trait(db: &dyn DefDatabase, item: ItemInNs) -> ItemInNs {
459 let assoc: AssocItemId = match item {
460 ItemInNs::Types(it) | ItemInNs::Values(it) => match it {
461 ModuleDefId::TypeAliasId(it) => it.into(),
462 ModuleDefId::FunctionId(it) => it.into(),
463 ModuleDefId::ConstId(it) => it.into(),
469 let container = match assoc {
470 AssocItemId::FunctionId(it) => it.lookup(db).container,
471 AssocItemId::ConstId(it) => it.lookup(db).container,
472 AssocItemId::TypeAliasId(it) => it.lookup(db).container,
476 AssocContainerId::TraitId(it) => ItemInNs::Types(it.into()),
481 fn check(ra_fixture: &str, expect: Expect) {
482 let db = TestDB::with_files(ra_fixture);
483 let crate_graph = db.crate_graph();
485 let actual = crate_graph
487 .filter_map(|krate| {
488 let cdata = &crate_graph[krate];
489 let name = cdata.display_name.as_ref()?;
491 let map = db.import_map(krate);
493 Some(format!("{}:\n{:?}\n", name, map))
495 .collect::<String>();
497 expect.assert_eq(&actual)
504 //- /main.rs crate:main deps:lib
508 pub struct InPrivateModule;
518 pub mod real_pu2 { // same path length as above
522 //- /lib.rs crate:lib
524 pub struct Pub2; // t + v
542 fn prefers_shortest_path() {
545 //- /main.rs crate:main
552 pub use super::sub::subsub::Def;
565 fn type_reexport_cross_crate() {
566 // Reexports need to be visible from a crate, even if the original crate exports the item
567 // at a shorter path.
570 //- /main.rs crate:main deps:lib
574 //- /lib.rs crate:lib
590 fn macro_reexport() {
593 //- /main.rs crate:main deps:lib
595 pub use lib::pub_macro;
597 //- /lib.rs crate:lib
599 macro_rules! pub_macro {
614 fn module_reexport() {
615 // Reexporting modules from a dependency adds all contents to the import map.
618 //- /main.rs crate:main deps:lib
619 pub use lib::module as reexported_module;
620 //- /lib.rs crate:lib
627 - reexported_module (t)
628 - reexported_module::S (t)
629 - reexported_module::S (v)
639 fn cyclic_module_reexport() {
640 // A cyclic reexport does not hang.
643 //- /lib.rs crate:lib
646 pub use super::sub::*;
650 pub use super::module;
667 //- /lib.rs crate:lib
668 macro_rules! private_macro {
683 //- /lib.rs crate:lib
684 pub struct Thing; // t + v
686 macro_rules! Thing { // m
700 //- /lib.rs crate:lib
701 pub mod Thing {} // t
703 macro_rules! Thing { // m
718 //- /main.rs crate:main deps:dep
719 //- /dep.rs crate:dep deps:tdep
720 use tdep::fmt as fmt_dep;
735 //- /tdep.rs crate:tdep
737 pub struct NotImportableFromMain;
750 dep::fmt::Display (t)
752 dep::fmt::Display (t)
759 Query::new("fmt").name_only().strict_include(),
765 dep::fmt::Display (t)
773 //- /main.rs crate:main deps:dep
774 //- /dep.rs crate:dep
795 Query::new("FMT").case_sensitive(),
807 //- /main.rs crate:main deps:dep
808 //- /dep.rs crate:dep
824 Query::new("").limit(2),
833 fn search_exclusions() {
835 //- /main.rs crate:main deps:dep
836 //- /dep.rs crate:dep
857 Query::new("FMT").exclude_import_kind(ImportKind::Adt),