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
169/// `path` split at its `::`s outside angle brackets: `<Foo as a::Bar>::f` is two segments. The `>` of a `->` inside
170/// one (`Handler::<fn() -> a::B>::call`) closes nothing (review of #14).
171pub fn path_segments(path: &str) -> Vec<&str> {
172    let (mut out, mut depth, mut start) = (Vec::new(), 0usize, 0usize);
173    let bytes = path.as_bytes();
174    let mut i = 0;
175    while i < bytes.len() {
176        match bytes[i] {
177            b'<' => depth += 1,
178            b'>' if depth > 0 && (i == 0 || bytes[i - 1] != b'-') => depth -= 1,
179            b':' if depth == 0 && bytes.get(i + 1) == Some(&b':') => {
180                out.push(&path[start..i]);
181                start = i + 2;
182                i += 1;
183            }
184            _ => {}
185        }
186        i += 1;
187    }
188    out.push(&path[start..]);
189    out
190}
191
192/// The type of a qualified-self segment, `a::Foo<T>` of `<a::Foo<T> as Debug>`; `None` for a generic list only (`<T>`).
193pub fn qualified_self_type(segment: &str) -> Option<&str> {
194    let inner = segment.strip_prefix('<')?.strip_suffix('>')?;
195    // ` as ` outside the type's own brackets.
196    let mut depth = 0usize;
197    let bytes = inner.as_bytes();
198    for i in 0..bytes.len() {
199        match bytes[i] {
200            b'<' => depth += 1,
201            b'>' if depth > 0 && (i == 0 || bytes[i - 1] != b'-') => depth -= 1,
202            b' ' if depth == 0 && inner[i..].starts_with(" as ") => return Some(&inner[..i]),
203            _ => {}
204        }
205    }
206    None
207}
208
209/// `path` without the generic lists of its segments: `mpsc::Receiver::<T>::recv_many` is `mpsc::Receiver::recv_many`,
210/// `<a::Foo<T> as Debug>::fmt` is `a::Foo::fmt`.
211pub fn path_without_generics(path: &str) -> std::borrow::Cow<'_, str> {
212    if !path.contains('<') {
213        return std::borrow::Cow::Borrowed(path);
214    }
215    let mut parts: Vec<String> = Vec::new();
216    for seg in path_segments(path) {
217        let seg = seg.trim();
218        if seg.starts_with('<') {
219            if let Some(ty) = qualified_self_type(seg) {
220                parts.push(path_without_generics(ty).into_owned());
221            }
222            continue;
223        }
224        parts.push(seg.split('<').next().unwrap_or(seg).to_string());
225    }
226    std::borrow::Cow::Owned(parts.into_iter().filter(|p| !p.is_empty()).collect::<Vec<_>>().join("::"))
227}
228
229/// Whether a path query is in `path`, both read as written and without generic lists, with or without the crate's name
230/// in front (`rapidfire::mpsc::Receiver::<T>::recv_many`, `Receiver::recv_many`).
231fn path_matches(crate_name: &str, path: &str, query: &str) -> bool {
232    // Every form below holds the query's last segment's name as written: skip the rest without building them.
233    // Taken from the query without its generic lists: `Map::get::<K, a::Key>` ends in `get`, not `Key>` (review of #14).
234    let q_plain = path_without_generics(query);
235    let last = q_plain.rsplit("::").next().unwrap_or(&q_plain).to_ascii_lowercase();
236    if !last.is_empty() && !contains_ascii_ci(path.as_bytes(), last.as_bytes()) {
237        return false;
238    }
239    let plain = path_without_generics(path);
240    let candidates = [path.to_string(), plain.to_string(), format!("{crate_name}::{path}"), format!("{crate_name}::{plain}")];
241    let queries = [query.to_ascii_lowercase(), q_plain.to_ascii_lowercase()];
242    candidates.iter().any(|c| queries.iter().any(|q| contains_ascii_ci(c.as_bytes(), q.as_bytes())))
243}
244
245impl WorkspaceIndex {
246    /// Workspace symbols as rust-analyzer lists them: items and imports whose name contains the query as a smart-case
247    /// subsequence, plus crates (dependencies included) whose name does, ordered by lowercased name and cut at
248    /// `limit`; types first, every kind only when no type matches; the dependencies' and the standard library's
249    /// symbols when nothing of the workspace matches (rust-analyzer's fallback to libraries: `Extend` lists
250    /// `core::iter::Extend`, which prod-code reads to keep a generated name off the prelude's, issue #6).
251    fn search_workspace_symbols_like_ra<'a>(&'a self, query: &str, limit: usize) -> Vec<WorkspaceSymbol<'a>> {
252        let has_local = self.reader_is_dependency.iter().any(|&d| !d);
253        let found = self.search_ra_defs(&get_or_build_ws_defs(self, has_local), query, limit);
254        if found.is_empty() && has_local {
255            return self.search_ra_defs(&get_or_build_ws_defs(self, false), query, limit);
256        }
257        found
258    }
259
260    /// rust-analyzer searches types first and all symbols only when no type matches.
261    fn search_ra_defs<'a>(&'a self, cached: &CachedWsDefs, query: &str, limit: usize) -> Vec<WorkspaceSymbol<'a>> {
262        let types = self.collect_ra_matches(&cached.types_by_name, query, limit);
263        if !types.is_empty() {
264            return types;
265        }
266        self.collect_ra_matches(&cached.all_by_name, query, limit)
267    }
268
269    fn collect_ra_matches<'a>(&'a self, entries: &[SymEntry], query: &str, limit: usize) -> Vec<WorkspaceSymbol<'a>> {
270        let mut out = Vec::new();
271        // One item compiled into several units (lib, lib test, bin) is one symbol: dedupe on the file it resolves to.
272        let mut seen = std::collections::HashSet::new();
273        let case_sensitive = query.chars().any(char::is_uppercase);
274        // rust-analyzer leaves `__`-prefixed names (macro internals such as `__DeserializeWith`) out unless asked for.
275        let skip_dunder = !query.starts_with("__");
276        for &entry in entries {
277            let name = entry_name(self, entry);
278            if (skip_dunder && name.starts_with("__")) || !ra_fuzzy_match(name, query, case_sensitive) {
279                continue;
280            }
281            let symbol = self.ws_symbol_at(entry);
282            // The name is part of the key: a crate root is listed under its crate's name and its target's dashed name
283            // (`search_stdin`, `search-stdin`), both at the root file's first position.
284            if !seen.insert((symbol.resolved_path(), symbol.span.start_line(), symbol.span.start_col(), symbol.name)) {
285                continue;
286            }
287            out.push(symbol);
288            if out.len() >= limit {
289                break;
290            }
291        }
292        out
293    }
294
295    fn ws_symbol_at(&self, entry: SymEntry) -> WorkspaceSymbol<'_> {
296        let i = entry.reader as usize;
297        let reader = &self.readers[i];
298        let source_root = self.source_roots.get(i).and_then(|r| r.as_deref()).or(self.workspace_root.as_deref());
299        let unit_key = self.unit_keys.get(i).and_then(|u| u.as_deref());
300        let crate_name = reader.crate_name();
301        if is_crate_entry(entry.def) {
302            let name = crate_entry_name(reader, entry.def);
303            let span = crate::format::Span::new(0, 1, 1, 1, name.len() as u32 + 1);
304            return WorkspaceSymbol {
305                crate_name,
306                name,
307                path: name,
308                kind: DefKind::Mod,
309                file: reader.get_file(0),
310                span,
311                signature: None,
312                is_macro_expansion: false,
313                source_root,
314                unit_key,
315            };
316        }
317        let def = &reader.definitions()[entry.def as usize];
318        let span = def.span();
319        WorkspaceSymbol {
320            crate_name,
321            name: reader.get_str(def.name_offset()),
322            path: reader.get_str(def.path_offset()),
323            kind: entry.kind,
324            file: reader.get_file(span.file_id()),
325            span,
326            signature: if def.sig_offset() != 0 { Some(reader.get_str(def.sig_offset())) } else { None },
327            is_macro_expansion: def.is_macro_expansion(),
328            source_root,
329            unit_key,
330        }
331    }
332
333    /// Workspace symbol search. A plain query follows rust-analyzer (see `search_workspace_symbols_like_ra`); an empty
334    /// query or a path query (`a::b`) keeps the local-first substring search.
335    pub fn search_workspace_symbols<'a>(&'a self, query: &str, limit: usize) -> Vec<WorkspaceSymbol<'a>> {
336        if !query.is_empty() && !query.contains("::") {
337            return self.search_workspace_symbols_like_ra(query, limit);
338        }
339        let found = self.search_symbols_by_substring(query, limit, true);
340        // A path naming a dependency's item (`rapidfire::mpsc::bounded`) is found there when nothing local matches, as
341        // a plain name is (prod-code, m=23269: it came back empty, and only `bounded` found it).
342        if found.is_empty() && query.contains("::") {
343            return self.search_symbols_by_substring(query, limit, false);
344        }
345        found
346    }
347
348    /// The substring search of `search_workspace_symbols`: the workspace's crates only when `local_first` and it has
349    /// any, every crate otherwise. A path query matches an item's path with its crate's name in front and the generic
350    /// lists of its impl left out (`Receiver::recv_many` matches `mpsc::Receiver::<T>::recv_many`).
351    fn search_symbols_by_substring<'a>(&'a self, query: &str, limit: usize, local_first: bool) -> Vec<WorkspaceSymbol<'a>> {
352        let q_lower = query.to_ascii_lowercase();
353        let q_bytes = q_lower.as_bytes();
354        let is_path_query = query.contains("::");
355        let has_local = local_first && self.reader_is_dependency.iter().any(|&d| !d);
356        let multi_reader = self.readers.len() > 1;
357        let mut results: Vec<WorkspaceSymbol<'a>> = Vec::new();
358        let mut seen = std::collections::HashSet::new();
359
360        for pass in 0..4u8 {
361            if results.len() >= limit {
362                break;
363            }
364            if pass > 0 && query.is_empty() {
365                break;
366            }
367            if (pass == 1 || pass == 3) && query.len() < 2 {
368                continue;
369            }
370            if pass == 3 && !results.is_empty() {
371                break;
372            }
373            for (i, reader) in self.readers.iter().enumerate() {
374                if has_local && self.reader_is_dependency.get(i).copied().unwrap_or(false) {
375                    continue;
376                }
377                let crate_name = reader.crate_name();
378                let source_root = self.source_roots.get(i).and_then(|r| r.as_deref()).or(self.workspace_root.as_deref());
379                let unit_key = self.unit_keys.get(i).and_then(|u| u.as_deref());
380
381                if multi_reader && (pass == 0 || pass == 1) && !crate_name.is_empty() {
382                    let crate_matched = if pass == 0 { contains_ascii_ci(crate_name.as_bytes(), q_bytes) } else { is_fuzzy_subseq(crate_name, query) };
383                    if crate_matched {
384                        let root_file = reader.get_file(0);
385                        if !root_file.is_empty() && seen.insert((crate_name, root_file, 1u32, 1u32)) {
386                            results.push(WorkspaceSymbol {
387                                crate_name,
388                                name: crate_name,
389                                path: crate_name,
390                                kind: DefKind::Mod,
391                                file: root_file,
392                                span: crate::format::Span::new(0, 1, 1, 1, crate_name.len() as u32 + 1),
393                                signature: None,
394                                is_macro_expansion: false,
395                                source_root,
396                                unit_key,
397                            });
398                            if results.len() >= limit {
399                                return results;
400                            }
401                        }
402                    }
403                }
404
405                for def in reader.definitions() {
406                    let kind = DefKind::from(def.kind);
407                    if is_excluded_ws_kind(kind) {
408                        continue;
409                    }
410                    if !query.is_empty() {
411                        let is_type = is_type_or_mod_ws_kind(kind);
412                        if (pass <= 1 && !is_type) || (pass >= 2 && is_type) {
413                            continue;
414                        }
415                    }
416                    let name = reader.get_str(def.name_offset());
417                    if name.is_empty() {
418                        continue;
419                    }
420                    let path = reader.get_str(def.path_offset());
421                    let matched = if query.is_empty() {
422                        true
423                    } else if pass == 0 || pass == 2 {
424                        contains_ascii_ci(name.as_bytes(), q_bytes)
425                            || (!multi_reader && crate_name.eq_ignore_ascii_case(query) && contains_ascii_ci(path.as_bytes(), q_bytes))
426                            || (is_path_query && path_matches(crate_name, path, query))
427                    } else {
428                        is_fuzzy_subseq(name, query)
429                    };
430                    if !matched {
431                        continue;
432                    }
433                    let span = def.span();
434                    let file = reader.get_file(span.file_id());
435                    if !seen.insert((path, file, span.start_line(), span.start_col())) {
436                        continue;
437                    }
438                    let signature = if def.sig_offset() != 0 { Some(reader.get_str(def.sig_offset())) } else { None };
439                    results.push(WorkspaceSymbol { crate_name, name, path, kind, file, span, signature, is_macro_expansion: def.is_macro_expansion(), source_root, unit_key });
440                    if results.len() >= limit {
441                        return results;
442                    }
443                }
444            }
445        }
446        results
447    }
448}
449
450#[cfg(test)]
451#[path = "workspace_symbol_tests.rs"]
452mod tests;