Skip to main content

ridx_syntax/name_res/
def_map.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//! Crate-wide item and import resolution table (`CrateDefMap`) — `use` trees, globs, re-exports,
12//! `extern crate`, and `std`/`core` edition preludes resolved into [`GlobalDefId`]s.
13
14use std::collections::HashMap;
15use std::sync::Arc;
16
17use super::db::{CrateId, Edition, FileId, GlobalDefId, ItemDb, ItemKind, ModuleId, NsMask, SourceDb, VisKind};
18use super::db_impls::ImplTargetKey;
19use super::def_collect::{collect_crate_items, CollectedCrate, LocalItemData};
20use super::def_solver::ImportSolver;
21use super::ext_scope::ExtScopeCache;
22use super::ident_key::IdentKey;
23use super::impl_collect::LocalImplArena;
24use super::impl_resolve::resolve_local_impls_and_assocs;
25use super::mod_tree::ModuleTree;
26use super::per_ns::{is_binding_visible, BindingOrigin, LocalItemId, PerNs, PrimTy, ResolvedBinding};
27use super::use_tree::{PathAnchor, UseArena};
28use crate::sema_fn::norm_ident;
29use crate::tree::SyntaxTree;
30
31/// Resolved symbol table of one module inside [`CrateDefMap`].
32#[derive(Clone, Debug)]
33pub struct ModuleScope {
34    pub index_def: GlobalDefId,
35    pub entries: HashMap<IdentKey, PerNs>,
36    /// Anonymous trait imports (`use Trait as _;`) visible for method lookup in this module.
37    pub unnamed_traits: Vec<ResolvedBinding>,
38    /// Precomputed in-order visible trait `GlobalDefId`s (`unnamed_traits` + `entries`).
39    pub(super) visible_traits: Arc<[GlobalDefId]>,
40    /// Sorted copy of `visible_traits` for `O(log T)` membership checks.
41    pub(super) visible_traits_sorted: Arc<[GlobalDefId]>,
42    /// Precomputed 64-bit hash of `(visible_traits, has_implicit_prelude)` for `O(1)` trait-item cache lookup.
43    pub visible_traits_hash: u64,
44}
45
46impl Default for ModuleScope {
47    #[inline]
48    fn default() -> Self {
49        let empty: Arc<[GlobalDefId]> = Arc::from([]);
50        Self {
51            index_def: GlobalDefId::NONE,
52            entries: HashMap::new(),
53            unnamed_traits: Vec::new(),
54            visible_traits: Arc::clone(&empty),
55            visible_traits_sorted: empty,
56            visible_traits_hash: 0,
57        }
58    }
59}
60
61impl ModuleScope {
62    #[inline]
63    pub fn get(&self, name: &str) -> PerNs {
64        self.entries.get(name).copied().unwrap_or(PerNs::EMPTY)
65    }
66}
67
68/// Non-fatal import-resolution diagnostics.
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub enum UseDiag {
71    UnresolvedUse { module: ModuleId, use_index: u32 },
72    UnresolvedExternCrate { module: ModuleId, name: String },
73}
74
75/// Complete crate-level definition & import map built without invoking `rustc`.
76#[derive(Debug)]
77pub struct CrateDefMap {
78    pub krate: CrateId,
79    pub edition: Edition,
80    pub prelude_mod: Option<GlobalDefId>,
81    pub prelude: HashMap<IdentKey, PerNs>,
82    pub(super) prelude_traits: Arc<[GlobalDefId]>,
83    pub(super) prelude_traits_sorted: Arc<[GlobalDefId]>,
84    /// Crate-wide extern crate prelude (`name -> (CrateId, root GlobalDefId)`).
85    pub extern_prelude: HashMap<IdentKey, (CrateId, GlobalDefId)>,
86    pub items: Vec<LocalItemData>,
87    pub(super) item_strings: String,
88    pub uses: UseArena,
89    pub scopes: Vec<ModuleScope>,
90    /// Per-`FlatUse` resolved `PerNs` (`resolved_uses[i]` corresponds to `uses.uses[i]`).
91    pub resolved_uses: Vec<PerNs>,
92    pub dirty_files: Vec<FileId>,
93    /// `true` when non-dirty crate definitions come from a pre-indexed `ItemDb` (`build_from_index`).
94    pub indexed_clean: bool,
95    pub mod_tree: Arc<ModuleTree>,
96    pub macro_bodies: Vec<(LocalItemId, u32, u32)>,
97    pub local_impls: LocalImplArena,
98    pub(super) local_alias_targets: HashMap<GlobalDefId, ImplTargetKey>,
99    pub diagnostics: Vec<UseDiag>,
100}
101
102impl CrateDefMap {
103    /// Builds the `CrateDefMap` for `mod_tree` with no dirty-file overrides.
104    pub fn build(db: &dyn ItemDb, sources: &dyn SourceDb, mod_tree: &ModuleTree) -> Self {
105        Self::build_cached(db, sources, mod_tree, &[], |_| None)
106    }
107
108    /// Builds the `CrateDefMap` reusing pre-parsed [`SyntaxTree`]s and honoring `dirty_files`.
109    pub fn build_cached<'t>(
110        db: &dyn ItemDb,
111        sources: &dyn SourceDb,
112        mod_tree: &ModuleTree,
113        dirty_files: &[FileId],
114        get_tree: impl FnMut(FileId) -> Option<&'t SyntaxTree<'t>>,
115    ) -> Self {
116        let collected = collect_crate_items(db, sources, mod_tree, dirty_files, get_tree);
117        let mut ext_cache = ExtScopeCache::new();
118        Self::from_collected(db, mod_tree, collected, dirty_files, &mut ext_cache)
119    }
120
121    pub(super) fn from_collected(db: &dyn ItemDb, mod_tree: &ModuleTree, collected: CollectedCrate, dirty_files: &[FileId], ext_cache: &mut ExtScopeCache) -> Self {
122        let next_seq = collected.next_overlay_seq;
123        let has_local_impls = !collected.local_impls.impls.is_empty() || !collected.local_impls.trait_assocs.is_empty() || !collected.local_impls.type_aliases.is_empty();
124        let mut map = ImportSolver::solve(db, mod_tree, collected, dirty_files, ext_cache);
125        if has_local_impls {
126            resolve_local_impls_and_assocs(&mut map, db, mod_tree, ext_cache, next_seq);
127        }
128        map
129    }
130
131    #[inline]
132    pub fn scope(&self, module: ModuleId) -> &ModuleScope {
133        &self.scopes[module.0 as usize]
134    }
135
136    #[inline]
137    pub fn item(&self, id: LocalItemId) -> &LocalItemData {
138        &self.items[id.0 as usize]
139    }
140
141    #[inline]
142    pub fn item_name(&self, id: LocalItemId) -> &str {
143        let it = self.item(id);
144        &self.item_strings[it.name_start as usize..it.name_end as usize]
145    }
146
147    /// Returns the raw `{ ... }` body text of a locally defined `macro_rules!` (`ItemKind::Macro`).
148    #[inline]
149    pub fn local_macro_body(&self, id: LocalItemId) -> Option<&str> {
150        let idx = self.macro_bodies.binary_search_by_key(&id, |&(lid, ..)| lid).ok()?;
151        let (_, bs, be) = self.macro_bodies[idx];
152        Some(&self.item_strings[bs as usize..be as usize])
153    }
154
155    /// Resolves an unqualified single-segment identifier `raw_name` inside `module` across all
156    /// namespaces (`module scope -> edition prelude -> extern crate prelude (2018+) -> primitives`).
157    pub fn resolve_name_in_module(&self, mod_tree: &ModuleTree, module: ModuleId, raw_name: &str) -> PerNs {
158        let name = norm_ident(raw_name);
159        let mut res = self.scope(module).get(name).filter_visible(mod_tree, module);
160
161        if !mod_tree.module(module).has_no_implicit_prelude() {
162            if let Some(&pre) = self.prelude.get(name) {
163                res = res.or_else_ns(pre);
164            }
165        }
166        if self.edition.has_uniform_paths() && res.types.is_none() {
167            if let Some(&(ext_krate, ext_root)) = self.extern_prelude.get(name) {
168                res.types = Some(extern_crate_binding(ext_krate, self.krate, ext_root));
169            }
170        }
171        if res.types.is_none() {
172            if let Some(p) = PrimTy::from_name(name) {
173                res.types = Some(ResolvedBinding::primitive(p, VisKind::Public, ModuleId::NONE, BindingOrigin::Builtin));
174            }
175        }
176        res
177    }
178
179    /// Resolves a multi-segment path `(anchor, segments)` from `module` across local modules,
180    /// re-exports, globs, external dependency crates, enum variants, and builtin primitives.
181    pub fn resolve_path(&self, db: &dyn ItemDb, mod_tree: &ModuleTree, module: ModuleId, anchor: PathAnchor, segments: &[&str]) -> PerNs {
182        let mut ext_cache = ExtScopeCache::new();
183        self.resolve_path_with_cache(db, mod_tree, &mut ext_cache, module, anchor, segments)
184    }
185
186    /// Same as [`Self::resolve_path`], reusing a caller-owned [`ExtScopeCache`] across bulk queries.
187    pub fn resolve_path_with_cache(&self, db: &dyn ItemDb, mod_tree: &ModuleTree, ext_cache: &mut ExtScopeCache, module: ModuleId, anchor: PathAnchor, segments: &[&str]) -> PerNs {
188        ImportSolver::resolve_arbitrary_path(self, db, mod_tree, ext_cache, module, anchor, segments)
189    }
190
191    /// Collects all traits in scope inside `module` (explicit/glob named traits, `use Trait as _;`,
192    /// and standard prelude traits when implicit prelude is active) in deterministic order.
193    pub fn traits_in_scope(&self, mod_tree: &ModuleTree, module: ModuleId) -> Vec<ResolvedBinding> {
194        let sc = self.scope(module);
195        let mut out: Vec<ResolvedBinding> = Vec::with_capacity(sc.unnamed_traits.len() + 16);
196        out.extend(sc.unnamed_traits.iter().copied());
197        let mut named: Vec<(&str, ResolvedBinding)> = Vec::with_capacity(sc.entries.len());
198        for (k, pns) in &sc.entries {
199            if let Some(t) = pns.types.filter(|t| !t.ambiguous && t.kind == ItemKind::Trait) {
200                named.push((k.as_str(), t));
201            }
202        }
203        named.sort_unstable_by(|a, b| a.0.cmp(b.0));
204        for (_, t) in named {
205            if !out.iter().any(|x| x.same_target(t)) {
206                out.push(t);
207            }
208        }
209        if !mod_tree.module(module).has_no_implicit_prelude() {
210            let mut prel: Vec<(&str, ResolvedBinding)> = Vec::with_capacity(self.prelude.len());
211            for (k, pns) in &self.prelude {
212                if let Some(t) = pns.types.filter(|t| t.kind == ItemKind::Trait) {
213                    prel.push((k.as_str(), t));
214                }
215            }
216            prel.sort_unstable_by(|a, b| a.0.cmp(b.0));
217            for (_, t) in prel {
218                if !out.iter().any(|x| x.same_target(t)) {
219                    out.push(t);
220                }
221            }
222        }
223        out
224    }
225}
226
227#[inline]
228pub(super) fn extern_crate_binding(target_krate: CrateId, self_krate: CrateId, root_def: GlobalDefId) -> ResolvedBinding {
229    ResolvedBinding {
230        def: root_def,
231        local: LocalItemId::NONE,
232        local_mod: if target_krate == self_krate { ModuleId::ROOT } else { ModuleId::NONE },
233        vis_mod: ModuleId::NONE,
234        kind: ItemKind::Mod,
235        vis: VisKind::Public,
236        origin: BindingOrigin::ExternPrelude,
237        prim_ty: 0,
238        ambiguous: false,
239    }
240}
241
242#[inline]
243pub(super) fn local_mod_binding(mod_id: ModuleId, index_def: GlobalDefId, vis: VisKind, vis_mod: ModuleId) -> PerNs {
244    let b = ResolvedBinding {
245        def: index_def,
246        local: LocalItemId::NONE,
247        local_mod: mod_id,
248        vis_mod,
249        kind: ItemKind::Mod,
250        vis,
251        origin: BindingOrigin::Explicit,
252        prim_ty: 0,
253        ambiguous: false,
254    };
255    PerNs::from_binding(b, NsMask::TYPE)
256}
257
258pub(super) fn finalize_in_scope_trait_tables(map: &mut CrateDefMap, mod_tree: &ModuleTree) {
259    let mut prel = Vec::with_capacity(map.prelude.len());
260    for pns in map.prelude.values() {
261        if let Some(tb) = pns.types.filter(|b| b.kind == ItemKind::Trait && b.def.is_some()) {
262            prel.push(tb.def);
263        }
264    }
265    prel.sort_unstable();
266    prel.dedup();
267    let prel_arc: Arc<[GlobalDefId]> = prel.into();
268    map.prelude_traits = Arc::clone(&prel_arc);
269    map.prelude_traits_sorted = prel_arc;
270
271    let mut named_buf = Vec::new();
272    for (midx, sc) in map.scopes.iter_mut().enumerate() {
273        finalize_module_trait_table(sc, mod_tree, ModuleId(midx as u32), &mut named_buf);
274    }
275}
276
277pub(super) fn finalize_nonleaf_trait_tables(map: &mut CrateDefMap, mod_tree: &ModuleTree) {
278    let mut prel = Vec::with_capacity(map.prelude.len());
279    for pns in map.prelude.values() {
280        if let Some(tb) = pns.types.filter(|b| b.kind == ItemKind::Trait && b.def.is_some()) {
281            prel.push(tb.def);
282        }
283    }
284    prel.sort_unstable();
285    prel.dedup();
286    let prel_arc: Arc<[GlobalDefId]> = prel.into();
287    map.prelude_traits = Arc::clone(&prel_arc);
288    map.prelude_traits_sorted = prel_arc;
289
290    let mut named_buf = Vec::new();
291    for (midx, sc) in map.scopes.iter_mut().enumerate() {
292        let mid = ModuleId(midx as u32);
293        if midx == 0 || !mod_tree.children(mid).is_empty() {
294            finalize_module_trait_table(sc, mod_tree, mid, &mut named_buf);
295        }
296    }
297}
298
299pub(super) fn finalize_module_trait_table(sc: &mut ModuleScope, mod_tree: &ModuleTree, from_mod: ModuleId, named_buf: &mut Vec<GlobalDefId>) {
300    let mut vis_list = Vec::with_capacity(sc.unnamed_traits.len() + 16);
301    for tb in &sc.unnamed_traits {
302        if tb.def.is_some() && !vis_list.contains(&tb.def) {
303            vis_list.push(tb.def);
304        }
305    }
306    named_buf.clear();
307    for pns in sc.entries.values() {
308        if let Some(tb) = pns.types.filter(|&b| b.kind == ItemKind::Trait && b.def.is_some() && is_binding_visible(mod_tree, b, from_mod)) {
309            named_buf.push(tb.def);
310        }
311    }
312    named_buf.sort_unstable();
313    named_buf.dedup();
314    for &tdef in &*named_buf {
315        if !vis_list.contains(&tdef) {
316            vis_list.push(tdef);
317        }
318    }
319    let mut sorted = vis_list.clone();
320    sorted.sort_unstable();
321    sorted.dedup();
322    let include_prelude = !mod_tree.module(from_mod).has_no_implicit_prelude();
323    let mut h: u64 = if include_prelude { 0xcbf2_9ce4_8422_2325 } else { 0x8422_2325_cbf2_9ce4 };
324    for &d in &vis_list {
325        let word = ((d.krate.0 as u64) << 32) | (d.index as u64);
326        h = (h ^ word).wrapping_mul(0x0000_0100_0000_01b3);
327    }
328    sc.visible_traits = vis_list.into();
329    sc.visible_traits_sorted = sorted.into();
330    sc.visible_traits_hash = h;
331}