Skip to main content

ridx_format/workspace/navigation/
exact_symbols.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
11//! Per-workspace O(1) exact short-name symbol index for low-latency code actions and quickfixes.
12
13use super::*;
14use std::collections::{HashMap, HashSet};
15use std::sync::{Arc, Mutex, OnceLock};
16
17type CacheKey = (u64, u64, usize);
18
19struct ExactSymbolCache {
20    by_name: HashMap<String, Vec<(u32, u32)>>,
21}
22
23static EXACT_SYMBOL_CACHE: OnceLock<Mutex<HashMap<CacheKey, Arc<ExactSymbolCache>>>> = OnceLock::new();
24
25impl ExactSymbolCache {
26    fn get(ws: &WorkspaceIndex) -> Arc<Self> {
27        let key = (ws.instance_id, ws.generation, ws.readers.len());
28        let mutex = EXACT_SYMBOL_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
29        if let Some(existing) = mutex.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
30            return Arc::clone(existing);
31        }
32        let built = Arc::new(Self::build(ws));
33        let mut guard = mutex.lock().unwrap_or_else(|e| e.into_inner());
34        guard.retain(|&(inst, gen, _), _| inst != ws.instance_id || gen == ws.generation);
35        guard.insert(key, Arc::clone(&built));
36        built
37    }
38
39    fn build(ws: &WorkspaceIndex) -> Self {
40        let mut by_name: HashMap<String, Vec<(u32, u32)>> = HashMap::new();
41        for (ri, reader) in ws.readers.iter().enumerate() {
42            for (di, def) in reader.definitions().iter().enumerate() {
43                if def.kind == DefKind::TyParam as u8 {
44                    continue;
45                }
46                let raw_name = reader.get_str(def.name_offset());
47                let bare = raw_name.strip_prefix("r#").unwrap_or(raw_name);
48                if !bare.is_empty() {
49                    by_name.entry(bare.to_string()).or_default().push((ri as u32, di as u32));
50                }
51            }
52        }
53        Self { by_name }
54    }
55}
56
57impl WorkspaceIndex {
58    /// O(1) exact bare-identifier lookup across all indexed definitions (including dependencies).
59    pub fn exact_symbols_by_name<'a>(&'a self, ident: &str) -> Vec<WorkspaceSymbol<'a>> {
60        self.exact_symbols_filtered(ident, |_| true)
61    }
62
63    /// O(1) exact bare-identifier lookup across local (non-dependency) workspace definitions.
64    pub fn exact_local_symbols_by_name<'a>(&'a self, ident: &str) -> Vec<WorkspaceSymbol<'a>> {
65        self.exact_symbols_filtered(ident, |ri| !self.reader_is_dependency.get(ri).copied().unwrap_or(false))
66    }
67
68    /// O(1) exact bare-identifier lookup filtered by shard reader index.
69    pub fn exact_symbols_filtered<'a, F>(&'a self, ident: &str, mut filter: F) -> Vec<WorkspaceSymbol<'a>>
70    where
71        F: FnMut(usize) -> bool,
72    {
73        let bare = ident.strip_prefix("r#").unwrap_or(ident);
74        if bare.is_empty() {
75            return Vec::new();
76        }
77        let cache = ExactSymbolCache::get(self);
78        let Some(entries) = cache.by_name.get(bare) else {
79            return Vec::new();
80        };
81        let mut matches = Vec::with_capacity(entries.len());
82        let mut seen = HashSet::new();
83        for &(ri_u32, di_u32) in entries {
84            let ri = ri_u32 as usize;
85            if !filter(ri) {
86                continue;
87            }
88            let Some(reader) = self.readers.get(ri) else { continue };
89            let Some(def) = reader.definitions().get(di_u32 as usize) else { continue };
90            let name = reader.get_str(def.name_offset());
91            let path = reader.get_str(def.path_offset());
92            let span = def.span();
93            let file = reader.get_file(span.file_id());
94            if !seen.insert((path, file, span.start_line(), span.start_col())) {
95                continue;
96            }
97            let signature = if def.sig_offset() != 0 { Some(reader.get_str(def.sig_offset())) } else { None };
98            let source_root = self.source_roots.get(ri).and_then(|r| r.as_deref()).or(self.workspace_root.as_deref());
99            let unit_key = self.unit_keys.get(ri).and_then(|u| u.as_deref());
100            matches.push(WorkspaceSymbol {
101                crate_name: reader.crate_name(),
102                name,
103                path,
104                kind: DefKind::from(def.kind),
105                file,
106                span,
107                signature,
108                is_macro_expansion: def.is_macro_expansion(),
109                source_root,
110                unit_key,
111            });
112        }
113        matches
114    }
115}