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