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