Skip to main content

ridx_syntax/name_res/
mod_tree.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//! Flat arena-backed crate module tree (`ModuleTree`) constructed from parsed `.rs` files
12//! (`mod foo;`, inline `mod foo { ... }`, `#[path = "..."]`, `#[cfg(...)]` / `#![cfg(...)]` /
13//! `#[cfg_attr(...)]`, and `#[macro_use]` / item-position `macro_rules!` wrappers).
14
15use super::db::{CrateId, Edition, FileId, ItemDb, ModuleId, SourceDb, VisKind};
16use super::mod_builder::Builder;
17use crate::sema_fn::norm_ident;
18use crate::tree::SyntaxTree;
19
20pub const MOD_FLAG_INLINE: u8 = 1 << 0;
21pub const MOD_FLAG_UNRESOLVED: u8 = 1 << 1;
22pub const MOD_FLAG_NO_IMPLICIT_PRELUDE: u8 = 1 << 2;
23pub const MOD_FLAG_MACRO_USE: u8 = 1 << 3;
24/// Out-of-line `mod foo;` resolved to `<dir>/foo.rs` (Rust 2018 non-`mod.rs` layout):
25/// normal submodules search `<dir>/foo/`, whereas `#[path = "..."]` resolves from `<dir>/`.
26pub const MOD_FLAG_NON_MOD_RS: u8 = 1 << 4;
27
28/// Compact 64-byte flat descriptor of one module inside [`ModuleTree::modules`].
29#[derive(Clone, Copy, Debug)]
30pub struct ModuleData {
31    pub id: ModuleId,
32    pub parent: ModuleId,
33    pub file: FileId,
34    pub decl_file: FileId,
35    /// `NodeId` of `K::Module` when inline (`mod foo { ... }`), or `u32::MAX` for a file root.
36    pub inline_node: u32,
37    pub decl_start: u32,
38    pub decl_end: u32,
39    pub(super) name_start: u32,
40    pub(super) name_end: u32,
41    pub(super) crate_path_start: u32,
42    pub(super) crate_path_end: u32,
43    pub(super) dir_start: u32,
44    pub(super) dir_end: u32,
45    pub(super) children_start: u32,
46    pub(super) children_len: u32,
47    pub vis: VisKind,
48    pub flags: u8,
49}
50
51impl ModuleData {
52    #[inline]
53    pub const fn is_inline(&self) -> bool {
54        (self.flags & MOD_FLAG_INLINE) != 0
55    }
56
57    #[inline]
58    pub const fn is_unresolved(&self) -> bool {
59        (self.flags & MOD_FLAG_UNRESOLVED) != 0
60    }
61
62    #[inline]
63    pub const fn has_no_implicit_prelude(&self) -> bool {
64        (self.flags & MOD_FLAG_NO_IMPLICIT_PRELUDE) != 0
65    }
66
67    #[inline]
68    pub const fn is_non_mod_rs(&self) -> bool {
69        (self.flags & MOD_FLAG_NON_MOD_RS) != 0
70    }
71}
72
73/// One child edge in [`ModuleTree::children`].
74#[derive(Clone, Copy, Debug)]
75pub struct ModChild {
76    pub child: ModuleId,
77    pub(super) name_start: u32,
78    pub(super) name_end: u32,
79    pub vis: VisKind,
80}
81
82/// Non-fatal module-tree discovery diagnostics.
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub enum ModDiag {
85    DisabledCrateRoot { file: FileId },
86    UnresolvedModFile { parent: ModuleId, name: String, tried_primary: String, tried_mod_rs: Option<String> },
87    AmbiguousModFile { parent: ModuleId, name: String, chosen: FileId, alternate: FileId },
88    CyclicModFile { parent: ModuleId, name: String, file: FileId },
89    DuplicateModDecl { parent: ModuleId, name: String },
90}
91
92/// Flat, arena-allocated module hierarchy of one crate.
93#[derive(Clone, Debug)]
94pub struct ModuleTree {
95    pub krate: CrateId,
96    pub edition: Edition,
97    pub no_std: bool,
98    pub no_core: bool,
99    pub modules: Vec<ModuleData>,
100    pub(super) children: Vec<ModChild>,
101    /// Sorted by `(file.0, is_inline, decl_start)` for `O(log N)` file -> module lookup.
102    pub(super) file_to_modules: Vec<(FileId, ModuleId)>,
103    pub(super) strings: String,
104    pub diagnostics: Vec<ModDiag>,
105}
106
107impl ModuleTree {
108    /// Builds the module tree of `krate` starting at `root_file`, parsing each reached `.rs` file once.
109    pub fn build(db: &dyn ItemDb, sources: &dyn SourceDb, krate: CrateId, root_file: FileId) -> Self {
110        Self::build_cached(db, sources, krate, root_file, |_| None)
111    }
112
113    /// Builds the module tree reusing caller-supplied pre-parsed [`SyntaxTree`]s when available.
114    pub fn build_cached<'t>(db: &dyn ItemDb, sources: &dyn SourceDb, krate: CrateId, root_file: FileId, mut get_tree: impl FnMut(FileId) -> Option<&'t SyntaxTree<'t>>) -> Self {
115        Builder::new(db, sources, krate, Some(&mut get_tree)).run(root_file)
116    }
117
118    pub(super) fn build_capturing_trees<'s>(
119        db: &'s dyn ItemDb,
120        sources: &'s dyn SourceDb,
121        krate: CrateId,
122        root_file: FileId,
123    ) -> (Self, std::collections::HashMap<FileId, SyntaxTree<'s>>) {
124        Builder::<'s, 's>::new(db, sources, krate, None).run_capturing(root_file)
125    }
126
127    #[inline]
128    pub fn module(&self, id: ModuleId) -> &ModuleData {
129        &self.modules[id.0 as usize]
130    }
131
132    #[inline]
133    pub fn name(&self, id: ModuleId) -> &str {
134        let m = self.module(id);
135        &self.strings[m.name_start as usize..m.name_end as usize]
136    }
137
138    #[inline]
139    pub fn crate_path(&self, id: ModuleId) -> &str {
140        let m = self.module(id);
141        &self.strings[m.crate_path_start as usize..m.crate_path_end as usize]
142    }
143
144    /// Directory searched for default submodules (`mod sub;`) declared inside `id`.
145    #[inline]
146    pub fn dir_path(&self, id: ModuleId) -> &str {
147        let m = self.module(id);
148        &self.strings[m.dir_start as usize..m.dir_end as usize]
149    }
150
151    /// Directory against which explicit `#[path = "..."]` attributes inside `id` resolve.
152    #[inline]
153    pub fn attr_base_dir(&self, id: ModuleId) -> &str {
154        let m = self.module(id);
155        let dir = &self.strings[m.dir_start as usize..m.dir_end as usize];
156        if m.is_non_mod_rs() {
157            parent_dir_str(dir)
158        } else {
159            dir
160        }
161    }
162
163    #[inline]
164    pub fn children(&self, id: ModuleId) -> &[ModChild] {
165        let m = self.module(id);
166        let s = m.children_start as usize;
167        &self.children[s..s + m.children_len as usize]
168    }
169
170    #[inline]
171    pub fn child_name(&self, edge: &ModChild) -> &str {
172        &self.strings[edge.name_start as usize..edge.name_end as usize]
173    }
174
175    /// Finds direct child module `name` of `parent`.
176    pub fn find_child(&self, parent: ModuleId, name: &str) -> Option<ModuleId> {
177        let target = norm_ident(name);
178        self.children(parent).iter().find(|e| self.child_name(e) == target).map(|e| e.child)
179    }
180
181    /// Resolves a module path like `"crate::sync::mpsc"` or `"sync::mpsc"` from crate root.
182    pub fn find_by_path(&self, path: &str) -> Option<ModuleId> {
183        if self.modules.is_empty() {
184            return None;
185        }
186        let mut cur = ModuleId::ROOT;
187        for seg in path.split("::").filter(|s| !s.is_empty()) {
188            if seg == "crate" {
189                cur = ModuleId::ROOT;
190            } else {
191                cur = self.find_child(cur, seg)?;
192            }
193        }
194        Some(cur)
195    }
196
197    /// Returns all `ModuleId`s backed by `file` (file-root module first, followed by inline modules).
198    pub fn modules_for_file(&self, file: FileId) -> impl Iterator<Item = ModuleId> + '_ {
199        let start = self.file_to_modules.partition_point(|&(f, _)| f < file);
200        let end = self.file_to_modules[start..].partition_point(|&(f, _)| f == file) + start;
201        self.file_to_modules[start..end].iter().map(|&(_, m)| m)
202    }
203
204    /// Innermost module in `file` whose byte span covers `byte_offset`.
205    pub fn module_at_offset(&self, file: FileId, byte_offset: u32) -> Option<ModuleId> {
206        let mut best: Option<ModuleId> = None;
207        for m_id in self.modules_for_file(file) {
208            let m = self.module(m_id);
209            if !m.is_inline() || m.file != file {
210                if best.is_none() {
211                    best = Some(m_id);
212                }
213            } else if m.decl_start <= byte_offset && byte_offset <= m.decl_end {
214                best = Some(m_id);
215            }
216        }
217        best
218    }
219}
220
221#[inline]
222pub(super) fn parent_dir_str(path: &str) -> &str {
223    match path.rfind('/') {
224        Some(0) => "/",
225        Some(idx) => &path[..idx],
226        None => "",
227    }
228}
229
230#[inline]
231fn push_norm_segment(buf: &mut String, part: &str, is_abs: bool) {
232    match part {
233        "" | "." => {}
234        ".." => {
235            if is_abs {
236                if buf.len() > 1 {
237                    let slash = buf.rfind('/').unwrap_or(0);
238                    buf.truncate(slash.max(1));
239                }
240                return;
241            }
242            if let Some(slash) = buf.rfind('/') {
243                if &buf[slash + 1..] != ".." {
244                    buf.truncate(slash);
245                    return;
246                }
247            } else if !buf.is_empty() && buf != ".." {
248                buf.clear();
249                return;
250            }
251            if !buf.is_empty() {
252                buf.push('/');
253            }
254            buf.push_str("..");
255        }
256        normal => {
257            if !buf.is_empty() && buf != "/" {
258                buf.push('/');
259            }
260            buf.push_str(normal);
261        }
262    }
263}
264
265/// Joins `base_dir`, `rel`, and `suffix` into `out` as a normalized `/` path with zero extra allocs.
266/// When `rel` is an absolute path (`/`-rooted), `base_dir` is ignored and the leading `/` is preserved.
267pub fn join_norm_into(out: &mut String, base_dir: &str, rel: &str, suffix: &str) {
268    out.clear();
269    let rel_is_abs = rel.starts_with('/');
270    let is_abs = rel_is_abs || base_dir.starts_with('/');
271    if is_abs {
272        out.push('/');
273    }
274    if !rel_is_abs {
275        for part in base_dir.split(['/', '\\']) {
276            push_norm_segment(out, part, is_abs);
277        }
278    }
279    let mut rel_it = rel.split(['/', '\\']).peekable();
280    while let Some(part) = rel_it.next() {
281        if rel_it.peek().is_none() && !suffix.is_empty() {
282            if suffix.starts_with('/') {
283                push_norm_segment(out, part, is_abs);
284                for sp in suffix.split('/') {
285                    push_norm_segment(out, sp, is_abs);
286                }
287            } else {
288                push_norm_segment(out, part, is_abs);
289                out.push_str(suffix);
290            }
291        } else {
292            push_norm_segment(out, part, is_abs);
293        }
294    }
295}
296
297/// Convenience wrapper returning a normalized joined `/` path.
298pub fn join_norm_path(base_dir: &str, rel: &str) -> String {
299    let mut out = String::with_capacity(base_dir.len() + rel.len() + 1);
300    join_norm_into(&mut out, base_dir, rel, "");
301    out
302}