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::{LibraryRoots, LocalRoots, 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 salsa::Update;
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 symbol indices of modules that make up a given crate.
105pub fn crate_symbols(db: &dyn HirDatabase, krate: Crate) -> Box<[&SymbolIndex<'_>]> {
106    let _p = tracing::info_span!("crate_symbols").entered();
107    krate.modules(db).into_iter().map(|module| SymbolIndex::module_symbols(db, module)).collect()
108}
109
110// Feature: Workspace Symbol
111//
112// Uses fuzzy-search to find types, modules and functions by name across your
113// project and dependencies. This is **the** most useful feature, which improves code
114// navigation tremendously. It mostly works on top of the built-in LSP
115// functionality, however `#` and `*` symbols can be used to narrow down the
116// search. Specifically,
117//
118// - `Foo` searches for `Foo` type in the current workspace
119// - `foo#` searches for `foo` function in the current workspace
120// - `Foo*` searches for `Foo` type among dependencies, including `stdlib`
121// - `foo#*` searches for `foo` function among dependencies
122//
123// That is, `#` switches from "types" to all symbols, `*` switches from the current
124// workspace to dependencies.
125//
126// Note that filtering does not currently work in VSCode due to the editor never
127// sending the special symbols to the language server. Instead, you can configure
128// the filtering via the `rust-analyzer.workspace.symbol.search.scope` and
129// `rust-analyzer.workspace.symbol.search.kind` settings. Symbols prefixed
130// with `__` are hidden from the search results unless configured otherwise.
131//
132// | Editor  | Shortcut |
133// |---------|-----------|
134// | VS Code | <kbd>Ctrl+T</kbd>
135pub fn world_symbols(db: &RootDatabase, query: Query) -> Vec<FileSymbol<'_>> {
136    let _p = tracing::info_span!("world_symbols", query = ?query.query).entered();
137
138    let indices: Vec<_> = if query.libs {
139        LibraryRoots::get(db)
140            .roots(db)
141            .par_iter()
142            .for_each_with(db.clone(), |snap, &root| _ = SymbolIndex::library_symbols(snap, root));
143        LibraryRoots::get(db)
144            .roots(db)
145            .iter()
146            .map(|&root| SymbolIndex::library_symbols(db, root))
147            .collect()
148    } else {
149        let mut crates = Vec::new();
150
151        for &root in LocalRoots::get(db).roots(db).iter() {
152            crates.extend(db.source_root_crates(root).iter().copied())
153        }
154        crates
155            .par_iter()
156            .for_each_with(db.clone(), |snap, &krate| _ = crate_symbols(snap, krate.into()));
157        crates.into_iter().flat_map(|krate| Vec::from(crate_symbols(db, krate.into()))).collect()
158    };
159
160    let mut res = vec![];
161    query.search::<()>(&indices, |f| {
162        res.push(f.clone());
163        ControlFlow::Continue(())
164    });
165    res
166}
167
168#[derive(Default)]
169pub struct SymbolIndex<'db> {
170    symbols: Box<[FileSymbol<'db>]>,
171    map: fst::Map<Vec<u8>>,
172}
173
174impl<'db> SymbolIndex<'db> {
175    /// The symbol index for a given source root within library_roots.
176    pub fn library_symbols(
177        db: &'db dyn HirDatabase,
178        source_root_id: SourceRootId,
179    ) -> &'db SymbolIndex<'db> {
180        // FIXME:
181        #[salsa::interned]
182        struct InternedSourceRootId {
183            id: SourceRootId,
184        }
185        #[salsa::tracked(returns(ref))]
186        fn library_symbols<'db>(
187            db: &'db dyn HirDatabase,
188            source_root_id: InternedSourceRootId<'db>,
189        ) -> SymbolIndex<'db> {
190            let _p = tracing::info_span!("library_symbols").entered();
191
192            // We call this without attaching because this runs in parallel, so we need to attach here.
193            hir::attach_db(db, || {
194                let mut symbol_collector = SymbolCollector::new(db, true);
195
196                db.source_root_crates(source_root_id.id(db))
197                    .iter()
198                    .flat_map(|&krate| Crate::from(krate).modules(db))
199                    // we specifically avoid calling other SymbolsDatabase queries here, even though they do the same thing,
200                    // as the index for a library is not going to really ever change, and we do not want to store
201                    // the module or crate indices for those in salsa unless we need to.
202                    .for_each(|module| symbol_collector.collect(module));
203
204                SymbolIndex::new(symbol_collector.finish())
205            })
206        }
207        library_symbols(db, InternedSourceRootId::new(db, source_root_id))
208    }
209
210    /// The symbol index for a given module. These modules should only be in source roots that
211    /// are inside local_roots.
212    pub fn module_symbols(db: &dyn HirDatabase, module: Module) -> &SymbolIndex<'_> {
213        // FIXME:
214        #[salsa::interned]
215        struct InternedModuleId {
216            id: hir::ModuleId,
217        }
218
219        #[salsa::tracked(returns(ref))]
220        fn module_symbols<'db>(
221            db: &'db dyn HirDatabase,
222            module: InternedModuleId<'db>,
223        ) -> SymbolIndex<'db> {
224            let _p = tracing::info_span!("module_symbols").entered();
225
226            // We call this without attaching because this runs in parallel, so we need to attach here.
227            hir::attach_db(db, || {
228                let module: Module = module.id(db).into();
229                SymbolIndex::new(SymbolCollector::new_module(
230                    db,
231                    module,
232                    !module.krate(db).origin(db).is_local(),
233                ))
234            })
235        }
236
237        module_symbols(db, InternedModuleId::new(db, hir::ModuleId::from(module)))
238    }
239}
240
241impl fmt::Debug for SymbolIndex<'_> {
242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243        f.debug_struct("SymbolIndex").field("n_symbols", &self.symbols.len()).finish()
244    }
245}
246
247impl PartialEq for SymbolIndex<'_> {
248    fn eq(&self, other: &SymbolIndex<'_>) -> bool {
249        self.symbols == other.symbols
250    }
251}
252
253impl Eq for SymbolIndex<'_> {}
254
255impl Hash for SymbolIndex<'_> {
256    fn hash<H: Hasher>(&self, hasher: &mut H) {
257        self.symbols.hash(hasher)
258    }
259}
260
261unsafe impl Update for SymbolIndex<'_> {
262    unsafe fn maybe_update(old_pointer: *mut Self, new_value: Self) -> bool {
263        let this = unsafe { &mut *old_pointer };
264        if *this == new_value {
265            false
266        } else {
267            *this = new_value;
268            true
269        }
270    }
271}
272
273impl<'db> SymbolIndex<'db> {
274    fn new(mut symbols: Box<[FileSymbol<'db>]>) -> SymbolIndex<'db> {
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<'db, T>(
340        self,
341        indices: &[&'db SymbolIndex<'db>],
342        cb: impl FnMut(&'db FileSymbol<'db>) -> 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<'db, T>(
375        &self,
376        indices: &[&'db SymbolIndex<'db>],
377        mut stream: fst::map::Union<'_>,
378        mut cb: impl FnMut(&'db FileSymbol<'db>) -> 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 rustc_hash::FxHashSet;
430    use salsa::Setter;
431    use test_fixture::{WORKSPACE, WithFixture};
432
433    use super::*;
434
435    #[test]
436    fn test_symbol_index_collection() {
437        let (db, _) = RootDatabase::with_many_files(
438            r#"
439//- /main.rs
440
441macro_rules! macro_rules_macro {
442    () => {}
443};
444
445macro_rules! define_struct {
446    () => {
447        struct StructFromMacro;
448    }
449};
450
451define_struct!();
452
453macro Macro { }
454
455struct Struct;
456enum Enum {
457    A, B
458}
459union Union {}
460
461impl Struct {
462    fn impl_fn() {}
463}
464
465struct StructT<T>;
466
467impl <T> StructT<T> {
468    fn generic_impl_fn() {}
469}
470
471trait Trait {
472    fn trait_fn(&self);
473}
474
475fn main() {
476    struct StructInFn;
477}
478
479const CONST: u32 = 1;
480static STATIC: &'static str = "2";
481type Alias = Struct;
482
483mod a_mod {
484    struct StructInModA;
485}
486
487const _: () = {
488    struct StructInUnnamedConst;
489
490    ()
491};
492
493const CONST_WITH_INNER: () = {
494    struct StructInNamedConst;
495
496    ()
497};
498
499mod b_mod;
500
501
502use define_struct as really_define_struct;
503use Macro as ItemLikeMacro;
504use Macro as Trait; // overlay namespaces
505//- /b_mod.rs
506struct StructInModB;
507pub(self) use super::Macro as SuperItemLikeMacro;
508pub(self) use crate::b_mod::StructInModB as ThisStruct;
509pub(self) use crate::Trait as IsThisJustATrait;
510"#,
511        );
512
513        let symbols: Vec<_> = Crate::from(db.test_crate())
514            .modules(&db)
515            .into_iter()
516            .map(|module_id| {
517                let mut symbols = SymbolCollector::new_module(&db, module_id, false);
518                symbols.sort_by_key(|it| it.name.as_str().to_owned());
519                (module_id, symbols)
520            })
521            .collect();
522
523        expect_file!["./test_data/test_symbol_index_collection.txt"].assert_debug_eq(&symbols);
524    }
525
526    #[test]
527    fn test_doc_alias() {
528        let (db, _) = RootDatabase::with_single_file(
529            r#"
530#[doc(alias="s1")]
531#[doc(alias="s2")]
532#[doc(alias("mul1","mul2"))]
533struct Struct;
534
535#[doc(alias="s1")]
536struct Duplicate;
537        "#,
538        );
539
540        let symbols: Vec<_> = Crate::from(db.test_crate())
541            .modules(&db)
542            .into_iter()
543            .map(|module_id| {
544                let mut symbols = SymbolCollector::new_module(&db, module_id, false);
545                symbols.sort_by_key(|it| it.name.as_str().to_owned());
546                (module_id, symbols)
547            })
548            .collect();
549
550        expect_file!["./test_data/test_doc_alias.txt"].assert_debug_eq(&symbols);
551    }
552
553    #[test]
554    fn test_exclude_imports() {
555        let (mut db, _) = RootDatabase::with_many_files(
556            r#"
557//- /lib.rs
558mod foo;
559pub use foo::Foo;
560
561//- /foo.rs
562pub struct Foo;
563"#,
564        );
565
566        let mut local_roots = FxHashSet::default();
567        local_roots.insert(WORKSPACE);
568        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
569
570        let mut query = Query::new("Foo".to_owned());
571        let mut symbols = world_symbols(&db, query.clone());
572        symbols.sort_by_key(|x| x.is_import);
573        expect_file!["./test_data/test_symbols_with_imports.txt"].assert_debug_eq(&symbols);
574
575        query.exclude_imports();
576        let symbols = world_symbols(&db, query);
577        expect_file!["./test_data/test_symbols_exclude_imports.txt"].assert_debug_eq(&symbols);
578    }
579}