ide_db/
symbol_index.rs

1//! This module handles fuzzy-searching of functions, structs and other symbols
2//! by name across the whole workspace and dependencies.
3//!
4//! It works by building an incrementally-updated text-search index of all
5//! symbols. The backbone of the index is the **awesome** `fst` crate by
6//! @BurntSushi.
7//!
8//! In a nutshell, you give a set of strings to `fst`, and it builds a
9//! finite state machine describing this set of strings. The strings which
10//! could fuzzy-match a pattern can also be described by a finite state machine.
11//! What is freaking cool is that you can now traverse both state machines in
12//! lock-step to enumerate the strings which are both in the input set and
13//! fuzz-match the query. Or, more formally, given two languages described by
14//! FSTs, one can build a product FST which describes the intersection of the
15//! languages.
16//!
17//! `fst` does not support cheap updating of the index, but it supports unioning
18//! of state machines. So, to account for changing source code, we build an FST
19//! for each library (which is assumed to never change) and an FST for each Rust
20//! file in the current workspace, and run a query against the union of all
21//! those FSTs.
22
23use std::{
24    cmp::Ordering,
25    fmt,
26    hash::{Hash, Hasher},
27    ops::ControlFlow,
28};
29
30use base_db::{RootQueryDb, SourceRootId};
31use fst::{Automaton, Streamer, raw::IndexedValue};
32use hir::{
33    Crate, Module,
34    db::HirDatabase,
35    import_map::{AssocSearchMode, SearchMode},
36    symbols::{FileSymbol, SymbolCollector},
37};
38use rayon::prelude::*;
39use rustc_hash::FxHashSet;
40
41use crate::RootDatabase;
42
43#[derive(Debug, Clone)]
44pub struct Query {
45    query: String,
46    lowercased: String,
47    mode: SearchMode,
48    assoc_mode: AssocSearchMode,
49    case_sensitive: bool,
50    only_types: bool,
51    libs: bool,
52    exclude_imports: bool,
53}
54
55impl Query {
56    pub fn new(query: String) -> Query {
57        let lowercased = query.to_lowercase();
58        Query {
59            query,
60            lowercased,
61            only_types: false,
62            libs: false,
63            mode: SearchMode::Fuzzy,
64            assoc_mode: AssocSearchMode::Include,
65            case_sensitive: false,
66            exclude_imports: false,
67        }
68    }
69
70    pub fn only_types(&mut self) {
71        self.only_types = true;
72    }
73
74    pub fn libs(&mut self) {
75        self.libs = true;
76    }
77
78    pub fn fuzzy(&mut self) {
79        self.mode = SearchMode::Fuzzy;
80    }
81
82    pub fn exact(&mut self) {
83        self.mode = SearchMode::Exact;
84    }
85
86    pub fn prefix(&mut self) {
87        self.mode = SearchMode::Prefix;
88    }
89
90    /// Specifies whether we want to include associated items in the result.
91    pub fn assoc_search_mode(&mut self, assoc_mode: AssocSearchMode) {
92        self.assoc_mode = assoc_mode;
93    }
94
95    pub fn case_sensitive(&mut self) {
96        self.case_sensitive = true;
97    }
98
99    pub fn exclude_imports(&mut self) {
100        self.exclude_imports = true;
101    }
102}
103
104/// The set of roots for crates.io libraries.
105/// Files in libraries are assumed to never change.
106#[salsa::input(singleton, debug)]
107pub struct LibraryRoots {
108    #[returns(ref)]
109    pub roots: FxHashSet<SourceRootId>,
110}
111
112/// The set of "local" (that is, from the current workspace) roots.
113/// Files in local roots are assumed to change frequently.
114#[salsa::input(singleton, debug)]
115pub struct LocalRoots {
116    #[returns(ref)]
117    pub roots: FxHashSet<SourceRootId>,
118}
119
120/// The symbol indices of modules that make up a given crate.
121pub fn crate_symbols(db: &dyn HirDatabase, krate: Crate) -> Box<[&SymbolIndex]> {
122    let _p = tracing::info_span!("crate_symbols").entered();
123    krate.modules(db).into_iter().map(|module| SymbolIndex::module_symbols(db, module)).collect()
124}
125
126// Feature: Workspace Symbol
127//
128// Uses fuzzy-search to find types, modules and functions by name across your
129// project and dependencies. This is **the** most useful feature, which improves code
130// navigation tremendously. It mostly works on top of the built-in LSP
131// functionality, however `#` and `*` symbols can be used to narrow down the
132// search. Specifically,
133//
134// - `Foo` searches for `Foo` type in the current workspace
135// - `foo#` searches for `foo` function in the current workspace
136// - `Foo*` searches for `Foo` type among dependencies, including `stdlib`
137// - `foo#*` searches for `foo` function among dependencies
138//
139// That is, `#` switches from "types" to all symbols, `*` switches from the current
140// workspace to dependencies.
141//
142// Note that filtering does not currently work in VSCode due to the editor never
143// sending the special symbols to the language server. Instead, you can configure
144// the filtering via the `rust-analyzer.workspace.symbol.search.scope` and
145// `rust-analyzer.workspace.symbol.search.kind` settings. Symbols prefixed
146// with `__` are hidden from the search results unless configured otherwise.
147//
148// | Editor  | Shortcut |
149// |---------|-----------|
150// | VS Code | <kbd>Ctrl+T</kbd>
151pub fn world_symbols(db: &RootDatabase, query: Query) -> Vec<FileSymbol> {
152    let _p = tracing::info_span!("world_symbols", query = ?query.query).entered();
153
154    let indices: Vec<_> = if query.libs {
155        LibraryRoots::get(db)
156            .roots(db)
157            .par_iter()
158            .for_each_with(db.clone(), |snap, &root| _ = SymbolIndex::library_symbols(snap, root));
159        LibraryRoots::get(db)
160            .roots(db)
161            .iter()
162            .map(|&root| SymbolIndex::library_symbols(db, root))
163            .collect()
164    } else {
165        let mut crates = Vec::new();
166
167        for &root in LocalRoots::get(db).roots(db).iter() {
168            crates.extend(db.source_root_crates(root).iter().copied())
169        }
170        crates
171            .par_iter()
172            .for_each_with(db.clone(), |snap, &krate| _ = crate_symbols(snap, krate.into()));
173        let indices: Vec<_> =
174            crates.into_iter().map(|krate| crate_symbols(db, krate.into())).collect();
175        indices.iter().flat_map(|indices| indices.iter().cloned()).collect()
176    };
177
178    let mut res = vec![];
179    query.search::<()>(&indices, |f| {
180        res.push(f.clone());
181        ControlFlow::Continue(())
182    });
183    res
184}
185
186#[derive(Default)]
187pub struct SymbolIndex {
188    symbols: Box<[FileSymbol]>,
189    map: fst::Map<Vec<u8>>,
190}
191
192impl SymbolIndex {
193    /// The symbol index for a given source root within library_roots.
194    pub fn library_symbols(db: &dyn HirDatabase, source_root_id: SourceRootId) -> &SymbolIndex {
195        // FIXME:
196        #[salsa::interned]
197        struct InternedSourceRootId {
198            id: SourceRootId,
199        }
200        #[salsa::tracked(returns(ref))]
201        fn library_symbols(
202            db: &dyn HirDatabase,
203            source_root_id: InternedSourceRootId<'_>,
204        ) -> SymbolIndex {
205            let _p = tracing::info_span!("library_symbols").entered();
206
207            // We call this without attaching because this runs in parallel, so we need to attach here.
208            hir::attach_db(db, || {
209                let mut symbol_collector = SymbolCollector::new(db, true);
210
211                db.source_root_crates(source_root_id.id(db))
212                    .iter()
213                    .flat_map(|&krate| Crate::from(krate).modules(db))
214                    // we specifically avoid calling other SymbolsDatabase queries here, even though they do the same thing,
215                    // as the index for a library is not going to really ever change, and we do not want to store
216                    // the module or crate indices for those in salsa unless we need to.
217                    .for_each(|module| symbol_collector.collect(module));
218
219                SymbolIndex::new(symbol_collector.finish())
220            })
221        }
222        library_symbols(db, InternedSourceRootId::new(db, source_root_id))
223    }
224
225    /// The symbol index for a given module. These modules should only be in source roots that
226    /// are inside local_roots.
227    pub fn module_symbols(db: &dyn HirDatabase, module: Module) -> &SymbolIndex {
228        // FIXME:
229        #[salsa::interned]
230        struct InternedModuleId {
231            id: hir::ModuleId,
232        }
233
234        #[salsa::tracked(returns(ref))]
235        fn module_symbols(db: &dyn HirDatabase, module: InternedModuleId<'_>) -> SymbolIndex {
236            let _p = tracing::info_span!("module_symbols").entered();
237
238            // We call this without attaching because this runs in parallel, so we need to attach here.
239            hir::attach_db(db, || {
240                let module: Module = module.id(db).into();
241                SymbolIndex::new(SymbolCollector::new_module(
242                    db,
243                    module,
244                    !module.krate().origin(db).is_local(),
245                ))
246            })
247        }
248
249        module_symbols(db, InternedModuleId::new(db, hir::ModuleId::from(module)))
250    }
251}
252
253impl fmt::Debug for SymbolIndex {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        f.debug_struct("SymbolIndex").field("n_symbols", &self.symbols.len()).finish()
256    }
257}
258
259impl PartialEq for SymbolIndex {
260    fn eq(&self, other: &SymbolIndex) -> bool {
261        self.symbols == other.symbols
262    }
263}
264
265impl Eq for SymbolIndex {}
266
267impl Hash for SymbolIndex {
268    fn hash<H: Hasher>(&self, hasher: &mut H) {
269        self.symbols.hash(hasher)
270    }
271}
272
273impl SymbolIndex {
274    fn new(mut symbols: Box<[FileSymbol]>) -> SymbolIndex {
275        fn cmp(lhs: &FileSymbol, rhs: &FileSymbol) -> Ordering {
276            let lhs_chars = lhs.name.as_str().chars().map(|c| c.to_ascii_lowercase());
277            let rhs_chars = rhs.name.as_str().chars().map(|c| c.to_ascii_lowercase());
278            lhs_chars.cmp(rhs_chars)
279        }
280
281        symbols.par_sort_by(cmp);
282
283        let mut builder = fst::MapBuilder::memory();
284
285        let mut last_batch_start = 0;
286
287        for idx in 0..symbols.len() {
288            if let Some(next_symbol) = symbols.get(idx + 1)
289                && cmp(&symbols[last_batch_start], next_symbol) == Ordering::Equal
290            {
291                continue;
292            }
293
294            let start = last_batch_start;
295            let end = idx + 1;
296            last_batch_start = end;
297
298            let key = symbols[start].name.as_str().to_ascii_lowercase();
299            let value = SymbolIndex::range_to_map_value(start, end);
300
301            builder.insert(key, value).unwrap();
302        }
303
304        let map = builder
305            .into_inner()
306            .and_then(|mut buf| {
307                fst::Map::new({
308                    buf.shrink_to_fit();
309                    buf
310                })
311            })
312            .unwrap();
313        SymbolIndex { symbols, map }
314    }
315
316    pub fn len(&self) -> usize {
317        self.symbols.len()
318    }
319
320    pub fn memory_size(&self) -> usize {
321        self.map.as_fst().size() + self.symbols.len() * size_of::<FileSymbol>()
322    }
323
324    fn range_to_map_value(start: usize, end: usize) -> u64 {
325        debug_assert![start <= (u32::MAX as usize)];
326        debug_assert![end <= (u32::MAX as usize)];
327
328        ((start as u64) << 32) | end as u64
329    }
330
331    fn map_value_to_range(value: u64) -> (usize, usize) {
332        let end = value as u32 as usize;
333        let start = (value >> 32) as usize;
334        (start, end)
335    }
336}
337
338impl Query {
339    pub(crate) fn search<'sym, T>(
340        self,
341        indices: &'sym [&SymbolIndex],
342        cb: impl FnMut(&'sym FileSymbol) -> ControlFlow<T>,
343    ) -> Option<T> {
344        let _p = tracing::info_span!("symbol_index::Query::search").entered();
345        let mut op = fst::map::OpBuilder::new();
346        match self.mode {
347            SearchMode::Exact => {
348                let automaton = fst::automaton::Str::new(&self.lowercased);
349
350                for index in indices.iter() {
351                    op = op.add(index.map.search(&automaton));
352                }
353                self.search_maps(indices, op.union(), cb)
354            }
355            SearchMode::Fuzzy => {
356                let automaton = fst::automaton::Subsequence::new(&self.lowercased);
357
358                for index in indices.iter() {
359                    op = op.add(index.map.search(&automaton));
360                }
361                self.search_maps(indices, op.union(), cb)
362            }
363            SearchMode::Prefix => {
364                let automaton = fst::automaton::Str::new(&self.lowercased).starts_with();
365
366                for index in indices.iter() {
367                    op = op.add(index.map.search(&automaton));
368                }
369                self.search_maps(indices, op.union(), cb)
370            }
371        }
372    }
373
374    fn search_maps<'sym, T>(
375        &self,
376        indices: &'sym [&SymbolIndex],
377        mut stream: fst::map::Union<'_>,
378        mut cb: impl FnMut(&'sym FileSymbol) -> ControlFlow<T>,
379    ) -> Option<T> {
380        let ignore_underscore_prefixed = !self.query.starts_with("__");
381        while let Some((_, indexed_values)) = stream.next() {
382            for &IndexedValue { index, value } in indexed_values {
383                let symbol_index = &indices[index];
384                let (start, end) = SymbolIndex::map_value_to_range(value);
385
386                for symbol in &symbol_index.symbols[start..end] {
387                    let non_type_for_type_only_query = self.only_types
388                        && !matches!(
389                            symbol.def,
390                            hir::ModuleDef::Adt(..)
391                                | hir::ModuleDef::TypeAlias(..)
392                                | hir::ModuleDef::BuiltinType(..)
393                                | hir::ModuleDef::Trait(..)
394                        );
395                    if non_type_for_type_only_query || !self.matches_assoc_mode(symbol.is_assoc) {
396                        continue;
397                    }
398                    // Hide symbols that start with `__` unless the query starts with `__`
399                    let symbol_name = symbol.name.as_str();
400                    if ignore_underscore_prefixed && symbol_name.starts_with("__") {
401                        continue;
402                    }
403                    if self.exclude_imports && symbol.is_import {
404                        continue;
405                    }
406                    if self.mode.check(&self.query, self.case_sensitive, symbol_name)
407                        && let Some(b) = cb(symbol).break_value()
408                    {
409                        return Some(b);
410                    }
411                }
412            }
413        }
414        None
415    }
416
417    fn matches_assoc_mode(&self, is_trait_assoc_item: bool) -> bool {
418        !matches!(
419            (is_trait_assoc_item, self.assoc_mode),
420            (true, AssocSearchMode::Exclude) | (false, AssocSearchMode::AssocItemsOnly)
421        )
422    }
423}
424
425#[cfg(test)]
426mod tests {
427
428    use expect_test::expect_file;
429    use salsa::Setter;
430    use test_fixture::{WORKSPACE, WithFixture};
431
432    use super::*;
433
434    #[test]
435    fn test_symbol_index_collection() {
436        let (db, _) = RootDatabase::with_many_files(
437            r#"
438//- /main.rs
439
440macro_rules! macro_rules_macro {
441    () => {}
442};
443
444macro_rules! define_struct {
445    () => {
446        struct StructFromMacro;
447    }
448};
449
450define_struct!();
451
452macro Macro { }
453
454struct Struct;
455enum Enum {
456    A, B
457}
458union Union {}
459
460impl Struct {
461    fn impl_fn() {}
462}
463
464struct StructT<T>;
465
466impl <T> StructT<T> {
467    fn generic_impl_fn() {}
468}
469
470trait Trait {
471    fn trait_fn(&self);
472}
473
474fn main() {
475    struct StructInFn;
476}
477
478const CONST: u32 = 1;
479static STATIC: &'static str = "2";
480type Alias = Struct;
481
482mod a_mod {
483    struct StructInModA;
484}
485
486const _: () = {
487    struct StructInUnnamedConst;
488
489    ()
490};
491
492const CONST_WITH_INNER: () = {
493    struct StructInNamedConst;
494
495    ()
496};
497
498mod b_mod;
499
500
501use define_struct as really_define_struct;
502use Macro as ItemLikeMacro;
503use Macro as Trait; // overlay namespaces
504//- /b_mod.rs
505struct StructInModB;
506pub(self) use super::Macro as SuperItemLikeMacro;
507pub(self) use crate::b_mod::StructInModB as ThisStruct;
508pub(self) use crate::Trait as IsThisJustATrait;
509"#,
510        );
511
512        let symbols: Vec<_> = Crate::from(db.test_crate())
513            .modules(&db)
514            .into_iter()
515            .map(|module_id| {
516                let mut symbols = SymbolCollector::new_module(&db, module_id, false);
517                symbols.sort_by_key(|it| it.name.as_str().to_owned());
518                (module_id, symbols)
519            })
520            .collect();
521
522        expect_file!["./test_data/test_symbol_index_collection.txt"].assert_debug_eq(&symbols);
523    }
524
525    #[test]
526    fn test_doc_alias() {
527        let (db, _) = RootDatabase::with_single_file(
528            r#"
529#[doc(alias="s1")]
530#[doc(alias="s2")]
531#[doc(alias("mul1","mul2"))]
532struct Struct;
533
534#[doc(alias="s1")]
535struct Duplicate;
536        "#,
537        );
538
539        let symbols: Vec<_> = Crate::from(db.test_crate())
540            .modules(&db)
541            .into_iter()
542            .map(|module_id| {
543                let mut symbols = SymbolCollector::new_module(&db, module_id, false);
544                symbols.sort_by_key(|it| it.name.as_str().to_owned());
545                (module_id, symbols)
546            })
547            .collect();
548
549        expect_file!["./test_data/test_doc_alias.txt"].assert_debug_eq(&symbols);
550    }
551
552    #[test]
553    fn test_exclude_imports() {
554        let (mut db, _) = RootDatabase::with_many_files(
555            r#"
556//- /lib.rs
557mod foo;
558pub use foo::Foo;
559
560//- /foo.rs
561pub struct Foo;
562"#,
563        );
564
565        let mut local_roots = FxHashSet::default();
566        local_roots.insert(WORKSPACE);
567        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
568
569        let mut query = Query::new("Foo".to_owned());
570        let mut symbols = world_symbols(&db, query.clone());
571        symbols.sort_by_key(|x| x.is_import);
572        expect_file!["./test_data/test_symbols_with_imports.txt"].assert_debug_eq(&symbols);
573
574        query.exclude_imports();
575        let symbols = world_symbols(&db, query);
576        expect_file!["./test_data/test_symbols_exclude_imports.txt"].assert_debug_eq(&symbols);
577    }
578}