Skip to main content

ridx_syntax/name_res/
path_res.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//! File-level expression, type, pattern, and `use`-tree path resolution (`FileNameRes`, `ResolvedRef`,
12//! `ResTarget`, `LocalBindData`, `GenericBindData`).
13
14use std::sync::Arc;
15
16use super::body_ribs::RibStack;
17use super::body_walk::FileResolver;
18use super::crate_snapshot::CrateSnapshot;
19use super::db::{FileId, GlobalDefId, ItemDb, ItemKind, ModuleId, SourceDb};
20use super::db_impls::ImplTargetKey;
21use super::def_map::CrateDefMap;
22use super::ext_scope::ExtScopeCache;
23use super::mod_tree::ModuleTree;
24use super::per_ns::{LocalItemId, PrimTy};
25use crate::parser::parse;
26use crate::tree::{NodeId, SyntaxTree};
27
28/// Dense index into [`FileNameRes::locals`] (`u32::MAX` = absent sentinel).
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
30pub struct LocalBindId(pub u32);
31
32impl LocalBindId {
33    pub const NONE: Self = Self(u32::MAX);
34
35    #[inline]
36    pub const fn is_some(self) -> bool {
37        self.0 != u32::MAX
38    }
39}
40
41impl Default for LocalBindId {
42    #[inline]
43    fn default() -> Self {
44        Self::NONE
45    }
46}
47
48/// Dense index into [`FileNameRes::generics`] (`u32::MAX` = absent sentinel).
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
50pub struct GenericBindId(pub u32);
51
52impl GenericBindId {
53    pub const NONE: Self = Self(u32::MAX);
54
55    #[inline]
56    pub const fn is_some(self) -> bool {
57        self.0 != u32::MAX
58    }
59}
60
61impl Default for GenericBindId {
62    #[inline]
63    fn default() -> Self {
64        Self::NONE
65    }
66}
67
68/// Declaration record of one local value binding (`self`, parameter, `let`, `match`, `for`, closure).
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub struct LocalBindData {
71    pub id: LocalBindId,
72    pub decl_node: NodeId,
73    pub name_start: u32,
74    pub name_end: u32,
75    pub is_self: bool,
76    pub is_mut: bool,
77}
78
79impl LocalBindData {
80    #[inline]
81    pub fn name<'s>(&self, src: &'s str) -> &'s str {
82        &src[self.name_start as usize..self.name_end as usize]
83    }
84}
85
86/// Declaration record of one generic `T` (`is_const = false`) or `const N: Ty` (`is_const = true`) parameter.
87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88pub struct GenericBindData {
89    pub id: GenericBindId,
90    pub def: GlobalDefId,
91    pub owner_node: NodeId,
92    pub owner_def: GlobalDefId,
93    pub decl_node: NodeId,
94    pub name_start: u32,
95    pub name_end: u32,
96    pub index: u16,
97    pub is_const: bool,
98}
99
100impl GenericBindData {
101    #[inline]
102    pub fn name<'s>(&self, src: &'s str) -> &'s str {
103        &src[self.name_start as usize..self.name_end as usize]
104    }
105}
106
107/// Syntactic role of a resolved path or identifier site.
108#[repr(u8)]
109#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
110pub enum PathCtx {
111    Expr = 0,
112    RecordExpr = 1,
113    Type = 2,
114    TypeArg = 3,
115    TypeBound = 4,
116    PatValue = 5,
117    PatRecord = 6,
118    UseTree = 7,
119    MacroCall = 8,
120}
121
122/// Semantic target of a resolved identifier / path segment.
123#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
124pub enum ResTarget {
125    /// Module, ADT, variant, function, associated item, field, const, static, type alias, or macro.
126    Def { def: GlobalDefId, local: LocalItemId, kind: ItemKind },
127    /// Local variable or `self` parameter declared in the enclosing body.
128    Local(LocalBindId),
129    /// Generic type parameter (`!is_const`) or const generic parameter (`is_const`).
130    Generic(GenericBindId),
131    /// `Self` inside an `impl` (`target` known) or `trait` (`trait_def` known).
132    SelfTy { target: ImplTargetKey, trait_def: GlobalDefId },
133    /// Builtin primitive type (`u32`, `str`, `bool`, ...).
134    Prim(PrimTy),
135}
136
137impl ResTarget {
138    /// Returns the underlying [`GlobalDefId`] when this target names a concrete definition
139    /// (including `Self` inside `impl Adt`, which maps to `adt_def` just like `rustc`'s `SelfTyAlias`).
140    #[inline]
141    pub const fn effective_def_id(self) -> Option<GlobalDefId> {
142        match self {
143            Self::Def { def, .. } if def.is_some() => Some(def),
144            Self::SelfTy { target: ImplTargetKey::Adt(adt_def), .. } if adt_def.is_some() => Some(adt_def),
145            _ => None,
146        }
147    }
148
149    #[inline]
150    pub fn effective_def_id_in(self, file_res: &FileNameRes) -> Option<GlobalDefId> {
151        match self {
152            Self::Generic(gid) => {
153                let d = file_res.generic_data(gid).def;
154                d.is_some().then_some(d)
155            }
156            other => other.effective_def_id(),
157        }
158    }
159
160    #[inline]
161    pub const fn is_local(self) -> bool {
162        matches!(self, Self::Local(_))
163    }
164}
165
166/// One resolved reference span `[start..end)` inside a file.
167#[derive(Clone, Copy, Debug, PartialEq, Eq)]
168pub struct ResolvedRef {
169    pub start: u32,
170    pub end: u32,
171    /// Enclosing `K::Path` node (`NodeId(u32::MAX)` for bare `IdentPat`, `RecordField`, `Use`, or `TokenTree` refs).
172    pub path_node: NodeId,
173    pub target: ResTarget,
174    pub ctx: PathCtx,
175    pub is_segment_tail: bool,
176}
177
178/// Reusable output table of all resolved paths, locals, and generic parameters in one `.rs` file.
179#[derive(Clone, Debug, Default)]
180pub struct FileNameRes {
181    pub file: FileId,
182    pub refs: Vec<ResolvedRef>,
183    pub locals: Vec<LocalBindData>,
184    pub generics: Vec<GenericBindData>,
185    pub prelude_traits: Arc<[GlobalDefId]>,
186    pub mod_trait_scopes: Vec<(NodeId, NodeId, Arc<[GlobalDefId]>, bool)>,
187    pub block_trait_imports: Vec<(NodeId, NodeId, GlobalDefId)>,
188    pub self_trait_scopes: Vec<(NodeId, NodeId, GlobalDefId)>,
189    pub param_trait_bounds: Vec<(GenericBindId, GlobalDefId)>,
190    pub(super) ribs: RibStack,
191}
192
193impl FileNameRes {
194    pub fn new() -> Self {
195        Self::default()
196    }
197
198    #[inline]
199    pub fn swap_scratch(&mut self, other: &mut Self) {
200        core::mem::swap(&mut self.ribs, &mut other.ribs);
201    }
202
203    #[inline]
204    pub fn clear(&mut self) {
205        self.file = FileId::NONE;
206        self.refs.clear();
207        self.locals.clear();
208        self.generics.clear();
209        self.mod_trait_scopes.clear();
210        self.block_trait_imports.clear();
211        self.self_trait_scopes.clear();
212        self.param_trait_bounds.clear();
213        self.ribs.clear();
214    }
215
216    /// Appends all traits visible for method resolution at `node` into `out` (`0` heap allocations when warm).
217    pub fn collect_traits_in_scope_at(&self, node: NodeId, out: &mut Vec<GlobalDefId>) {
218        out.clear();
219        for &(s, e, tdef) in &self.self_trait_scopes {
220            if node.0 >= s.0 && node.0 < e.0 && tdef.is_some() && !out.contains(&tdef) {
221                out.push(tdef);
222            }
223        }
224        for &(s, e, tdef) in self.block_trait_imports.iter().rev() {
225            if node.0 >= s.0 && node.0 < e.0 && tdef.is_some() && !out.contains(&tdef) {
226                out.push(tdef);
227            }
228        }
229        let mut include_prelude = true;
230        if let Some((_, _, vis, inc)) = self.mod_trait_scopes.iter().rfind(|&&(s, e, _, _)| node.0 >= s.0 && node.0 < e.0) {
231            include_prelude = *inc;
232            for &tdef in vis.iter() {
233                if tdef.is_some() && !out.contains(&tdef) {
234                    out.push(tdef);
235                }
236            }
237        }
238        if include_prelude {
239            for &tdef in self.prelude_traits.iter() {
240                if tdef.is_some() && !out.contains(&tdef) {
241                    out.push(tdef);
242                }
243            }
244        }
245    }
246
247    /// Returns `true` if any inner `impl Trait`, block `use Trait`, or inline `mod` begins or ends inside `(start..end)`.
248    #[inline]
249    pub fn has_inner_trait_scopes(&self, start: NodeId, end: u32) -> bool {
250        let s0 = start.0;
251        self.block_trait_imports.iter().any(|&(s, e, _)| (s.0 > s0 && s.0 < end) || (e.0 > s0 && e.0 < end))
252            || self.self_trait_scopes.iter().any(|&(s, e, _)| (s.0 > s0 && s.0 < end) || (e.0 > s0 && e.0 < end))
253            || self.mod_trait_scopes.iter().any(|(s, e, _, _)| (s.0 > s0 && s.0 < end) || (e.0 > s0 && e.0 < end))
254    }
255
256    pub(super) fn finalize(&mut self) {
257        self.refs.sort_unstable_by_key(|a| (a.start, a.end, a.target, !a.is_segment_tail, a.path_node.0, a.ctx));
258        self.refs.dedup_by(|b, a| a.start == b.start && a.end == b.end && a.target == b.target);
259    }
260
261    /// Binary-searches for a reference covering `byte_offset` (`start <= byte_offset < end`).
262    pub fn ref_at_offset(&self, byte_offset: u32) -> Option<&ResolvedRef> {
263        let idx = self.refs.partition_point(|r| r.start <= byte_offset);
264        self.refs[..idx].iter().rfind(|r| byte_offset < r.end)
265    }
266
267    /// Returns all resolved references with exact byte span `[start..end)`.
268    pub fn refs_at_span(&self, start: u32, end: u32) -> &[ResolvedRef] {
269        let lo = self.refs.partition_point(|r| (r.start, r.end) < (start, end));
270        let hi = self.refs[lo..].partition_point(|r| r.start == start && r.end == end);
271        &self.refs[lo..lo + hi]
272    }
273
274    /// Returns the tail segment resolution of `path_node` (`K::Path`), if resolved.
275    pub fn path_tail_ref(&self, path_node: NodeId) -> Option<&ResolvedRef> {
276        self.refs.iter().find(|r| r.path_node == path_node && r.is_segment_tail)
277    }
278
279    /// `O(log N)` tail-segment resolution lookup bounded by `path_node`'s CST byte range.
280    #[inline]
281    pub fn path_tail_ref_in_st(&self, st: &SyntaxTree<'_>, path_node: NodeId) -> Option<&ResolvedRef> {
282        let nr = st.range(path_node);
283        let lo = self.refs.partition_point(|r| r.start < nr.start as u32);
284        let hi = lo + self.refs[lo..].partition_point(|r| r.start <= nr.end as u32);
285        self.refs[lo..hi].iter().find(|r| r.path_node == path_node && r.is_segment_tail).or_else(|| {
286            let te = st.children(path_node).filter(|&c| st.kind(c) == crate::syntax_kind::SyntaxKind::PathSegment).last().map_or(nr.end as u32, |s| st.range(s).end as u32);
287            self.refs[lo..hi].iter().rfind(|r| r.path_node == NodeId(u32::MAX) && r.is_segment_tail && r.end == te)
288        })
289    }
290
291    /// `O(log N)` slice of references starting inside `[start..=end]`.
292    #[inline]
293    pub fn refs_starting_in(&self, start: u32, end: u32) -> &[ResolvedRef] {
294        let lo = self.refs.partition_point(|r| r.start < start);
295        let hi = lo + self.refs[lo..].partition_point(|r| r.start <= end);
296        &self.refs[lo..hi]
297    }
298
299    #[inline]
300    pub fn local_data(&self, id: LocalBindId) -> &LocalBindData {
301        &self.locals[id.0 as usize]
302    }
303
304    #[inline]
305    pub fn generic_data(&self, id: GenericBindId) -> &GenericBindData {
306        &self.generics[id.0 as usize]
307    }
308
309    /// Iterates over every reference resolving to `local_id` in source order.
310    pub fn local_uses(&self, local_id: LocalBindId) -> impl Iterator<Item = &ResolvedRef> {
311        self.refs.iter().filter(move |r| r.target == ResTarget::Local(local_id))
312    }
313}
314
315impl CrateDefMap {
316    /// Parses `file` from `sources` and resolves all expressions, types, patterns, and `use` paths in `file`.
317    pub fn resolve_file_paths(&self, db: &dyn ItemDb, sources: &dyn SourceDb, mod_tree: &ModuleTree, file: FileId) -> FileNameRes {
318        let st = parse(sources.file_text(file));
319        let mut ext_cache = ExtScopeCache::new();
320        let mut out = FileNameRes::new();
321        self.resolve_file_paths_into(db, mod_tree, &mut ext_cache, file, &st, &mut out);
322        out
323    }
324
325    /// Resolves all paths in pre-parsed `st` for `file` into caller-reusable `out` (retaining `Vec` capacities).
326    pub fn resolve_file_paths_into(&self, db: &dyn ItemDb, mod_tree: &ModuleTree, ext_cache: &mut ExtScopeCache, file: FileId, st: &SyntaxTree<'_>, out: &mut FileNameRes) {
327        out.clear();
328        out.file = file;
329        let ribs = std::mem::take(&mut out.ribs);
330        let mut resolver = FileResolver::new(self, db, mod_tree, ext_cache, file, st, out, ribs);
331        resolver.walk_file();
332        let ribs = resolver.ribs;
333        out.ribs = ribs;
334        out.finalize();
335    }
336
337    /// Resolves only the ancestor chain and body of `target_fn` inside `st`, pruning sibling items (`0` warm allocs).
338    #[allow(clippy::too_many_arguments)]
339    pub fn resolve_fn_paths_into(
340        &self,
341        db: &dyn ItemDb,
342        mod_tree: &ModuleTree,
343        ext_cache: &mut ExtScopeCache,
344        file: FileId,
345        st: &SyntaxTree<'_>,
346        target_fn: NodeId,
347        out: &mut FileNameRes,
348    ) {
349        out.clear();
350        out.file = file;
351        let ribs = std::mem::take(&mut out.ribs);
352        let mut resolver = FileResolver::new(self, db, mod_tree, ext_cache, file, st, out, ribs);
353        resolver.target_range = Some((target_fn.0, st.node(target_fn).subtree_end));
354        resolver.walk_file();
355        let ribs = resolver.ribs;
356        out.ribs = ribs;
357        out.finalize();
358    }
359
360    pub(crate) fn resolve_module_snippet_into(&self, db: &dyn ItemDb, module: ModuleId, file: FileId, st: &SyntaxTree<'_>, out: &mut FileNameRes) {
361        out.clear();
362        out.file = file;
363        let mut ext_cache = ExtScopeCache::new();
364        let ribs = std::mem::take(&mut out.ribs);
365        let mut resolver = FileResolver::new(self, db, &self.mod_tree, &mut ext_cache, file, st, out, ribs);
366        resolver.cur_mod = module;
367        resolver.walk_file();
368        out.ribs = resolver.ribs;
369        out.finalize();
370    }
371}
372
373impl CrateSnapshot {
374    /// Resolves all paths in `st` for clean `file` reusing the snapshot's warm [`ExtScopeCache`].
375    pub fn resolve_file_paths_into(&self, db: &dyn ItemDb, file: FileId, st: &SyntaxTree<'_>, out: &mut FileNameRes) {
376        let mut ext_c = self.ext_cache.borrow_mut();
377        self.clean_def_map.resolve_file_paths_into(db, &self.mod_tree, &mut ext_c, file, st, out);
378    }
379
380    /// Resolves only `target_fn`'s ancestor chain and body inside `st`, reusing the snapshot's warm [`ExtScopeCache`].
381    pub fn resolve_fn_paths_into(&self, db: &dyn ItemDb, file: FileId, st: &SyntaxTree<'_>, target_fn: NodeId, out: &mut FileNameRes) {
382        let mut ext_c = self.ext_cache.borrow_mut();
383        self.clean_def_map.resolve_fn_paths_into(db, &self.mod_tree, &mut ext_c, file, st, target_fn, out);
384    }
385
386    /// Resolves all paths in `st` for `file` against a dirty overlay `def_map` (and optional `new_mod_tree`),
387    /// reusing the snapshot's warm [`ExtScopeCache`].
388    pub fn resolve_dirty_file_paths_into(
389        &self,
390        db: &dyn ItemDb,
391        new_mod_tree: Option<&ModuleTree>,
392        def_map: &CrateDefMap,
393        file: FileId,
394        st: &SyntaxTree<'_>,
395        out: &mut FileNameRes,
396    ) {
397        let mut ext_c = self.ext_cache.borrow_mut();
398        def_map.resolve_file_paths_into(db, new_mod_tree.unwrap_or(&self.mod_tree), &mut ext_c, file, st, out);
399    }
400}