Skip to main content

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::{
31    CrateOrigin, InternedSourceRootId, LangCrateOrigin, LibraryRoots, LocalRoots, SourceRootId,
32    salsa::Update, source_root_crates,
33};
34use fst::{Automaton, Streamer, raw::IndexedValue};
35use hir::{
36    Crate, Module,
37    db::HirDatabase,
38    import_map::{AssocSearchMode, SearchMode},
39    symbols::{FileSymbol, SymbolCollector},
40};
41use itertools::Itertools;
42use rayon::prelude::*;
43
44use crate::RootDatabase;
45
46/// A query for searching symbols in the workspace or dependencies.
47///
48/// This struct configures how symbol search is performed, including the search text,
49/// matching strategy, and filtering options. It is used by [`world_symbols`] to find
50/// symbols across the codebase.
51///
52/// # Example
53/// ```ignore
54/// let mut query = Query::new("MyStruct".to_string());
55/// query.only_types();  // Only search for type definitions
56/// query.libs();        // Include library dependencies
57/// query.exact();       // Use exact matching instead of fuzzy
58/// ```
59#[derive(Debug, Clone)]
60pub struct Query {
61    /// The item name to search for (last segment of the path, or full query if no path).
62    /// When empty with a non-empty `path_filter`, returns all items in that module.
63    query: String,
64    /// Lowercase version of [`Self::query`], pre-computed for efficiency.
65    /// Used to build FST automata for case-insensitive index lookups.
66    lowercased: String,
67    /// Path segments to filter by (all segments except the last).
68    /// Empty if no `::` in the original query.
69    path_filter: Vec<String>,
70    /// If true, the first path segment must be a crate name (query started with `::`).
71    anchor_to_crate: bool,
72    /// The search strategy to use when matching symbols.
73    /// - [`SearchMode::Exact`]: Symbol name must exactly match the query.
74    /// - [`SearchMode::Fuzzy`]: Symbol name must contain all query characters in order (subsequence match).
75    /// - [`SearchMode::Prefix`]: Symbol name must start with the query string.
76    ///
77    /// Defaults to [`SearchMode::Fuzzy`].
78    mode: SearchMode,
79    /// Controls filtering of trait-associated items (methods, constants, types).
80    /// - [`AssocSearchMode::Include`]: Include both associated and non-associated items.
81    /// - [`AssocSearchMode::Exclude`]: Exclude trait-associated items from results.
82    /// - [`AssocSearchMode::AssocItemsOnly`]: Only return trait-associated items.
83    ///
84    /// Defaults to [`AssocSearchMode::Include`].
85    assoc_mode: AssocSearchMode,
86    /// Whether the final symbol name comparison should be case-sensitive.
87    /// When `false`, matching is case-insensitive (e.g., "foo" matches "Foo").
88    ///
89    /// Defaults to `false`.
90    case_sensitive: bool,
91    /// When `true`, only return type definitions: structs, enums, unions,
92    /// type aliases, built-in types, and traits. Functions, constants, statics,
93    /// and modules are excluded.
94    ///
95    /// Defaults to `false`.
96    only_types: bool,
97    /// When `true`, search library dependency roots instead of local workspace crates.
98    /// This enables finding symbols in external dependencies including the standard library.
99    ///
100    /// Defaults to `false` (search local workspace only).
101    libs: bool,
102    /// When `true`, exclude re-exported/imported symbols from results,
103    /// showing only the original definitions.
104    ///
105    /// Defaults to `false`.
106    exclude_imports: bool,
107}
108
109impl Query {
110    pub fn new(query: String) -> Query {
111        let (path_filter, item_query, anchor_to_crate) = Self::parse_path_query(&query);
112        let lowercased = item_query.to_lowercase();
113        Query {
114            query: item_query,
115            lowercased,
116            path_filter,
117            anchor_to_crate,
118            only_types: false,
119            libs: false,
120            mode: SearchMode::Fuzzy,
121            assoc_mode: AssocSearchMode::Include,
122            case_sensitive: false,
123            exclude_imports: false,
124        }
125    }
126
127    /// Parse a query string that may contain path segments.
128    ///
129    /// Returns (path_filter, item_query, anchor_to_crate) where:
130    /// - `path_filter`: Path segments to match (all but the last segment)
131    /// - `item_query`: The item name to search for (last segment)
132    /// - `anchor_to_crate`: Whether the first segment must be a crate name
133    fn parse_path_query(query: &str) -> (Vec<String>, String, bool) {
134        // Check for leading :: (absolute path / crate search)
135        let (query, anchor_to_crate) = match query.strip_prefix("::") {
136            Some(q) => (q, true),
137            None => (query, false),
138        };
139
140        let Some((prefix, query)) = query.rsplit_once("::") else {
141            return (vec![], query.to_owned(), anchor_to_crate);
142        };
143
144        let prefix: Vec<_> =
145            prefix.split("::").filter(|s| !s.is_empty()).map(ToOwned::to_owned).collect();
146
147        (prefix, query.to_owned(), anchor_to_crate)
148    }
149
150    /// Returns true if this query is searching for crates
151    /// (i.e., the query was "::" alone or "::foo" for fuzzy crate search)
152    fn is_crate_search(&self) -> bool {
153        self.anchor_to_crate && self.path_filter.is_empty()
154    }
155
156    pub fn only_types(&mut self) {
157        self.only_types = true;
158    }
159
160    pub fn libs(&mut self) {
161        self.libs = true;
162    }
163
164    pub fn fuzzy(&mut self) {
165        self.mode = SearchMode::Fuzzy;
166    }
167
168    pub fn exact(&mut self) {
169        self.mode = SearchMode::Exact;
170    }
171
172    pub fn prefix(&mut self) {
173        self.mode = SearchMode::Prefix;
174    }
175
176    /// Specifies whether we want to include associated items in the result.
177    pub fn assoc_search_mode(&mut self, assoc_mode: AssocSearchMode) {
178        self.assoc_mode = assoc_mode;
179    }
180
181    pub fn case_sensitive(&mut self) {
182        self.case_sensitive = true;
183    }
184
185    pub fn exclude_imports(&mut self) {
186        self.exclude_imports = true;
187    }
188}
189
190/// The symbol indices of modules that make up a given crate.
191pub fn crate_symbols(db: &dyn HirDatabase, krate: Crate) -> Box<[&SymbolIndex<'_>]> {
192    let _p = tracing::info_span!("crate_symbols").entered();
193    krate.modules(db).into_iter().map(|module| SymbolIndex::module_symbols(db, module)).collect()
194}
195
196// Feature: Workspace Symbol
197//
198// Uses fuzzy-search to find types, modules and functions by name across your
199// project and dependencies. This is **the** most useful feature, which improves code
200// navigation tremendously. It mostly works on top of the built-in LSP
201// functionality, however `#` and `*` symbols can be used to narrow down the
202// search. Specifically,
203//
204// - `Foo` searches for `Foo` type in the current workspace
205// - `foo#` searches for `foo` function in the current workspace
206// - `Foo*` searches for `Foo` type among dependencies, including `stdlib`
207// - `foo#*` searches for `foo` function among dependencies
208//
209// That is, `#` switches from "types" to all symbols, `*` switches from the current
210// workspace to dependencies.
211//
212// This also supports general Rust path syntax with the usual rules.
213//
214// Note that paths do not currently work in VSCode due to the editor never
215// sending the special symbols to the language server. Some other editors might not support the # or
216// * search either, instead, you can configure the filtering via the
217// `rust-analyzer.workspace.symbol.search.scope` and `rust-analyzer.workspace.symbol.search.kind`
218// settings. Symbols prefixed with `__` are hidden from the search results unless configured
219// otherwise.
220//
221// | Editor  | Shortcut |
222// |---------|-----------|
223// | VS Code | <kbd>Ctrl+T</kbd>
224pub fn world_symbols(db: &RootDatabase, mut query: Query) -> Vec<FileSymbol<'_>> {
225    let _p = tracing::info_span!("world_symbols", query = ?query.query).entered();
226
227    // Search for crates by name (handles "::" and "::foo" queries)
228    let indices: Vec<_> = if query.is_crate_search() {
229        query.only_types = false;
230        vec![SymbolIndex::extern_prelude_symbols(db)]
231        // If we have a path filter, resolve it to target modules
232    } else if !query.path_filter.is_empty() {
233        query.only_types = false;
234        let target_modules = resolve_path_to_modules(
235            db,
236            &query.path_filter,
237            query.anchor_to_crate,
238            query.case_sensitive,
239        );
240
241        if target_modules.is_empty() {
242            return vec![];
243        }
244
245        target_modules.iter().map(|&module| SymbolIndex::module_symbols(db, module)).collect()
246    } else if query.libs {
247        LibraryRoots::get(db)
248            .roots(db)
249            .par_iter()
250            .for_each_with(db.clone(), |snap, &root| _ = SymbolIndex::library_symbols(snap, root));
251        LibraryRoots::get(db)
252            .roots(db)
253            .iter()
254            .map(|&root| SymbolIndex::library_symbols(db, root))
255            .collect()
256    } else {
257        let mut crates = Vec::new();
258
259        for &root in LocalRoots::get(db).roots(db).iter() {
260            crates.extend(source_root_crates(db, root).iter().copied())
261        }
262        crates
263            .par_iter()
264            .for_each_with(db.clone(), |snap, &krate| _ = crate_symbols(snap, krate.into()));
265        crates
266            .into_iter()
267            .flat_map(|krate| Vec::from(crate_symbols(db, krate.into())))
268            .chain(std::iter::once(SymbolIndex::extern_prelude_symbols(db)))
269            .collect()
270    };
271
272    let mut res = vec![];
273
274    // Normal search: use FST to match item name
275    query.search::<()>(db, &indices, |f| {
276        res.push(f.clone());
277        ControlFlow::Continue(())
278    });
279
280    res
281}
282
283/// Resolve a path filter to the target module(s) it points to.
284/// Returns the modules whose symbol indices should be searched.
285///
286/// The path_filter contains segments like ["std", "vec"] for a query like "std::vec::Vec".
287/// We resolve this by:
288/// 1. Finding crates matching the first segment
289/// 2. Walking down the module tree following subsequent segments
290fn resolve_path_to_modules(
291    db: &dyn HirDatabase,
292    path_filter: &[String],
293    anchor_to_crate: bool,
294    case_sensitive: bool,
295) -> Vec<Module> {
296    let [first_segment, rest_segments @ ..] = path_filter else {
297        return vec![];
298    };
299
300    // Helper for name comparison
301    let names_match = |actual: &str, expected: &str| -> bool {
302        if case_sensitive { actual == expected } else { actual.eq_ignore_ascii_case(expected) }
303    };
304
305    // Find crates matching the first segment
306    let matching_crates: Vec<Crate> = Crate::all(db)
307        .into_iter()
308        .filter(|krate| {
309            krate
310                .display_name(db)
311                .is_some_and(|name| names_match(name.crate_name().as_str(), first_segment))
312        })
313        .collect();
314
315    // If anchor_to_crate is true, first segment MUST be a crate name
316    // If anchor_to_crate is false, first segment could be a crate OR a module in local crates
317    let mut candidate_modules: Vec<(Module, bool)> = vec![];
318
319    // Add crate root modules for matching crates
320    for krate in matching_crates {
321        candidate_modules.push((krate.root_module(db), krate.origin(db).is_local()));
322    }
323
324    // If not anchored to crate, also search for modules matching first segment in local crates
325    if !anchor_to_crate {
326        for &root in LocalRoots::get(db).roots(db).iter() {
327            for &krate in source_root_crates(db, root).iter() {
328                let root_module = Crate::from(krate).root_module(db);
329                for child in root_module.children(db) {
330                    if let Some(name) = child.name(db)
331                        && names_match(name.as_str(), first_segment)
332                    {
333                        candidate_modules.push((child, true));
334                    }
335                }
336            }
337        }
338    }
339
340    // Walk down the module tree for remaining path segments
341    for segment in rest_segments {
342        candidate_modules = candidate_modules
343            .into_iter()
344            .flat_map(|(module, local)| {
345                module
346                    .modules_in_scope(db, !local)
347                    .into_iter()
348                    .filter(|(name, _)| names_match(name.as_str(), segment))
349                    .map(move |(_, module)| (module, local))
350            })
351            .unique()
352            .collect();
353
354        if candidate_modules.is_empty() {
355            break;
356        }
357    }
358
359    candidate_modules.into_iter().map(|(module, _)| module).collect()
360}
361
362#[derive(Default)]
363pub struct SymbolIndex<'db> {
364    symbols: Box<[FileSymbol<'db>]>,
365    map: fst::Map<Vec<u8>>,
366}
367
368// SAFETY:
369// - It is safe to compare a `SymbolIndex` from a previous revision to a new one.
370// - FileSymbol<'db>: Update
371unsafe impl<'db> Update for SymbolIndex<'db>
372where
373    FileSymbol<'db>: Update,
374{
375    unsafe fn maybe_update(old_pointer: *mut Self, new_value: Self) -> bool {
376        // SAFETY: Safe to dereference as per `salsa::Update` contract.
377        let this = unsafe { &mut *old_pointer };
378        if *this != new_value {
379            *this = new_value;
380            true
381        } else {
382            false
383        }
384    }
385}
386
387impl<'db> SymbolIndex<'db> {
388    /// The symbol index for a given source root within library_roots.
389    pub fn library_symbols(
390        db: &'db dyn HirDatabase,
391        source_root_id: SourceRootId,
392    ) -> &'db SymbolIndex<'db> {
393        #[salsa::tracked(returns(ref))]
394        fn library_symbols<'db>(
395            db: &'db dyn HirDatabase,
396            source_root_id: InternedSourceRootId<'db>,
397        ) -> SymbolIndex<'db> {
398            let _p = tracing::info_span!("library_symbols").entered();
399
400            // We call this without attaching because this runs in parallel, so we need to attach here.
401            hir::attach_db(db, || {
402                let mut symbol_collector = SymbolCollector::new(db, true);
403
404                source_root_crates(db, source_root_id.id(db))
405                    .iter()
406                    .flat_map(|&krate| Crate::from(krate).modules(db))
407                    // we specifically avoid calling other SymbolsDatabase queries here, even though they do the same thing,
408                    // as the index for a library is not going to really ever change, and we do not want to store
409                    // the module or crate indices for those in salsa unless we need to.
410                    .for_each(|module| symbol_collector.collect(module));
411
412                SymbolIndex::new(symbol_collector.finish())
413            })
414        }
415        library_symbols(db, InternedSourceRootId::new(db, source_root_id))
416    }
417
418    /// The symbol index for a given module. These modules should only be in source roots that
419    /// are inside local_roots.
420    pub fn module_symbols(db: &dyn HirDatabase, module: Module) -> &SymbolIndex<'_> {
421        #[salsa::tracked(returns(ref))]
422        fn module_symbols<'db>(
423            db: &'db dyn HirDatabase,
424            module: hir::ModuleId,
425        ) -> SymbolIndex<'db> {
426            let _p = tracing::info_span!("module_symbols").entered();
427
428            // We call this without attaching because this runs in parallel, so we need to attach here.
429            hir::attach_db(db, || {
430                let module: Module = module.into();
431                SymbolIndex::new(SymbolCollector::new_module(
432                    db,
433                    module,
434                    !module.krate(db).origin(db).is_local(),
435                ))
436            })
437        }
438
439        module_symbols(db, hir::ModuleId::from(module))
440    }
441
442    /// The symbol index for all extern prelude crates.
443    pub fn extern_prelude_symbols(db: &dyn HirDatabase) -> &SymbolIndex<'_> {
444        #[salsa::tracked(returns(ref))]
445        fn extern_prelude_symbols<'db>(db: &'db dyn HirDatabase) -> SymbolIndex<'db> {
446            let _p = tracing::info_span!("extern_prelude_symbols").entered();
447
448            // We call this without attaching because this runs in parallel, so we need to attach here.
449            hir::attach_db(db, || {
450                let mut collector = SymbolCollector::new(db, false);
451
452                for krate in Crate::all(db) {
453                    if krate
454                        .display_name(db)
455                        .is_none_or(|name| name.canonical_name().as_str() == "build-script-build")
456                    {
457                        continue;
458                    }
459                    if let CrateOrigin::Lang(LangCrateOrigin::Dependency | LangCrateOrigin::Other) =
460                        krate.origin(db)
461                    {
462                        // don't show dependencies of the sysroot
463                        continue;
464                    }
465                    collector.push_crate_root(krate);
466                }
467
468                SymbolIndex::new(collector.finish())
469            })
470        }
471
472        extern_prelude_symbols(db)
473    }
474}
475
476impl fmt::Debug for SymbolIndex<'_> {
477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478        f.debug_struct("SymbolIndex").field("n_symbols", &self.symbols.len()).finish()
479    }
480}
481
482impl PartialEq for SymbolIndex<'_> {
483    fn eq(&self, other: &SymbolIndex<'_>) -> bool {
484        self.symbols == other.symbols
485    }
486}
487
488impl Eq for SymbolIndex<'_> {}
489
490impl Hash for SymbolIndex<'_> {
491    fn hash<H: Hasher>(&self, hasher: &mut H) {
492        self.symbols.hash(hasher)
493    }
494}
495
496impl<'db> SymbolIndex<'db> {
497    fn new(mut symbols: Box<[FileSymbol<'db>]>) -> SymbolIndex<'db> {
498        fn cmp(lhs: &FileSymbol<'_>, rhs: &FileSymbol<'_>) -> Ordering {
499            let lhs_chars = lhs.name.as_str().chars().map(|c| c.to_ascii_lowercase());
500            let rhs_chars = rhs.name.as_str().chars().map(|c| c.to_ascii_lowercase());
501            lhs_chars.cmp(rhs_chars)
502        }
503
504        symbols.par_sort_by(cmp);
505
506        let mut builder = fst::MapBuilder::memory();
507
508        let mut last_batch_start = 0;
509
510        for idx in 0..symbols.len() {
511            if let Some(next_symbol) = symbols.get(idx + 1)
512                && cmp(&symbols[last_batch_start], next_symbol) == Ordering::Equal
513            {
514                continue;
515            }
516
517            let start = last_batch_start;
518            let end = idx + 1;
519            last_batch_start = end;
520
521            let key = symbols[start].name.as_str().to_ascii_lowercase();
522            let value = SymbolIndex::range_to_map_value(start, end);
523
524            builder.insert(key, value).unwrap();
525        }
526
527        let map = builder
528            .into_inner()
529            .and_then(|mut buf| {
530                fst::Map::new({
531                    buf.shrink_to_fit();
532                    buf
533                })
534            })
535            .unwrap();
536        SymbolIndex { symbols, map }
537    }
538
539    pub fn len(&self) -> usize {
540        self.symbols.len()
541    }
542
543    pub fn memory_size(&self) -> usize {
544        self.map.as_fst().size() + self.symbols.len() * size_of::<FileSymbol<'_>>()
545    }
546
547    fn range_to_map_value(start: usize, end: usize) -> u64 {
548        debug_assert![start <= (u32::MAX as usize)];
549        debug_assert![end <= (u32::MAX as usize)];
550
551        ((start as u64) << 32) | end as u64
552    }
553
554    fn map_value_to_range(value: u64) -> (usize, usize) {
555        let end = value as u32 as usize;
556        let start = (value >> 32) as usize;
557        (start, end)
558    }
559}
560
561impl Query {
562    /// Search symbols in the given indices.
563    pub(crate) fn search<'db, T>(
564        &self,
565        db: &'db RootDatabase,
566        indices: &[&'db SymbolIndex<'db>],
567        cb: impl FnMut(&'db FileSymbol<'db>) -> ControlFlow<T>,
568    ) -> Option<T> {
569        let _p = tracing::info_span!("symbol_index::Query::search").entered();
570
571        let mut op = fst::map::OpBuilder::new();
572        match self.mode {
573            SearchMode::Exact => {
574                let automaton = fst::automaton::Str::new(&self.lowercased);
575
576                for index in indices.iter() {
577                    op = op.add(index.map.search(&automaton));
578                }
579                self.search_maps(db, indices, op.union(), cb)
580            }
581            SearchMode::Fuzzy => {
582                let automaton = fst::automaton::Subsequence::new(&self.lowercased);
583
584                for index in indices.iter() {
585                    op = op.add(index.map.search(&automaton));
586                }
587                self.search_maps(db, indices, op.union(), cb)
588            }
589            SearchMode::Prefix => {
590                let automaton = fst::automaton::Str::new(&self.lowercased).starts_with();
591
592                for index in indices.iter() {
593                    op = op.add(index.map.search(&automaton));
594                }
595                self.search_maps(db, indices, op.union(), cb)
596            }
597        }
598    }
599
600    fn search_maps<'db, T>(
601        &self,
602        db: &'db RootDatabase,
603        indices: &[&'db SymbolIndex<'db>],
604        mut stream: fst::map::Union<'_>,
605        mut cb: impl FnMut(&'db FileSymbol<'db>) -> ControlFlow<T>,
606    ) -> Option<T> {
607        let ignore_underscore_prefixed = !self.query.starts_with("__");
608        while let Some((_, indexed_values)) = stream.next() {
609            for &IndexedValue { index, value } in indexed_values {
610                let symbol_index = indices[index];
611                let (start, end) = SymbolIndex::map_value_to_range(value);
612
613                for symbol in &symbol_index.symbols[start..end] {
614                    let non_type_for_type_only_query = self.only_types
615                        && !(matches!(
616                            symbol.def,
617                            hir::ModuleDef::Adt(..)
618                                | hir::ModuleDef::TypeAlias(..)
619                                | hir::ModuleDef::BuiltinType(..)
620                                | hir::ModuleDef::Trait(..)
621                        ) || matches!(
622                            symbol.def,
623                            hir::ModuleDef::Module(module) if module.is_crate_root(db)
624                        ));
625                    if non_type_for_type_only_query || !self.matches_assoc_mode(symbol.is_assoc) {
626                        continue;
627                    }
628                    // Hide symbols that start with `__` unless the query starts with `__`
629                    let symbol_name = symbol.name.as_str();
630                    if ignore_underscore_prefixed && symbol_name.starts_with("__") {
631                        continue;
632                    }
633                    if self.exclude_imports && symbol.is_import {
634                        continue;
635                    }
636                    if self.mode.check(&self.query, self.case_sensitive, symbol_name)
637                        && let Some(b) = cb(symbol).break_value()
638                    {
639                        return Some(b);
640                    }
641                }
642            }
643        }
644        None
645    }
646
647    fn matches_assoc_mode(&self, is_trait_assoc_item: bool) -> bool {
648        !matches!(
649            (is_trait_assoc_item, self.assoc_mode),
650            (true, AssocSearchMode::Exclude) | (false, AssocSearchMode::AssocItemsOnly)
651        )
652    }
653}
654
655#[cfg(test)]
656mod tests {
657
658    use expect_test::expect_file;
659    use rustc_hash::FxHashSet;
660    use salsa::Setter;
661    use test_fixture::{WORKSPACE, WithFixture};
662
663    use super::*;
664
665    #[test]
666    fn test_symbol_index_collection() {
667        let (db, _) = RootDatabase::with_many_files(
668            r#"
669//- /main.rs
670
671macro_rules! macro_rules_macro {
672    () => {}
673};
674
675macro_rules! define_struct {
676    () => {
677        struct StructFromMacro;
678    }
679};
680
681define_struct!();
682
683macro Macro { }
684
685struct Struct;
686enum Enum {
687    A, B
688}
689union Union {}
690
691impl Struct {
692    fn impl_fn() {}
693}
694
695struct StructT<T>;
696
697impl <T> StructT<T> {
698    fn generic_impl_fn() {}
699}
700
701trait Trait {
702    fn trait_fn(&self);
703}
704
705fn main() {
706    struct StructInFn;
707}
708
709const CONST: u32 = 1;
710static STATIC: &'static str = "2";
711type Alias = Struct;
712
713mod a_mod {
714    struct StructInModA;
715}
716
717const _: () = {
718    struct StructInUnnamedConst;
719
720    ()
721};
722
723const CONST_WITH_INNER: () = {
724    struct StructInNamedConst;
725
726    ()
727};
728
729mod b_mod;
730
731
732use define_struct as really_define_struct;
733use Macro as ItemLikeMacro;
734use Macro as Trait; // overlay namespaces
735//- /b_mod.rs
736struct StructInModB;
737pub(self) use super::Macro as SuperItemLikeMacro;
738pub(self) use crate::b_mod::StructInModB as ThisStruct;
739pub(self) use crate::Trait as IsThisJustATrait;
740"#,
741        );
742
743        let symbols: Vec<_> = Crate::from(db.test_crate())
744            .modules(&db)
745            .into_iter()
746            .map(|module_id| {
747                let mut symbols = SymbolCollector::new_module(&db, module_id, false);
748                symbols.sort_by_key(|it| it.name.as_str().to_owned());
749                (module_id, symbols)
750            })
751            .collect();
752
753        expect_file!["./test_data/test_symbol_index_collection.txt"].assert_debug_eq(&symbols);
754    }
755
756    #[test]
757    fn test_doc_alias() {
758        let (db, _) = RootDatabase::with_single_file(
759            r#"
760#[doc(alias="s1")]
761#[doc(alias="s2")]
762#[doc(alias("mul1","mul2"))]
763struct Struct;
764
765#[doc(alias="s1")]
766struct Duplicate;
767        "#,
768        );
769
770        let symbols: Vec<_> = Crate::from(db.test_crate())
771            .modules(&db)
772            .into_iter()
773            .map(|module_id| {
774                let mut symbols = SymbolCollector::new_module(&db, module_id, false);
775                symbols.sort_by_key(|it| it.name.as_str().to_owned());
776                (module_id, symbols)
777            })
778            .collect();
779
780        expect_file!["./test_data/test_doc_alias.txt"].assert_debug_eq(&symbols);
781    }
782
783    #[test]
784    fn test_exclude_imports() {
785        let (mut db, _) = RootDatabase::with_many_files(
786            r#"
787//- /lib.rs
788mod foo;
789pub use foo::Foo;
790
791//- /foo.rs
792pub struct Foo;
793"#,
794        );
795
796        let mut local_roots = FxHashSet::default();
797        local_roots.insert(WORKSPACE);
798        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
799
800        let mut query = Query::new("Foo".to_owned());
801        let mut symbols = world_symbols(&db, query.clone());
802        symbols.sort_by_key(|x| x.is_import);
803        expect_file!["./test_data/test_symbols_with_imports.txt"].assert_debug_eq(&symbols);
804
805        query.exclude_imports();
806        let symbols = world_symbols(&db, query);
807        expect_file!["./test_data/test_symbols_exclude_imports.txt"].assert_debug_eq(&symbols);
808    }
809
810    #[test]
811    fn test_parse_path_query() {
812        // Plain query - no path
813        let (path, item, anchor) = Query::parse_path_query("Item");
814        assert_eq!(path, Vec::<String>::new());
815        assert_eq!(item, "Item");
816        assert!(!anchor);
817
818        // Path with item
819        let (path, item, anchor) = Query::parse_path_query("foo::Item");
820        assert_eq!(path, vec!["foo"]);
821        assert_eq!(item, "Item");
822        assert!(!anchor);
823
824        // Multi-segment path
825        let (path, item, anchor) = Query::parse_path_query("foo::bar::Item");
826        assert_eq!(path, vec!["foo", "bar"]);
827        assert_eq!(item, "Item");
828        assert!(!anchor);
829
830        // Leading :: (anchor to crate)
831        let (path, item, anchor) = Query::parse_path_query("::std::vec::Vec");
832        assert_eq!(path, vec!["std", "vec"]);
833        assert_eq!(item, "Vec");
834        assert!(anchor);
835
836        // Just "::" - return all crates
837        let (path, item, anchor) = Query::parse_path_query("::");
838        assert_eq!(path, Vec::<String>::new());
839        assert_eq!(item, "");
840        assert!(anchor);
841
842        // "::foo" - fuzzy search crate names
843        let (path, item, anchor) = Query::parse_path_query("::foo");
844        assert_eq!(path, Vec::<String>::new());
845        assert_eq!(item, "foo");
846        assert!(anchor);
847
848        // Trailing ::
849        let (path, item, anchor) = Query::parse_path_query("foo::");
850        assert_eq!(path, vec!["foo"]);
851        assert_eq!(item, "");
852        assert!(!anchor);
853
854        // Full path with trailing ::
855        let (path, item, anchor) = Query::parse_path_query("foo::bar::");
856        assert_eq!(path, vec!["foo", "bar"]);
857        assert_eq!(item, "");
858        assert!(!anchor);
859
860        // Absolute path with trailing ::
861        let (path, item, anchor) = Query::parse_path_query("::std::vec::");
862        assert_eq!(path, vec!["std", "vec"]);
863        assert_eq!(item, "");
864        assert!(anchor);
865
866        // Empty segments should be filtered
867        let (path, item, anchor) = Query::parse_path_query("foo::::bar");
868        assert_eq!(path, vec!["foo"]);
869        assert_eq!(item, "bar");
870        assert!(!anchor);
871    }
872
873    #[test]
874    fn test_path_search() {
875        let (mut db, _) = RootDatabase::with_many_files(
876            r#"
877//- /lib.rs crate:main
878mod inner;
879pub struct RootStruct;
880
881//- /inner.rs
882pub struct InnerStruct;
883pub mod nested {
884    pub struct NestedStruct;
885}
886"#,
887        );
888
889        let mut local_roots = FxHashSet::default();
890        local_roots.insert(WORKSPACE);
891        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
892
893        // Search for item in specific module
894        let query = Query::new("inner::InnerStruct".to_owned());
895        let symbols = world_symbols(&db, query);
896        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
897        assert!(names.contains(&"InnerStruct"), "Expected InnerStruct in {:?}", names);
898
899        // Search for item in nested module
900        let query = Query::new("inner::nested::NestedStruct".to_owned());
901        let symbols = world_symbols(&db, query);
902        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
903        assert!(names.contains(&"NestedStruct"), "Expected NestedStruct in {:?}", names);
904
905        // Search with crate prefix
906        let query = Query::new("main::inner::InnerStruct".to_owned());
907        let symbols = world_symbols(&db, query);
908        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
909        assert!(names.contains(&"InnerStruct"), "Expected InnerStruct in {:?}", names);
910
911        // Wrong path should return empty
912        let query = Query::new("wrong::InnerStruct".to_owned());
913        let symbols = world_symbols(&db, query);
914        assert!(symbols.is_empty(), "Expected empty results for wrong path");
915    }
916
917    #[test]
918    fn test_path_search_module() {
919        let (mut db, _) = RootDatabase::with_many_files(
920            r#"
921//- /lib.rs crate:main
922mod mymod;
923
924//- /mymod.rs
925pub struct MyStruct;
926pub fn my_func() {}
927pub const MY_CONST: u32 = 1;
928"#,
929        );
930
931        let mut local_roots = FxHashSet::default();
932        local_roots.insert(WORKSPACE);
933        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
934
935        // Browse all items in module
936        let query = Query::new("main::mymod::".to_owned());
937        let symbols = world_symbols(&db, query);
938        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
939
940        assert!(names.contains(&"MyStruct"), "Expected MyStruct in {:?}", names);
941        assert!(names.contains(&"my_func"), "Expected my_func in {:?}", names);
942        assert!(names.contains(&"MY_CONST"), "Expected MY_CONST in {:?}", names);
943    }
944
945    #[test]
946    fn test_fuzzy_item_with_path() {
947        let (mut db, _) = RootDatabase::with_many_files(
948            r#"
949//- /lib.rs crate:main
950mod mymod;
951
952//- /mymod.rs
953pub struct MyLongStructName;
954"#,
955        );
956
957        let mut local_roots = FxHashSet::default();
958        local_roots.insert(WORKSPACE);
959        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
960
961        // Fuzzy match on item name with exact path
962        let query = Query::new("main::mymod::MyLong".to_owned());
963        let symbols = world_symbols(&db, query);
964        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
965        assert!(
966            names.contains(&"MyLongStructName"),
967            "Expected fuzzy match for MyLongStructName in {:?}",
968            names
969        );
970    }
971
972    #[test]
973    fn test_case_insensitive_path() {
974        let (mut db, _) = RootDatabase::with_many_files(
975            r#"
976//- /lib.rs crate:main
977mod MyMod;
978
979//- /MyMod.rs
980pub struct MyStruct;
981"#,
982        );
983
984        let mut local_roots = FxHashSet::default();
985        local_roots.insert(WORKSPACE);
986        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
987
988        // Case insensitive path matching (default)
989        let query = Query::new("main::mymod::MyStruct".to_owned());
990        let symbols = world_symbols(&db, query);
991        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
992        assert!(names.contains(&"MyStruct"), "Expected case-insensitive match in {:?}", names);
993    }
994
995    #[test]
996    fn test_absolute_path_search() {
997        let (mut db, _) = RootDatabase::with_many_files(
998            r#"
999//- /lib.rs crate:mycrate
1000mod inner;
1001pub struct CrateRoot;
1002
1003//- /inner.rs
1004pub struct InnerItem;
1005"#,
1006        );
1007
1008        let mut local_roots = FxHashSet::default();
1009        local_roots.insert(WORKSPACE);
1010        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
1011
1012        // Absolute path with leading ::
1013        let query = Query::new("::mycrate::inner::InnerItem".to_owned());
1014        let symbols = world_symbols(&db, query);
1015        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
1016        assert!(
1017            names.contains(&"InnerItem"),
1018            "Expected InnerItem with absolute path in {:?}",
1019            names
1020        );
1021
1022        // Absolute path should NOT match if crate name is wrong
1023        let query = Query::new("::wrongcrate::inner::InnerItem".to_owned());
1024        let symbols = world_symbols(&db, query);
1025        assert!(symbols.is_empty(), "Expected empty results for wrong crate name");
1026    }
1027
1028    #[test]
1029    fn test_wrong_path_returns_empty() {
1030        let (mut db, _) = RootDatabase::with_many_files(
1031            r#"
1032//- /lib.rs crate:main
1033mod existing;
1034
1035//- /existing.rs
1036pub struct MyStruct;
1037"#,
1038        );
1039
1040        let mut local_roots = FxHashSet::default();
1041        local_roots.insert(WORKSPACE);
1042        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
1043
1044        // Non-existent module path
1045        let query = Query::new("nonexistent::MyStruct".to_owned());
1046        let symbols = world_symbols(&db, query);
1047        assert!(symbols.is_empty(), "Expected empty results for non-existent path");
1048
1049        // Correct item, wrong module
1050        let query = Query::new("wrongmod::MyStruct".to_owned());
1051        let symbols = world_symbols(&db, query);
1052        assert!(symbols.is_empty(), "Expected empty results for wrong module");
1053    }
1054
1055    #[test]
1056    fn test_root_module_items() {
1057        let (mut db, _) = RootDatabase::with_many_files(
1058            r#"
1059//- /lib.rs crate:mylib
1060pub struct RootItem;
1061pub fn root_fn() {}
1062"#,
1063        );
1064
1065        let mut local_roots = FxHashSet::default();
1066        local_roots.insert(WORKSPACE);
1067        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
1068
1069        // Items at crate root - path is just the crate name
1070        let query = Query::new("mylib::RootItem".to_owned());
1071        let symbols = world_symbols(&db, query);
1072        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
1073        assert!(names.contains(&"RootItem"), "Expected RootItem at crate root in {:?}", names);
1074
1075        let query = Query::new("mylib::".to_owned());
1076        let symbols = world_symbols(&db, query);
1077        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
1078        assert!(names.contains(&"RootItem"), "Expected RootItem {:?}", names);
1079        assert!(names.contains(&"root_fn"), "Expected root_fn {:?}", names);
1080    }
1081
1082    #[test]
1083    fn test_crate_search_all() {
1084        // Test that sole "::" returns all crates
1085        let (mut db, _) = RootDatabase::with_many_files(
1086            r#"
1087//- /lib.rs crate:alpha
1088pub struct AlphaStruct;
1089
1090//- /beta.rs crate:beta
1091pub struct BetaStruct;
1092
1093//- /gamma.rs crate:gamma
1094pub struct GammaStruct;
1095"#,
1096        );
1097
1098        let mut local_roots = FxHashSet::default();
1099        local_roots.insert(WORKSPACE);
1100        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
1101
1102        // Sole "::" should return all crates (as module symbols)
1103        let query = Query::new("::".to_owned());
1104        let symbols = world_symbols(&db, query);
1105        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
1106
1107        assert!(names.contains(&"alpha"), "Expected alpha crate in {:?}", names);
1108        assert!(names.contains(&"beta"), "Expected beta crate in {:?}", names);
1109        assert!(names.contains(&"gamma"), "Expected gamma crate in {:?}", names);
1110        assert_eq!(symbols.len(), 3, "Expected exactly 3 crates, got {:?}", names);
1111    }
1112
1113    #[test]
1114    fn test_crate_search_fuzzy() {
1115        // Test that "::foo" fuzzy-matches crate names
1116        let (mut db, _) = RootDatabase::with_many_files(
1117            r#"
1118//- /lib.rs crate:my_awesome_lib
1119pub struct AwesomeStruct;
1120
1121//- /other.rs crate:another_lib
1122pub struct OtherStruct;
1123
1124//- /foo.rs crate:foobar
1125pub struct FooStruct;
1126"#,
1127        );
1128
1129        let mut local_roots = FxHashSet::default();
1130        local_roots.insert(WORKSPACE);
1131        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
1132
1133        // "::foo" should fuzzy-match crate names containing "foo"
1134        let query = Query::new("::foo".to_owned());
1135        let symbols = world_symbols(&db, query);
1136        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
1137
1138        assert!(names.contains(&"foobar"), "Expected foobar crate in {:?}", names);
1139        assert_eq!(symbols.len(), 1, "Expected only foobar crate, got {:?}", names);
1140
1141        // "::awesome" should match my_awesome_lib
1142        let query = Query::new("::awesome".to_owned());
1143        let symbols = world_symbols(&db, query);
1144        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
1145
1146        assert!(names.contains(&"my_awesome_lib"), "Expected my_awesome_lib crate in {:?}", names);
1147        assert_eq!(symbols.len(), 1, "Expected only my_awesome_lib crate, got {:?}", names);
1148
1149        // "::lib" should match multiple crates
1150        let query = Query::new("::lib".to_owned());
1151        let symbols = world_symbols(&db, query);
1152        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
1153
1154        assert!(names.contains(&"my_awesome_lib"), "Expected my_awesome_lib in {:?}", names);
1155        assert!(names.contains(&"another_lib"), "Expected another_lib in {:?}", names);
1156        assert_eq!(symbols.len(), 2, "Expected 2 crates matching 'lib', got {:?}", names);
1157
1158        // "::nonexistent" should return empty
1159        let query = Query::new("::nonexistent".to_owned());
1160        let symbols = world_symbols(&db, query);
1161        assert!(symbols.is_empty(), "Expected empty results for non-matching crate pattern");
1162    }
1163
1164    #[test]
1165    fn test_path_search_with_use_reexport() {
1166        // Test that module resolution works for `use` items (re-exports), not just `mod` items
1167        let (mut db, _) = RootDatabase::with_many_files(
1168            r#"
1169//- /lib.rs crate:main
1170mod inner;
1171pub use inner::nested;
1172
1173//- /inner.rs
1174pub mod nested {
1175    pub struct NestedStruct;
1176    pub fn nested_fn() {}
1177}
1178"#,
1179        );
1180
1181        let mut local_roots = FxHashSet::default();
1182        local_roots.insert(WORKSPACE);
1183        LocalRoots::get(&db).set_roots(&mut db).to(local_roots);
1184
1185        // Search via the re-exported path (main::nested::NestedStruct)
1186        // This should work because `nested` is in scope via `pub use inner::nested`
1187        let query = Query::new("main::nested::NestedStruct".to_owned());
1188        let symbols = world_symbols(&db, query);
1189        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
1190        assert!(
1191            names.contains(&"NestedStruct"),
1192            "Expected NestedStruct via re-exported path in {:?}",
1193            names
1194        );
1195
1196        // Also verify the original path still works
1197        let query = Query::new("main::inner::nested::NestedStruct".to_owned());
1198        let symbols = world_symbols(&db, query);
1199        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
1200        assert!(
1201            names.contains(&"NestedStruct"),
1202            "Expected NestedStruct via original path in {:?}",
1203            names
1204        );
1205
1206        // Browse the re-exported module
1207        let query = Query::new("main::nested::".to_owned());
1208        let symbols = world_symbols(&db, query);
1209        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
1210        assert!(
1211            names.contains(&"NestedStruct"),
1212            "Expected NestedStruct when browsing re-exported module in {:?}",
1213            names
1214        );
1215        assert!(
1216            names.contains(&"nested_fn"),
1217            "Expected nested_fn when browsing re-exported module in {:?}",
1218            names
1219        );
1220    }
1221}