Skip to main content

ridx_syntax/name_res/
def_collect.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//! Module-tree CST walker for [`super::def_map::CrateDefMap`] (per-item extraction helpers live in
12//! [`super::def_collect_items`]).
13
14use super::attr::eval_outer_attrs;
15use super::db::{CrateId, FileId, GlobalDefId, IndexedDef, ItemDb, ItemKind, ModuleId, SourceDb, VisKind};
16use super::impl_collect::LocalImplArena;
17use super::mbe_expand::MAX_MBE_DEPTH;
18use super::mbe_parse::MacroRulesDef;
19use super::mod_tree::{ModuleTree, MOD_FLAG_MACRO_USE};
20use super::per_ns::LocalItemId;
21use super::use_tree::UseArena;
22use crate::parser::parse;
23use crate::sema_fn::norm_ident;
24use crate::syntax_kind::SyntaxKind as K;
25use crate::token::Token;
26use crate::tree::{NodeId, SyntaxTree};
27
28/// Compact descriptor of one locally defined item (or enum variant) inside [`super::def_map::CrateDefMap`].
29#[derive(Clone, Copy, Debug)]
30pub struct LocalItemData {
31    pub id: LocalItemId,
32    pub module: ModuleId,
33    pub file: FileId,
34    /// Owning `LocalItemId` when `kind == ItemKind::Variant`, otherwise `LocalItemId::NONE`.
35    pub parent_enum: LocalItemId,
36    /// Matched compiler `GlobalDefId` from `ItemDb` (`GlobalDefId::NONE` for brand-new unindexed items).
37    pub index_def: GlobalDefId,
38    pub(super) name_start: u32,
39    pub(super) name_end: u32,
40    pub kind: ItemKind,
41    pub vis: VisKind,
42    pub vis_mod: ModuleId,
43    pub has_value_ctor: bool,
44    pub macro_export: bool,
45    pub var_start: u32,
46    pub var_len: u16,
47    pub span_start: u32,
48    pub span_end: u32,
49}
50
51#[derive(Clone, Debug)]
52pub(super) struct CollectedCrate {
53    pub mod_index_defs: Vec<GlobalDefId>,
54    pub items: Vec<LocalItemData>,
55    pub strings: String,
56    pub uses: UseArena,
57    /// Per-module `#[macro_use]` / local textual macros visible inside that module.
58    pub textual_macros: Vec<Vec<(LocalItemId, GlobalDefId)>>,
59    pub macro_bodies: Vec<(LocalItemId, u32, u32)>,
60    pub local_impls: LocalImplArena,
61    pub scan_all_impls: bool,
62    pub next_overlay_seq: u32,
63}
64
65pub(super) type MacroScopeVec = Vec<(String, usize, LocalItemId, GlobalDefId)>;
66
67pub(super) fn collect_crate_items<'t>(
68    db: &dyn ItemDb,
69    sources: &dyn SourceDb,
70    mod_tree: &ModuleTree,
71    dirty_files: &[FileId],
72    mut get_tree: impl FnMut(FileId) -> Option<&'t SyntaxTree<'t>>,
73) -> CollectedCrate {
74    let mod_count = mod_tree.modules.len();
75    let mod_index_defs = match_module_index_defs(db, mod_tree);
76    let scan_all_impls = if db.crate_root_def(mod_tree.krate).is_some() {
77        false
78    } else {
79        let mut ci = Vec::new();
80        db.crate_impls(mod_tree.krate, &mut ci);
81        ci.is_empty()
82    };
83
84    let mut coll = Collector {
85        db,
86        sources,
87        krate: mod_tree.krate,
88        mod_tree,
89        dirty_files,
90        scan_all_impls,
91        out: CollectedCrate {
92            mod_index_defs,
93            items: Vec::with_capacity(mod_count * 8),
94            strings: String::with_capacity(mod_count * 64),
95            uses: UseArena::with_capacity(mod_count * 4),
96            textual_macros: vec![Vec::new(); mod_count],
97            macro_bodies: Vec::new(),
98            local_impls: LocalImplArena::default(),
99            scan_all_impls,
100            next_overlay_seq: 0,
101        },
102        macro_defs: Vec::new(),
103        in_flight_includes: Vec::new(),
104        scratch_idx_defs: Vec::new(),
105        scratch_var_defs: Vec::new(),
106        scratch_toks: Vec::with_capacity(64),
107        scratch_prefix: Vec::with_capacity(16),
108    };
109
110    let mut macro_env = MacroScopeVec::new();
111    coll.walk_module(ModuleId::ROOT, &mut get_tree, None, &mut macro_env);
112    assign_overlay_item_ids(&mut coll.out);
113    coll.out
114}
115
116pub(super) fn assign_overlay_item_ids(out: &mut CollectedCrate) {
117    let mut seq = out.next_overlay_seq;
118    for it in &mut out.items {
119        if it.module.is_some() && !it.index_def.is_some() {
120            it.index_def = GlobalDefId::new(CrateId::LOCAL_OVERLAY, seq);
121            seq += 1;
122        }
123    }
124    out.next_overlay_seq = seq;
125}
126
127fn match_module_index_defs(db: &dyn ItemDb, tree: &ModuleTree) -> Vec<GlobalDefId> {
128    let n = tree.modules.len();
129    let mut out = vec![GlobalDefId::NONE; n];
130    if n == 0 {
131        return out;
132    }
133    let Some(root_def) = db.crate_root_def(tree.krate) else { return out };
134    out[ModuleId::ROOT.0 as usize] = root_def;
135    let mut scratch = Vec::new();
136    for idx in 0..n {
137        let m_id = ModuleId(idx as u32);
138        let p_def = out[idx];
139        if !p_def.is_some() || tree.children(m_id).is_empty() {
140            continue;
141        }
142        scratch.clear();
143        db.module_defs(p_def, &mut scratch);
144        for edge in tree.children(m_id) {
145            let cname = tree.child_name(edge);
146            if let Some(found) = scratch.iter().find(|d| d.kind == ItemKind::Mod && d.name == cname) {
147                out[edge.child.0 as usize] = found.id;
148            }
149        }
150    }
151    out
152}
153
154pub(super) struct Collector<'a> {
155    pub(super) db: &'a dyn ItemDb,
156    pub(super) sources: &'a dyn SourceDb,
157    pub(super) krate: CrateId,
158    pub(super) mod_tree: &'a ModuleTree,
159    pub(super) dirty_files: &'a [FileId],
160    pub(super) scan_all_impls: bool,
161    pub(super) out: CollectedCrate,
162    pub(super) macro_defs: Vec<(String, String, Option<MacroRulesDef>)>,
163    pub(super) in_flight_includes: Vec<FileId>,
164    pub(super) scratch_idx_defs: Vec<IndexedDef<'a>>,
165    pub(super) scratch_var_defs: Vec<IndexedDef<'a>>,
166    pub(super) scratch_toks: Vec<Token>,
167    pub(super) scratch_prefix: Vec<(u32, u32)>,
168}
169
170impl<'a> Collector<'a> {
171    #[inline]
172    pub(super) fn push_str(&mut self, s: &str) -> (u32, u32) {
173        let start = self.out.strings.len() as u32;
174        self.out.strings.push_str(s);
175        (start, self.out.strings.len() as u32)
176    }
177
178    #[inline]
179    pub(super) fn should_scan_impls(&self, file: FileId) -> bool {
180        self.scan_all_impls || self.dirty_files.contains(&file)
181    }
182
183    fn walk_module<'t>(
184        &mut self,
185        mod_id: ModuleId,
186        get_tree: &mut impl FnMut(FileId) -> Option<&'t SyntaxTree<'t>>,
187        parent_file_tree: Option<(FileId, &SyntaxTree<'_>)>,
188        macro_env: &mut MacroScopeVec,
189    ) {
190        let m = *self.mod_tree.module(mod_id);
191        if !m.file.is_some() || m.is_unresolved() {
192            return;
193        }
194        // Snapshot inherited textual `#[macro_use]` macros active upon entering `mod_id`.
195        for &(_, _, lid, gdef) in macro_env.iter() {
196            self.out.textual_macros[mod_id.0 as usize].push((lid, gdef));
197        }
198        let local_tree;
199        let st: &SyntaxTree<'_> = if let Some(t) = get_tree(m.file) {
200            t
201        } else if let Some((pf, pt)) = parent_file_tree.filter(|&(pf, _)| pf == m.file) {
202            let _ = pf;
203            pt
204        } else {
205            local_tree = parse(self.sources.file_text(m.file));
206            &local_tree
207        };
208        let mod_def = self.out.mod_index_defs[mod_id.0 as usize];
209        self.scratch_idx_defs.clear();
210        if mod_def.is_some() {
211            self.db.module_defs(mod_def, &mut self.scratch_idx_defs);
212        }
213        let item_mark = self.out.items.len();
214        if m.is_inline() {
215            if m.inline_node != u32::MAX {
216                if let Some(il) = st.child(NodeId(m.inline_node), K::ItemList) {
217                    self.scan_items(mod_id, m.file, st, il, macro_env, 0);
218                }
219            }
220        } else {
221            self.scan_items(mod_id, m.file, st, st.root(), macro_env, 0);
222        }
223
224        if mod_def.is_some() && !self.dirty_files.contains(&m.file) {
225            let start_mark = if m.is_inline() && m.inline_node == u32::MAX { 0 } else { item_mark };
226            self.supplement_indexed_defs(mod_id, m.file, start_mark);
227        }
228
229        let child_len = self.mod_tree.children(mod_id).len();
230        for cidx in 0..child_len {
231            let child_id = self.mod_tree.children(mod_id)[cidx].child;
232            let env_mark = macro_env.len();
233            self.walk_module(child_id, get_tree, Some((m.file, st)), macro_env);
234            if (self.mod_tree.module(child_id).flags & MOD_FLAG_MACRO_USE) != 0 {
235                for &(_, _, lid, gdef) in &macro_env[env_mark..] {
236                    self.out.textual_macros[mod_id.0 as usize].push((lid, gdef));
237                }
238            } else {
239                macro_env.truncate(env_mark);
240            }
241        }
242    }
243
244    pub(super) fn scan_items(&mut self, mod_id: ModuleId, file: FileId, st: &SyntaxTree<'_>, container: NodeId, macro_env: &mut MacroScopeVec, mbe_depth: u32) {
245        for node in st.children(container) {
246            match st.kind(node) {
247                K::Use => self.out.uses.lower_use_into(st, node, self.mod_tree, mod_id, self.db, self.krate, &mut self.scratch_toks, &mut self.scratch_prefix),
248                K::ExternCrate => self.out.uses.lower_extern_crate(st, node, self.mod_tree, mod_id, self.db, self.krate),
249                K::Struct => {
250                    self.collect_named_item(mod_id, file, st, node, ItemKind::Struct);
251                }
252                K::Enum => self.collect_enum_item(mod_id, file, st, node),
253                K::Union => {
254                    self.collect_named_item(mod_id, file, st, node, ItemKind::Union);
255                }
256                K::Trait => self.collect_trait_item(mod_id, file, st, node, macro_env),
257                K::Fn => {
258                    self.collect_named_item(mod_id, file, st, node, ItemKind::Fn);
259                }
260                K::TypeAlias => self.collect_type_alias_item(mod_id, file, st, node),
261                K::Impl if self.should_scan_impls(file) => {
262                    self.out.local_impls.collect_impl_node(st, node, self.mod_tree, mod_id, file, self.db, self.sources, self.krate, &mut self.macro_defs, macro_env);
263                }
264                K::Const => {
265                    self.collect_named_item(mod_id, file, st, node, ItemKind::Const);
266                }
267                K::Static => {
268                    self.collect_named_item(mod_id, file, st, node, ItemKind::Static);
269                }
270                K::Module if mbe_depth > 0 => {
271                    self.collect_mbe_inline_module(mod_id, file, st, node, macro_env, mbe_depth);
272                }
273                K::ExternBlock => {
274                    let attrs = eval_outer_attrs(st, node, self.db, self.krate);
275                    if attrs.enabled {
276                        if let Some(il) = st.child(node, K::ItemList) {
277                            self.scan_items(mod_id, file, st, il, macro_env, mbe_depth);
278                        }
279                    }
280                }
281                K::MacroRules => self.collect_macro_rules(mod_id, file, st, node, macro_env),
282                K::MacroCall if mbe_depth < MAX_MBE_DEPTH => {
283                    self.try_expand_scope_macro(mod_id, file, st, node, macro_env, mbe_depth);
284                }
285                _ => {}
286            }
287        }
288    }
289
290    fn collect_mbe_inline_module(&mut self, parent_mod: ModuleId, file: FileId, st: &SyntaxTree<'_>, mod_node: NodeId, macro_env: &mut MacroScopeVec, mbe_depth: u32) {
291        let Some(item_list) = st.child(mod_node, K::ItemList) else { return };
292        let attrs = eval_outer_attrs(st, mod_node, self.db, self.krate);
293        if !attrs.enabled {
294            return;
295        }
296        let Some(name_node) = st.child(mod_node, K::Name) else { return };
297        let mod_name = norm_ident(st.text(name_node));
298        let Some(edge) = self.mod_tree.children(parent_mod).iter().find(|e| self.mod_tree.child_name(e) == mod_name) else {
299            return;
300        };
301        let child_id = edge.child;
302        let saved_idx_defs = std::mem::take(&mut self.scratch_idx_defs);
303        let child_def = self.out.mod_index_defs[child_id.0 as usize];
304        if child_def.is_some() {
305            self.db.module_defs(child_def, &mut self.scratch_idx_defs);
306        }
307        let env_mark = macro_env.len();
308        self.scan_items(child_id, file, st, item_list, macro_env, mbe_depth);
309        if !attrs.macro_use {
310            macro_env.truncate(env_mark);
311        }
312        self.scratch_idx_defs = saved_idx_defs;
313    }
314}