Skip to main content

ridx_format/workspace/navigation/
workspace_symbol.rs

1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11use super::workspace_symbol_crates::{crate_entries, crate_entry_name, is_crate_entry};
12use super::workspace_symbol_match::{contains_ascii_ci, is_fuzzy_subseq, ra_fuzzy_match};
13use super::workspace_symbol_use::{child_item_of_private_import, declared_pub_super, import_target_kind, use_is_pub};
14use super::*;
15
16/// A symbol rust-analyzer's search covers: a workspace definition `(reader, definition)` or a crate root
17/// `(reader, CRATE_ROOT)`, with the kind it is listed under (an import takes the kind of what it imports).
18#[derive(Clone, Copy)]
19struct SymEntry {
20    reader: u32,
21    def: u32,
22    kind: DefKind,
23}
24
25struct CachedWsDefs {
26    /// Every symbol, dependencies' crate roots included, ordered by lowercased name.
27    all_by_name: Vec<SymEntry>,
28    /// The type-like subset rust-analyzer searches first (its default `only_types` search kind).
29    types_by_name: Vec<SymEntry>,
30}
31
32/// The name an entry is matched and ordered by; a raw identifier counts by its name (`async` for `r#async`), as in
33/// rust-analyzer.
34fn entry_name(ws: &WorkspaceIndex, e: SymEntry) -> &str {
35    let reader = &ws.readers[e.reader as usize];
36    if is_crate_entry(e.def) {
37        crate_entry_name(reader, e.def)
38    } else {
39        let name = reader.get_str(reader.definitions()[e.def as usize].name_offset());
40        name.strip_prefix("r#").unwrap_or(name)
41    }
42}
43
44/// What rust-analyzer's `only_types` search returns: types, traits, type aliases and crates, not modules.
45fn is_ra_type_entry(e: &SymEntry) -> bool {
46    is_crate_entry(e.def)
47        || matches!(e.kind, DefKind::Struct | DefKind::Enum | DefKind::Union | DefKind::Trait | DefKind::TraitAlias | DefKind::TyAlias | DefKind::AssocTy | DefKind::ForeignTy)
48}
49
50fn get_or_build_ws_defs(ws: &WorkspaceIndex, has_local: bool) -> std::sync::Arc<CachedWsDefs> {
51    use std::collections::{HashMap, HashSet};
52    use std::sync::{Arc, Mutex, OnceLock};
53    type CacheKey = (u64, bool);
54    static CACHE: OnceLock<Mutex<HashMap<CacheKey, Arc<CachedWsDefs>>>> = OnceLock::new();
55    // Every reader's definition table (address and length) identifies the workspace: entries index into them.
56    let mut hasher = std::collections::hash_map::DefaultHasher::new();
57    for r in &ws.readers {
58        std::hash::Hash::hash(&(r.definitions().as_ptr() as usize, r.definitions().len(), r.crate_name()), &mut hasher);
59    }
60    let key = (std::hash::Hasher::finish(&hasher), has_local);
61    let mutex = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
62    if let Ok(guard) = mutex.lock() {
63        if let Some(found) = guard.get(&key) {
64            return Arc::clone(found);
65        }
66    }
67    let mut by_name: Vec<SymEntry> = Vec::new();
68    let mut seen = HashSet::new();
69    let mut sources: HashMap<&str, Option<String>> = HashMap::new();
70    for (i, reader) in ws.readers.iter().enumerate() {
71        if has_local && ws.reader_is_dependency.get(i).copied().unwrap_or(false) {
72            continue;
73        }
74        for (d_idx, def) in reader.definitions().iter().enumerate() {
75            let kind = DefKind::from(def.kind);
76            let name = reader.get_str(def.name_offset());
77            // rust-analyzer lists re-exports (`pub use a::B;`) and renaming imports (`use a::B as C;`) as symbols,
78            // not plain private imports, globs or `self` — except a private import of a child's `pub(super)` item,
79            // which keeps the item's explicit visibility.
80            let target = if def.sig_offset() != 0 { reader.get_str(def.sig_offset()) } else { "" };
81            let renamed = target.rsplit("::").next().is_some_and(|last| !last.is_empty() && last != name);
82            let is_named_import = kind == DefKind::Use && !matches!(name, "*" | "_" | "self") && {
83                let span = def.span();
84                let file = reader.get_file(span.file_id());
85                let read = |file: &str| ws.read_source_file(file).or_else(|| ws.resolve_path_for_crate(reader.crate_name(), file).to_str().and_then(|s| ws.read_source_file(s)));
86                renamed
87                    || sources.entry(file).or_insert_with(|| read(file)).as_deref().is_some_and(|src| use_is_pub(src, span.start_line(), span.start_col()))
88                    || child_item_of_private_import(reader, reader.get_str(def.path_offset()), target)
89                        .is_some_and(|(item_file, l, c)| sources.entry(item_file).or_insert_with(|| read(item_file)).as_deref().is_some_and(|src| declared_pub_super(src, l, c)))
90            };
91            if (is_excluded_ws_kind(kind) && !is_named_import) || name.is_empty() {
92                continue;
93            }
94            let path = reader.get_str(def.path_offset());
95            let span = def.span();
96            // rustc's test descriptor: a `const` named like its `#[test]` function, spanning the attribute, or sharing
97            // the function's path (a `const` and a `fn` never share one otherwise) where a macro wrote both.
98            let width = span.end_col().saturating_sub(span.start_col()) as usize;
99            let spans_attr = span.start_line() == span.end_line() && width != name.chars().count() && width != name.chars().count() + 2;
100            if kind == DefKind::Const && (spans_attr || reader.has_multiple_definitions_at_path(path)) {
101                continue;
102            }
103            // rust-analyzer collects items declared in the bodies of module-level functions, not in method bodies.
104            if path.rsplit_once("::").and_then(|(parent, _)| reader.find_definition_by_path(parent)).is_some_and(|p| DefKind::from(p.kind) == DefKind::AssocFn) {
105                continue;
106            }
107            let file = reader.get_file(span.file_id());
108            if !seen.insert((path, file, span.start_line(), span.start_col())) {
109                continue;
110            }
111            let kind = if is_named_import && !target.is_empty() { import_target_kind(ws, reader, target) } else { kind };
112            by_name.push(SymEntry { reader: i as u32, def: d_idx as u32, kind });
113        }
114    }
115    by_name.extend(crate_entries(ws).into_iter().map(|(reader, def)| SymEntry { reader, def, kind: DefKind::Mod }));
116    // Stable sort: equal lowercased names keep index order. Lowercasing on the fly keeps no name copies alive.
117    by_name.sort_by(|&a, &b| entry_name(ws, a).chars().flat_map(char::to_lowercase).cmp(entry_name(ws, b).chars().flat_map(char::to_lowercase)));
118    let types_by_name = by_name.iter().copied().filter(is_ra_type_entry).collect();
119    let built = Arc::new(CachedWsDefs { all_by_name: by_name, types_by_name });
120    if let Ok(mut guard) = mutex.lock() {
121        if guard.len() >= 16 {
122            guard.clear();
123        }
124        guard.insert(key, Arc::clone(&built));
125    }
126    built
127}
128
129fn is_excluded_ws_kind(kind: DefKind) -> bool {
130    matches!(
131        kind,
132        DefKind::TyParam
133            | DefKind::LifetimeParam
134            | DefKind::ConstParam
135            | DefKind::Local
136            | DefKind::Field
137            | DefKind::Use
138            | DefKind::ExternCrate
139            | DefKind::Impl
140            | DefKind::Closure
141            | DefKind::AnonConst
142            | DefKind::InlineConst
143            | DefKind::StructCtor
144            | DefKind::VariantCtor
145    )
146}
147
148fn is_type_or_mod_ws_kind(kind: DefKind) -> bool {
149    matches!(
150        kind,
151        DefKind::Mod
152            | DefKind::Struct
153            | DefKind::Union
154            | DefKind::Enum
155            | DefKind::Trait
156            | DefKind::TyAlias
157            | DefKind::ForeignTy
158            | DefKind::TraitAlias
159            | DefKind::AssocTy
160            | DefKind::Const
161            | DefKind::Static
162            | DefKind::AssocConst
163            | DefKind::Macro
164            | DefKind::ForeignMod
165            | DefKind::OpaqueTy
166    )
167}
168
169impl WorkspaceIndex {
170    /// Workspace symbols as rust-analyzer lists them: items and imports whose name contains the query as a smart-case
171    /// subsequence, plus crates (dependencies included) whose name does, ordered by lowercased name and cut at
172    /// `limit`; types first, every kind only when no type matches; the dependencies' and the standard library's
173    /// symbols when nothing of the workspace matches (rust-analyzer's fallback to libraries: `Extend` lists
174    /// `core::iter::Extend`, which prod-code reads to keep a generated name off the prelude's, issue #6).
175    fn search_workspace_symbols_like_ra<'a>(&'a self, query: &str, limit: usize) -> Vec<WorkspaceSymbol<'a>> {
176        let has_local = self.reader_is_dependency.iter().any(|&d| !d);
177        let found = self.search_ra_defs(&get_or_build_ws_defs(self, has_local), query, limit);
178        if found.is_empty() && has_local {
179            return self.search_ra_defs(&get_or_build_ws_defs(self, false), query, limit);
180        }
181        found
182    }
183
184    /// rust-analyzer searches types first and all symbols only when no type matches.
185    fn search_ra_defs<'a>(&'a self, cached: &CachedWsDefs, query: &str, limit: usize) -> Vec<WorkspaceSymbol<'a>> {
186        let types = self.collect_ra_matches(&cached.types_by_name, query, limit);
187        if !types.is_empty() {
188            return types;
189        }
190        self.collect_ra_matches(&cached.all_by_name, query, limit)
191    }
192
193    fn collect_ra_matches<'a>(&'a self, entries: &[SymEntry], query: &str, limit: usize) -> Vec<WorkspaceSymbol<'a>> {
194        let mut out = Vec::new();
195        // One item compiled into several units (lib, lib test, bin) is one symbol: dedupe on the file it resolves to.
196        let mut seen = std::collections::HashSet::new();
197        let case_sensitive = query.chars().any(char::is_uppercase);
198        // rust-analyzer leaves `__`-prefixed names (macro internals such as `__DeserializeWith`) out unless asked for.
199        let skip_dunder = !query.starts_with("__");
200        for &entry in entries {
201            let name = entry_name(self, entry);
202            if (skip_dunder && name.starts_with("__")) || !ra_fuzzy_match(name, query, case_sensitive) {
203                continue;
204            }
205            let symbol = self.ws_symbol_at(entry);
206            // The name is part of the key: a crate root is listed under its crate's name and its target's dashed name
207            // (`search_stdin`, `search-stdin`), both at the root file's first position.
208            if !seen.insert((symbol.resolved_path(), symbol.span.start_line(), symbol.span.start_col(), symbol.name)) {
209                continue;
210            }
211            out.push(symbol);
212            if out.len() >= limit {
213                break;
214            }
215        }
216        out
217    }
218
219    fn ws_symbol_at(&self, entry: SymEntry) -> WorkspaceSymbol<'_> {
220        let i = entry.reader as usize;
221        let reader = &self.readers[i];
222        let source_root = self.source_roots.get(i).and_then(|r| r.as_deref()).or(self.workspace_root.as_deref());
223        let unit_key = self.unit_keys.get(i).and_then(|u| u.as_deref());
224        let crate_name = reader.crate_name();
225        if is_crate_entry(entry.def) {
226            let name = crate_entry_name(reader, entry.def);
227            let span = crate::format::Span::new(0, 1, 1, 1, name.len() as u32 + 1);
228            return WorkspaceSymbol {
229                crate_name,
230                name,
231                path: name,
232                kind: DefKind::Mod,
233                file: reader.get_file(0),
234                span,
235                signature: None,
236                is_macro_expansion: false,
237                source_root,
238                unit_key,
239            };
240        }
241        let def = &reader.definitions()[entry.def as usize];
242        let span = def.span();
243        WorkspaceSymbol {
244            crate_name,
245            name: reader.get_str(def.name_offset()),
246            path: reader.get_str(def.path_offset()),
247            kind: entry.kind,
248            file: reader.get_file(span.file_id()),
249            span,
250            signature: if def.sig_offset() != 0 { Some(reader.get_str(def.sig_offset())) } else { None },
251            is_macro_expansion: def.is_macro_expansion(),
252            source_root,
253            unit_key,
254        }
255    }
256
257    /// Workspace symbol search. A plain query follows rust-analyzer (see `search_workspace_symbols_like_ra`); an empty
258    /// query or a path query (`a::b`) keeps the local-first substring search.
259    pub fn search_workspace_symbols<'a>(&'a self, query: &str, limit: usize) -> Vec<WorkspaceSymbol<'a>> {
260        if !query.is_empty() && !query.contains("::") {
261            return self.search_workspace_symbols_like_ra(query, limit);
262        }
263        let q_lower = query.to_ascii_lowercase();
264        let q_bytes = q_lower.as_bytes();
265        let has_local = self.reader_is_dependency.iter().any(|&d| !d);
266        let multi_reader = self.readers.len() > 1;
267        let mut results: Vec<WorkspaceSymbol<'a>> = Vec::new();
268        let mut seen = std::collections::HashSet::new();
269
270        for pass in 0..4u8 {
271            if results.len() >= limit {
272                break;
273            }
274            if pass > 0 && query.is_empty() {
275                break;
276            }
277            if (pass == 1 || pass == 3) && query.len() < 2 {
278                continue;
279            }
280            if pass == 3 && !results.is_empty() {
281                break;
282            }
283            for (i, reader) in self.readers.iter().enumerate() {
284                if has_local && self.reader_is_dependency.get(i).copied().unwrap_or(false) {
285                    continue;
286                }
287                let crate_name = reader.crate_name();
288                let source_root = self.source_roots.get(i).and_then(|r| r.as_deref()).or(self.workspace_root.as_deref());
289                let unit_key = self.unit_keys.get(i).and_then(|u| u.as_deref());
290
291                if multi_reader && (pass == 0 || pass == 1) && !crate_name.is_empty() {
292                    let crate_matched = if pass == 0 { contains_ascii_ci(crate_name.as_bytes(), q_bytes) } else { is_fuzzy_subseq(crate_name, query) };
293                    if crate_matched {
294                        let root_file = reader.get_file(0);
295                        if !root_file.is_empty() && seen.insert((crate_name, root_file, 1u32, 1u32)) {
296                            results.push(WorkspaceSymbol {
297                                crate_name,
298                                name: crate_name,
299                                path: crate_name,
300                                kind: DefKind::Mod,
301                                file: root_file,
302                                span: crate::format::Span::new(0, 1, 1, 1, crate_name.len() as u32 + 1),
303                                signature: None,
304                                is_macro_expansion: false,
305                                source_root,
306                                unit_key,
307                            });
308                            if results.len() >= limit {
309                                return results;
310                            }
311                        }
312                    }
313                }
314
315                for def in reader.definitions() {
316                    let kind = DefKind::from(def.kind);
317                    if is_excluded_ws_kind(kind) {
318                        continue;
319                    }
320                    if !query.is_empty() {
321                        let is_type = is_type_or_mod_ws_kind(kind);
322                        if (pass <= 1 && !is_type) || (pass >= 2 && is_type) {
323                            continue;
324                        }
325                    }
326                    let name = reader.get_str(def.name_offset());
327                    if name.is_empty() {
328                        continue;
329                    }
330                    let path = reader.get_str(def.path_offset());
331                    let matched = if query.is_empty() {
332                        true
333                    } else if pass == 0 || pass == 2 {
334                        contains_ascii_ci(name.as_bytes(), q_bytes)
335                            || ((query.contains("::") || (!multi_reader && crate_name.eq_ignore_ascii_case(query))) && contains_ascii_ci(path.as_bytes(), q_bytes))
336                    } else {
337                        is_fuzzy_subseq(name, query)
338                    };
339                    if !matched {
340                        continue;
341                    }
342                    let span = def.span();
343                    let file = reader.get_file(span.file_id());
344                    if !seen.insert((path, file, span.start_line(), span.start_col())) {
345                        continue;
346                    }
347                    let signature = if def.sig_offset() != 0 { Some(reader.get_str(def.sig_offset())) } else { None };
348                    results.push(WorkspaceSymbol { crate_name, name, path, kind, file, span, signature, is_macro_expansion: def.is_macro_expansion(), source_root, unit_key });
349                    if results.len() >= limit {
350                        return results;
351                    }
352                }
353            }
354        }
355        results
356    }
357}
358
359#[cfg(test)]
360#[path = "workspace_symbol_tests.rs"]
361mod tests;