Skip to main content

lean_ctx/core/graph_index/
rust_modules.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Structural Rust module resolution for the project graph (gh-2269).
3//!
4//! Rust import edges cannot be derived from a `use` string alone: the same
5//! module is reached through `crate::`, `super::`, `self::`, a workspace crate
6//! name, a `pub use` re-export chain or a glob, and a module's file depends on
7//! `foo.rs` vs `foo/mod.rs` and `#[path]`. This resolver builds the module tree
8//! of every Cargo target in the project (no compiler, no build scripts) and
9//! resolves each `use` path and each fully qualified path in code to the file
10//! that *defines* the named item:
11//!
12//! - crate roots come from each `Cargo.toml` (`[lib]`, bins, tests, examples,
13//!   benches, build script), workspace crates are named by their library name
14//!   with `-` mapped to `_`, renamed dependencies (`package = "…"`) included;
15//! - `mod x;` follows `x.rs`, `x/mod.rs` and `#[path = "…"]`; a
16//!   `#[cfg_attr(…, path = "…")]` target is an additional file of the same
17//!   module (the configuration is not evaluated, so every existing candidate
18//!   is loaded and the module is their union); inline `mod x { … }` blocks are
19//!   modules of their own (so `super::` inside an inline `mod tests` is the
20//!   file's module);
21//! - `pub use` re-exports and globs are followed up to four hops;
22//! - strings and comments are skipped, so a module named only in a comment or a
23//!   string is not a dependency.
24//!
25//! Facade modules — crate roots and `mod.rs` files that declare child files —
26//! never receive an import edge: almost every file reaches its imports through
27//! them, and an edge there would make every impact the whole workspace. Their
28//! `mod` declarations are still recorded as `module` edges.
29
30use std::collections::{HashMap, HashSet, VecDeque};
31use std::path::Path;
32
33/// `use` re-export / glob hops followed to the defining module.
34const MAX_REEXPORT_HOPS: u8 = 4;
35/// Size cap for a manifest read from disk.
36const MAX_MANIFEST_BYTES: u64 = 1024 * 1024;
37/// Size cap for a source read from disk (matches the edge builder's cap).
38const MAX_SOURCE_BYTES: u64 = 2 * 1024 * 1024;
39
40/// Edges and coverage produced by [`resolve_workspace`].
41#[derive(Debug, Default)]
42pub struct RustModuleGraph {
43    /// `(from, to)` file pairs: `from` names an item defined in `to` through a
44    /// `use` path or a fully qualified path. Sorted, deduplicated, no self edges.
45    pub imports: Vec<(String, String)>,
46    /// `(parent, child)` file pairs for `mod child;` declarations (incl.
47    /// `#[path]`). Sorted and deduplicated.
48    pub modules: Vec<(String, String)>,
49    /// Every `.rs` file placed in a crate's module tree. Only these files have
50    /// structurally resolved imports; for any other `.rs` file dependents are
51    /// unknown.
52    pub mapped: HashSet<String>,
53    /// Crate roots and `mod.rs` files with child files (see module docs).
54    pub facades: HashSet<String>,
55}
56
57/// Graph edge kind of a resolved Rust use (`(from, to)` in [`RustModuleGraph::imports`]).
58pub const IMPORT_EDGE_KIND: &str = "import";
59/// Weight of an [`IMPORT_EDGE_KIND`] edge in the project graph.
60pub const IMPORT_EDGE_WEIGHT: f32 = 1.0;
61/// Graph edge kind of a `mod child;` declaration (`(parent, child)` in [`RustModuleGraph::modules`]).
62pub const MODULE_EDGE_KIND: &str = "module";
63/// Weight of a [`MODULE_EDGE_KIND`] edge in the project graph.
64pub const MODULE_EDGE_WEIGHT: f32 = 0.8;
65
66impl RustModuleGraph {
67    /// The resolved edges as project-graph edges, imports first, each list in
68    /// its sorted order. Every graph builder (the `graph_index` scan and the
69    /// `ctx_impact` property-graph build) records Rust edges through this one
70    /// conversion, so both answer the same impact question identically.
71    pub fn index_edges(&self) -> Vec<super::IndexEdge> {
72        let edge = |(from, to): &(String, String), kind: &str, weight: f32| super::IndexEdge {
73            from: from.clone(),
74            to: to.clone(),
75            kind: kind.to_string(),
76            weight,
77        };
78        self.imports
79            .iter()
80            .map(|pair| edge(pair, IMPORT_EDGE_KIND, IMPORT_EDGE_WEIGHT))
81            .chain(
82                self.modules
83                    .iter()
84                    .map(|pair| edge(pair, MODULE_EDGE_KIND, MODULE_EDGE_WEIGHT)),
85            )
86            .collect()
87    }
88}
89
90/// Why the dependents of a Rust file cannot be listed from the resolved
91/// graph, or `None` when they can. `declared`: some file declares it with
92/// `mod` (it has an incoming [`MODULE_EDGE_KIND`] edge); `declares_children`:
93/// it declares child files itself. Every impact answer for a `.rs` file asks
94/// this before it may say that nothing depends on the file.
95pub fn unresolved_dependents_reason(
96    declared: bool,
97    declares_children: bool,
98) -> Option<&'static str> {
99    match (declared, declares_children) {
100        (true, _) => None,
101        (false, true) => Some(
102            "it is a crate root; uses of its items are recorded against the modules that define them",
103        ),
104        (false, false) => Some(
105            "it is not reached from any crate root's module tree, so Rust paths to it are not resolved",
106        ),
107    }
108}
109
110/// The advice that follows an unknown-dependents answer.
111pub const UNKNOWN_DEPENDENTS_ADVICE: &str =
112    "Search for its module path (e.g. `git grep`) before assuming nothing depends on it.";
113
114/// Resolve the Rust module graph of every Cargo target below `root`.
115///
116/// `rs_files` are project-relative paths as the caller keys them (`\` on
117/// Windows, where the graph index keeps the platform separator); `contents`
118/// is an optional in-memory cache keyed the same way (files missing from it
119/// are read from disk, size-capped). The graph names every file by the
120/// caller's own key.
121pub fn resolve_workspace(
122    root: &Path,
123    rs_files: &[String],
124    contents: &HashMap<String, String>,
125) -> RustModuleGraph {
126    if !rs_files.iter().any(|f| f.contains('\\')) {
127        return resolve_slash_separated(root, rs_files, contents);
128    }
129    // The resolver joins and splits module paths on `/`: resolve under
130    // `/`-separated names, then hand every file back under the caller's key.
131    let caller_key: HashMap<String, &String> =
132        rs_files.iter().map(|f| (f.replace('\\', "/"), f)).collect();
133    let files: Vec<String> = rs_files.iter().map(|f| f.replace('\\', "/")).collect();
134    let slash_contents: HashMap<String, String> = contents
135        .iter()
136        .map(|(f, text)| (f.replace('\\', "/"), text.clone()))
137        .collect();
138    let graph = resolve_slash_separated(root, &files, &slash_contents);
139    let key = |f: &String| {
140        caller_key
141            .get(f)
142            .map_or_else(|| f.clone(), |k| (*k).clone())
143    };
144    let pairs = |list: Vec<(String, String)>| {
145        let mut out: Vec<(String, String)> = list.iter().map(|(a, b)| (key(a), key(b))).collect();
146        out.sort();
147        out.dedup();
148        out
149    };
150    RustModuleGraph {
151        imports: pairs(graph.imports),
152        modules: pairs(graph.modules),
153        mapped: graph.mapped.iter().map(key).collect(),
154        facades: graph.facades.iter().map(key).collect(),
155    }
156}
157
158/// [`resolve_workspace`] for `/`-separated project-relative paths.
159fn resolve_slash_separated(
160    root: &Path,
161    rs_files: &[String],
162    contents: &HashMap<String, String>,
163) -> RustModuleGraph {
164    let file_set: HashSet<&str> = rs_files
165        .iter()
166        .map(String::as_str)
167        .filter(|f| is_rs(f))
168        .collect();
169    if file_set.is_empty() {
170        return RustModuleGraph::default();
171    }
172    let manifests = discover_manifests(root, &file_set);
173    let mut tree = ModuleTree::default();
174    for (crate_idx, krate) in manifests.crates.iter().enumerate() {
175        tree.load_crate(crate_idx, &krate.root_file, root, &file_set, contents);
176    }
177    for (name, crate_idx) in &manifests.externs {
178        if let Some(&root_mod) = tree.crate_roots.get(crate_idx) {
179            tree.externs.insert(name.clone(), root_mod);
180        }
181    }
182    tree.into_graph()
183}
184
185fn is_rs(path: &str) -> bool {
186    Path::new(path)
187        .extension()
188        .is_some_and(|ext| ext.eq_ignore_ascii_case("rs"))
189}
190
191// ---------------------------------------------------------------------------
192// Manifests
193// ---------------------------------------------------------------------------
194
195struct CrateTarget {
196    /// Project-relative path of the target's root source file.
197    root_file: String,
198}
199
200#[derive(Default)]
201struct Manifests {
202    crates: Vec<CrateTarget>,
203    /// Extern crate name (library name or dependency alias) -> index into
204    /// `crates` of the library target it names.
205    externs: HashMap<String, usize>,
206}
207
208fn join_rel(dir: &str, rest: &str) -> String {
209    let joined = if dir.is_empty() {
210        rest.to_string()
211    } else {
212        format!("{dir}/{rest}")
213    };
214    normalize_rel(&joined)
215}
216
217/// Collapse `.` and `..` segments of a `/`-separated relative path.
218fn normalize_rel(path: &str) -> String {
219    let mut parts: Vec<&str> = Vec::new();
220    for seg in path.split(['/', '\\']) {
221        match seg {
222            "" | "." => {}
223            ".." => {
224                parts.pop();
225            }
226            s => parts.push(s),
227        }
228    }
229    parts.join("/")
230}
231
232fn parent_dir(file: &str) -> &str {
233    file.rsplit_once('/').map_or("", |(dir, _)| dir)
234}
235
236fn crate_ident(name: &str) -> String {
237    name.replace('-', "_")
238}
239
240fn read_capped(path: &Path, cap: u64) -> Option<String> {
241    let meta = path.metadata().ok()?;
242    if !meta.is_file() || meta.len() > cap {
243        return None;
244    }
245    crate::core::text_decode::read_text(path).ok()
246}
247
248/// Every `Cargo.toml` in the ancestry of a `.rs` file, parsed into targets.
249fn discover_manifests(root: &Path, file_set: &HashSet<&str>) -> Manifests {
250    let mut dirs: HashSet<&str> = HashSet::new();
251    for file in file_set {
252        let mut dir = parent_dir(file);
253        loop {
254            if !dirs.insert(dir) {
255                break;
256            }
257            if dir.is_empty() {
258                break;
259            }
260            dir = parent_dir(dir);
261        }
262    }
263    let mut manifest_dirs: Vec<&str> = dirs
264        .into_iter()
265        .filter(|dir| root.join(dir).join("Cargo.toml").is_file())
266        .collect();
267    manifest_dirs.sort_unstable();
268
269    let mut out = Manifests::default();
270    let mut lib_of_package: HashMap<String, usize> = HashMap::new();
271    let mut aliases: Vec<(String, String)> = Vec::new();
272    let mut seen_roots: HashSet<String> = HashSet::new();
273
274    for dir in manifest_dirs {
275        let Some(text) = read_capped(&root.join(dir).join("Cargo.toml"), MAX_MANIFEST_BYTES) else {
276            continue;
277        };
278        let Ok(manifest) = text.parse::<toml::Table>() else {
279            continue;
280        };
281        collect_aliases(&manifest, &mut aliases);
282        let Some(package) = manifest.get("package").and_then(toml::Value::as_table) else {
283            continue;
284        };
285        let Some(package_name) = package.get("name").and_then(toml::Value::as_str) else {
286            continue;
287        };
288        let mut push_root = |file: String, out: &mut Manifests| -> Option<usize> {
289            if !file_set.contains(file.as_str()) || !seen_roots.insert(file.clone()) {
290                return None;
291            }
292            out.crates.push(CrateTarget { root_file: file });
293            Some(out.crates.len() - 1)
294        };
295
296        // Library target.
297        let lib = manifest.get("lib").and_then(toml::Value::as_table);
298        let lib_path = lib
299            .and_then(|l| l.get("path"))
300            .and_then(toml::Value::as_str)
301            .map_or_else(|| join_rel(dir, "src/lib.rs"), |p| join_rel(dir, p));
302        let lib_name = lib
303            .and_then(|l| l.get("name"))
304            .and_then(toml::Value::as_str)
305            .map_or_else(|| crate_ident(package_name), crate_ident);
306        if let Some(idx) = push_root(lib_path, &mut out) {
307            out.externs.entry(lib_name).or_insert(idx);
308            lib_of_package.insert(crate_ident(package_name), idx);
309        }
310
311        // Explicit [[bin]]/[[test]]/[[example]]/[[bench]] paths.
312        for section in ["bin", "test", "example", "bench"] {
313            for target in manifest
314                .get(section)
315                .and_then(toml::Value::as_array)
316                .into_iter()
317                .flatten()
318                .filter_map(toml::Value::as_table)
319            {
320                if let Some(path) = target.get("path").and_then(toml::Value::as_str) {
321                    push_root(join_rel(dir, path), &mut out);
322                } else if section == "bin"
323                    && let Some(name) = target.get("name").and_then(toml::Value::as_str)
324                {
325                    push_root(join_rel(dir, &format!("src/bin/{name}.rs")), &mut out);
326                    push_root(join_rel(dir, &format!("src/bin/{name}/main.rs")), &mut out);
327                }
328            }
329        }
330
331        // Auto-discovered targets.
332        push_root(join_rel(dir, "src/main.rs"), &mut out);
333        match package.get("build") {
334            Some(toml::Value::String(path)) => {
335                push_root(join_rel(dir, path), &mut out);
336            }
337            Some(toml::Value::Boolean(false)) => {}
338            _ => {
339                push_root(join_rel(dir, "build.rs"), &mut out);
340            }
341        }
342        for target_dir in ["src/bin", "tests", "examples", "benches"] {
343            let prefix = format!("{}/", join_rel(dir, target_dir));
344            let mut found: Vec<&str> = file_set
345                .iter()
346                .copied()
347                .filter(|f| {
348                    f.strip_prefix(prefix.as_str()).is_some_and(|rest| {
349                        !rest.contains('/')
350                            || (rest.split('/').count() == 2 && rest.ends_with("/main.rs"))
351                    })
352                })
353                .collect();
354            found.sort_unstable();
355            for file in found {
356                push_root(file.to_string(), &mut out);
357            }
358        }
359    }
360
361    for (alias, package) in aliases {
362        if let Some(&idx) = lib_of_package.get(&package) {
363            out.externs.entry(alias).or_insert(idx);
364        }
365    }
366    out
367}
368
369/// Renamed dependencies (`alias = { package = "real" }`) in every dependency
370/// table of a manifest, as `(alias, package)` crate identifiers.
371fn collect_aliases(manifest: &toml::Table, out: &mut Vec<(String, String)>) {
372    fn from_deps(deps: Option<&toml::Value>, out: &mut Vec<(String, String)>) {
373        let Some(deps) = deps.and_then(toml::Value::as_table) else {
374            return;
375        };
376        for (alias, spec) in deps {
377            if let Some(package) = spec
378                .as_table()
379                .and_then(|t| t.get("package"))
380                .and_then(toml::Value::as_str)
381            {
382                out.push((crate_ident(alias), crate_ident(package)));
383            }
384        }
385    }
386    for table in ["dependencies", "dev-dependencies", "build-dependencies"] {
387        from_deps(manifest.get(table), out);
388    }
389    if let Some(targets) = manifest.get("target").and_then(toml::Value::as_table) {
390        for spec in targets.values().filter_map(toml::Value::as_table) {
391            for table in ["dependencies", "dev-dependencies", "build-dependencies"] {
392                from_deps(spec.get(table), out);
393            }
394        }
395    }
396    if let Some(workspace) = manifest.get("workspace").and_then(toml::Value::as_table) {
397        from_deps(workspace.get("dependencies"), out);
398    }
399}
400
401// ---------------------------------------------------------------------------
402// Lexer
403// ---------------------------------------------------------------------------
404
405#[derive(Debug, Clone, PartialEq, Eq)]
406enum Tok {
407    Ident(String),
408    Str(String),
409    PathSep,
410    Punct(char),
411}
412
413fn is_ident_start(b: u8) -> bool {
414    b.is_ascii_alphabetic() || b == b'_' || b >= 0x80
415}
416
417fn is_ident_continue(b: u8) -> bool {
418    b.is_ascii_alphanumeric() || b == b'_' || b >= 0x80
419}
420
421/// Tokens of a Rust source with comments, literals and lifetimes dropped
422/// (string literal contents are kept for `#[path = "…"]`).
423fn lex(src: &str) -> Vec<Tok> {
424    let b = src.as_bytes();
425    let n = b.len();
426    let mut out = Vec::new();
427    let mut i = 0;
428    while i < n {
429        let c = b[i];
430        if c.is_ascii_whitespace() {
431            i += 1;
432        } else if c == b'/' && b.get(i + 1) == Some(&b'/') {
433            while i < n && b[i] != b'\n' {
434                i += 1;
435            }
436        } else if c == b'/' && b.get(i + 1) == Some(&b'*') {
437            let mut depth = 1usize;
438            i += 2;
439            while i < n && depth > 0 {
440                if b[i] == b'/' && b.get(i + 1) == Some(&b'*') {
441                    depth += 1;
442                    i += 2;
443                } else if b[i] == b'*' && b.get(i + 1) == Some(&b'/') {
444                    depth -= 1;
445                    i += 2;
446                } else {
447                    i += 1;
448                }
449            }
450        } else if let Some((value, end)) = lex_string_literal(src, i) {
451            out.push(Tok::Str(value));
452            i = end;
453        } else if c == b'\'' {
454            i = skip_char_or_lifetime(b, i);
455        } else if c == b'r'
456            && b.get(i + 1) == Some(&b'#')
457            && b.get(i + 2).is_some_and(|&x| is_ident_start(x))
458        {
459            let start = i + 2;
460            i = start;
461            while i < n && is_ident_continue(b[i]) {
462                i += 1;
463            }
464            out.push(Tok::Ident(src[start..i].to_string()));
465        } else if is_ident_start(c) {
466            let start = i;
467            while i < n && is_ident_continue(b[i]) {
468                i += 1;
469            }
470            out.push(Tok::Ident(src[start..i].to_string()));
471        } else if c.is_ascii_digit() {
472            while i < n && is_ident_continue(b[i]) {
473                i += 1;
474            }
475        } else if c == b':' && b.get(i + 1) == Some(&b':') {
476            out.push(Tok::PathSep);
477            i += 2;
478        } else {
479            out.push(Tok::Punct(char::from(c)));
480            i += 1;
481        }
482    }
483    out
484}
485
486/// A string literal (`"…"`, `b"…"`, `c"…"`, raw `r#"…"#` and its byte/C
487/// forms) starting at `i`: its contents and the index after it.
488fn lex_string_literal(src: &str, i: usize) -> Option<(String, usize)> {
489    let bytes = src.as_bytes();
490    let mut pos = i;
491    if matches!(bytes.get(pos), Some(b'b' | b'c')) {
492        pos += 1;
493    }
494    if bytes.get(pos) == Some(&b'r') {
495        let mut open = pos + 1;
496        let mut hashes = 0usize;
497        while bytes.get(open) == Some(&b'#') {
498            hashes += 1;
499            open += 1;
500        }
501        if bytes.get(open) != Some(&b'"') {
502            return None;
503        }
504        let start = open + 1;
505        let mut scan = start;
506        while scan < bytes.len() {
507            if bytes[scan] == b'"' && (1..=hashes).all(|h| bytes.get(scan + h) == Some(&b'#')) {
508                return Some((src[start..scan].to_string(), scan + 1 + hashes));
509            }
510            scan += 1;
511        }
512        return Some((src[start..].to_string(), bytes.len()));
513    }
514    if bytes.get(pos) != Some(&b'"') {
515        return None;
516    }
517    let start = pos + 1;
518    let mut scan = start;
519    while scan < bytes.len() {
520        match bytes[scan] {
521            b'\\' => scan += 2,
522            b'"' => return Some((src[start..scan].to_string(), scan + 1)),
523            _ => scan += 1,
524        }
525    }
526    Some((src[start.min(bytes.len())..].to_string(), bytes.len()))
527}
528
529/// Skip a char literal (`'a'`, `'\n'`, `'\u{..}'`) or a lifetime (`'a`)
530/// starting at the quote `i`; returns the index after it.
531fn skip_char_or_lifetime(b: &[u8], i: usize) -> usize {
532    let n = b.len();
533    if b.get(i + 1) == Some(&b'\\') {
534        // Skip the escaped character itself, then scan to the closing quote.
535        let mut m = i + 3;
536        while m < n && b[m] != b'\'' && b[m] != b'\n' {
537            m += 1;
538        }
539        return (m + 1).min(n);
540    }
541    // One (possibly multi-byte) character followed by a closing quote.
542    let mut next = i + 2;
543    while next < n && (b[next] & 0xC0) == 0x80 {
544        next += 1;
545    }
546    if b.get(next) == Some(&b'\'') {
547        return next + 1;
548    }
549    let mut m = i + 1;
550    while m < n && is_ident_continue(b[m]) {
551        m += 1;
552    }
553    m.max(i + 1)
554}
555
556// ---------------------------------------------------------------------------
557// Module tree
558// ---------------------------------------------------------------------------
559
560#[derive(Debug, Clone)]
561struct UsePath {
562    segs: Vec<String>,
563    /// Leading `::` (extern crate only).
564    global: bool,
565}
566
567#[derive(Debug)]
568struct Module {
569    crate_idx: usize,
570    /// File that holds this module's items (inline modules share their file).
571    file: String,
572    parent: Option<usize>,
573    /// Directory where `mod x;` children of this module are looked up.
574    child_dir: String,
575    children: HashMap<String, usize>,
576    items: HashSet<String>,
577    bindings: Vec<(String, UsePath)>,
578    globs: Vec<UsePath>,
579    /// Paths whose target this module's file depends on.
580    refs: Vec<UsePath>,
581    /// Other files of the same `mod x;` declaration (`#[cfg_attr(…, path)]`
582    /// candidates); a name visible in any of them is visible in the module.
583    alternates: Vec<usize>,
584}
585
586#[derive(Debug, Clone, Copy, PartialEq, Eq)]
587enum Res {
588    Module(usize),
589    /// An item defined in this module.
590    Item(usize),
591    /// The path reached this module, but its next segment is not visible to
592    /// the parser (e.g. generated by a macro).
593    Partial(usize),
594}
595
596#[derive(Debug, Clone, Copy)]
597enum Scope {
598    Module(usize),
599    /// A macro invocation body (`cfg_if! { … }`): items stay module items.
600    MacroBody,
601    /// Any other block (fn body, impl, struct, trait): not module items.
602    Block,
603}
604
605const ITEM_KEYWORDS: [&str; 8] = [
606    "fn", "struct", "enum", "trait", "type", "const", "static", "union",
607];
608
609const KEYWORDS: [&str; 12] = [
610    "fn", "struct", "enum", "trait", "type", "const", "static", "union", "unsafe", "async",
611    "extern", "mut",
612];
613
614/// `#[path]` attributes seen since the last item, for the next `mod x;`.
615#[derive(Default)]
616struct PendingPaths {
617    /// `#[path = "…"]`.
618    plain: Option<String>,
619    /// `path = "…"` inside `#[cfg_attr(…)]`, in source order.
620    cfg: Vec<String>,
621}
622
623#[derive(Default)]
624struct ModuleTree {
625    modules: Vec<Module>,
626    /// Crate index -> its root module.
627    crate_roots: HashMap<usize, usize>,
628    externs: HashMap<String, usize>,
629    module_edges: Vec<(String, String)>,
630    mapped: HashSet<String>,
631    facades: HashSet<String>,
632}
633
634impl ModuleTree {
635    fn new_module(
636        &mut self,
637        crate_idx: usize,
638        file: &str,
639        parent: Option<usize>,
640        child_dir: String,
641    ) -> usize {
642        self.modules.push(Module {
643            crate_idx,
644            file: file.to_string(),
645            parent,
646            child_dir,
647            children: HashMap::new(),
648            items: HashSet::new(),
649            bindings: Vec::new(),
650            globs: Vec::new(),
651            refs: Vec::new(),
652            alternates: Vec::new(),
653        });
654        self.modules.len() - 1
655    }
656
657    fn load_crate(
658        &mut self,
659        crate_idx: usize,
660        root_file: &str,
661        root: &Path,
662        file_set: &HashSet<&str>,
663        contents: &HashMap<String, String>,
664    ) {
665        let root_mod = self.new_module(
666            crate_idx,
667            root_file,
668            None,
669            parent_dir(root_file).to_string(),
670        );
671        self.crate_roots.insert(crate_idx, root_mod);
672        self.facades.insert(root_file.to_string());
673        let mut loaded: HashSet<String> = HashSet::new();
674        let mut queue: VecDeque<(usize, String)> = VecDeque::new();
675        queue.push_back((root_mod, root_file.to_string()));
676        while let Some((module, file)) = queue.pop_front() {
677            if !loaded.insert(file.clone()) {
678                continue;
679            }
680            let text = match contents.get(&file) {
681                Some(cached) => Some(std::borrow::Cow::Borrowed(cached.as_str())),
682                None => {
683                    read_capped(&root.join(&file), MAX_SOURCE_BYTES).map(std::borrow::Cow::Owned)
684                }
685            };
686            let Some(text) = text else { continue };
687            self.mapped.insert(file.clone());
688            let children = self.parse_file(module, &file, &lex(&text), file_set);
689            if !children.is_empty() && file.rsplit('/').next() == Some("mod.rs") {
690                self.facades.insert(file.clone());
691            }
692            for (child, child_file) in children {
693                self.module_edges.push((file.clone(), child_file.clone()));
694                if !loaded.contains(&child_file) {
695                    queue.push_back((child, child_file));
696                }
697            }
698        }
699    }
700
701    /// Record the items, `use` declarations, paths and child modules of one
702    /// file; returns the file child modules declared in it.
703    fn parse_file(
704        &mut self,
705        file_module: usize,
706        file: &str,
707        toks: &[Tok],
708        file_set: &HashSet<&str>,
709    ) -> Vec<(usize, String)> {
710        let crate_idx = self.modules[file_module].crate_idx;
711        let mut children = Vec::new();
712        let mut stack: Vec<Scope> = vec![Scope::Module(file_module)];
713        let mut pending = PendingPaths::default();
714        let mut i = 0usize;
715        let current = |stack: &[Scope]| -> usize {
716            stack
717                .iter()
718                .rev()
719                .find_map(|s| match s {
720                    Scope::Module(m) => Some(*m),
721                    _ => None,
722                })
723                .unwrap_or(file_module)
724        };
725        let ident_at = |k: usize| -> Option<&str> {
726            match toks.get(k) {
727                Some(Tok::Ident(s)) => Some(s.as_str()),
728                _ => None,
729            }
730        };
731        while i < toks.len() {
732            let tok = &toks[i];
733            match tok {
734                Tok::Punct('#') => {
735                    let mut j = i + 1;
736                    if toks.get(j) == Some(&Tok::Punct('!')) {
737                        j += 1;
738                    }
739                    if toks.get(j) != Some(&Tok::Punct('[')) {
740                        i += 1;
741                        continue;
742                    }
743                    let end = matching_close(toks, j, '[', ']');
744                    if end == j + 5
745                        && ident_at(j + 1) == Some("path")
746                        && toks.get(j + 2) == Some(&Tok::Punct('='))
747                        && let Some(Tok::Str(path)) = toks.get(j + 3)
748                    {
749                        pending.plain = Some(path.clone());
750                    } else if ident_at(j + 1) == Some("cfg_attr")
751                        && toks.get(j + 2) == Some(&Tok::Punct('('))
752                    {
753                        cfg_attr_paths(&toks[..end], j + 2, &mut pending.cfg);
754                    }
755                    i = end;
756                }
757                Tok::Ident(kw) if kw == "mod" => {
758                    let module = current(&stack);
759                    match (ident_at(i + 1), toks.get(i + 2)) {
760                        (Some(name), Some(Tok::Punct(';'))) => {
761                            let candidates =
762                                self.child_files(module, name, &pending, &stack, file_set);
763                            let mut group: Vec<usize> = Vec::with_capacity(candidates.len());
764                            for (child_file, child_dir) in candidates {
765                                let child = self.new_module(
766                                    crate_idx,
767                                    &child_file,
768                                    Some(module),
769                                    child_dir,
770                                );
771                                if group.is_empty() {
772                                    self.modules[module]
773                                        .children
774                                        .insert(name.to_string(), child);
775                                }
776                                group.push(child);
777                                children.push((child, child_file));
778                            }
779                            for &member in &group {
780                                self.modules[member].alternates =
781                                    group.iter().copied().filter(|&m| m != member).collect();
782                            }
783                            i += 3;
784                        }
785                        (Some(name), Some(Tok::Punct('{'))) => {
786                            let child_dir = join_rel(&self.modules[module].child_dir, name);
787                            let child = self.new_module(crate_idx, file, Some(module), child_dir);
788                            self.modules[module]
789                                .children
790                                .insert(name.to_string(), child);
791                            stack.push(Scope::Module(child));
792                            i += 3;
793                        }
794                        _ => i += 1,
795                    }
796                    pending = PendingPaths::default();
797                }
798                Tok::Ident(kw) if kw == "use" && !prev_is(toks, i, &Tok::PathSep) => {
799                    let module = current(&stack);
800                    let end = find_semicolon(toks, i + 1);
801                    let mut items = Vec::new();
802                    let mut k = i + 1;
803                    parse_use_tree(&toks[..end], &mut k, Vec::new(), false, &mut items);
804                    let m = &mut self.modules[module];
805                    for item in items {
806                        match item {
807                            UseItem::Binding(name, path) => {
808                                m.refs.push(path.clone());
809                                m.bindings.push((name, path));
810                            }
811                            UseItem::Glob(path) => {
812                                m.refs.push(path.clone());
813                                m.globs.push(path);
814                            }
815                        }
816                    }
817                    pending = PendingPaths::default();
818                    i = end + 1;
819                }
820                Tok::Ident(kw) if kw == "extern" && ident_at(i + 1) == Some("crate") => {
821                    let module = current(&stack);
822                    if let Some(name) = ident_at(i + 2).filter(|n| *n != "self") {
823                        let alias = if ident_at(i + 3) == Some("as") {
824                            ident_at(i + 4).unwrap_or(name)
825                        } else {
826                            name
827                        };
828                        self.modules[module].bindings.push((
829                            alias.to_string(),
830                            UsePath {
831                                segs: vec![name.to_string()],
832                                global: true,
833                            },
834                        ));
835                    }
836                    i = find_semicolon(toks, i) + 1;
837                }
838                Tok::Ident(kw)
839                    if ITEM_KEYWORDS.contains(&kw.as_str())
840                        && !matches!(stack.last(), Some(Scope::Block)) =>
841                {
842                    if let Some(name) =
843                        ident_at(i + 1).filter(|n| !KEYWORDS.contains(n) && *n != "_")
844                    {
845                        let module = current(&stack);
846                        self.modules[module].items.insert(name.to_string());
847                    }
848                    i += 1;
849                }
850                Tok::Ident(kw)
851                    if kw == "macro_rules"
852                        && toks.get(i + 1) == Some(&Tok::Punct('!'))
853                        && !matches!(stack.last(), Some(Scope::Block)) =>
854                {
855                    if let Some(name) = ident_at(i + 2) {
856                        let module = current(&stack);
857                        self.modules[module].items.insert(name.to_string());
858                    }
859                    i += 2;
860                }
861                Tok::Ident(first)
862                    if toks.get(i + 1) == Some(&Tok::PathSep)
863                        && !prev_is(toks, i, &Tok::PathSep)
864                        && !prev_is(toks, i, &Tok::Punct('$'))
865                        && (i == 0 || ident_at(i - 1) != Some("in"))
866                        && first != "Self" =>
867                {
868                    let mut segs = vec![first.clone()];
869                    let mut k = i + 1;
870                    while toks.get(k) == Some(&Tok::PathSep) {
871                        match toks.get(k + 1) {
872                            Some(Tok::Ident(seg)) => {
873                                segs.push(seg.clone());
874                                k += 2;
875                            }
876                            _ => break,
877                        }
878                    }
879                    let module = current(&stack);
880                    self.modules[module].refs.push(UsePath {
881                        segs,
882                        global: false,
883                    });
884                    i = k;
885                }
886                Tok::Punct('{') => {
887                    let macro_body = prev_is(toks, i, &Tok::Punct('!'))
888                        || (i >= 2
889                            && toks.get(i - 2) == Some(&Tok::Punct('!'))
890                            && ident_at(i - 1).is_some());
891                    stack.push(if macro_body {
892                        Scope::MacroBody
893                    } else {
894                        Scope::Block
895                    });
896                    pending = PendingPaths::default();
897                    i += 1;
898                }
899                Tok::Punct('}') => {
900                    if stack.len() > 1 {
901                        stack.pop();
902                    }
903                    pending = PendingPaths::default();
904                    i += 1;
905                }
906                Tok::Punct(';') => {
907                    pending = PendingPaths::default();
908                    i += 1;
909                }
910                _ => i += 1,
911            }
912        }
913        children
914    }
915
916    /// Files and child directories of `mod name;` declared in `module`: the
917    /// file Rust loads without configuration (`#[path]`, else `name.rs` /
918    /// `name/mod.rs`) first, then each existing `#[cfg_attr(…, path)]`
919    /// target. Missing files are skipped; duplicates are listed once.
920    fn child_files(
921        &self,
922        module: usize,
923        name: &str,
924        pending: &PendingPaths,
925        stack: &[Scope],
926        file_set: &HashSet<&str>,
927    ) -> Vec<(String, String)> {
928        let m = &self.modules[module];
929        // Outside inline modules `#[path]` is relative to the declaring
930        // file's directory; inside them, to the inline module's directory.
931        let inline = stack
932            .iter()
933            .filter(|s| matches!(s, Scope::Module(_)))
934            .count()
935            > 1;
936        let path_base = if inline {
937            m.child_dir.as_str()
938        } else {
939            parent_dir(&m.file)
940        };
941        let by_path = |path: &str| -> Option<(String, String)> {
942            let file = join_rel(path_base, path);
943            file_set
944                .contains(file.as_str())
945                .then(|| (file.clone(), parent_dir(&file).to_string()))
946        };
947
948        let mut out: Vec<(String, String)> = Vec::new();
949        let primary = if let Some(path) = pending.plain.as_deref() {
950            by_path(path)
951        } else {
952            let child_dir = join_rel(&m.child_dir, name);
953            let flat = join_rel(&m.child_dir, &format!("{name}.rs"));
954            let nested = join_rel(&child_dir, "mod.rs");
955            if file_set.contains(flat.as_str()) {
956                Some((flat, child_dir))
957            } else {
958                file_set
959                    .contains(nested.as_str())
960                    .then_some((nested, child_dir))
961            }
962        };
963        out.extend(primary);
964        for path in &pending.cfg {
965            if let Some(candidate) = by_path(path)
966                && !out.iter().any(|(file, _)| *file == candidate.0)
967            {
968                out.push(candidate);
969            }
970        }
971        out
972    }
973
974    // -- resolution --------------------------------------------------------
975
976    fn crate_root(&self, module: usize) -> Option<usize> {
977        self.crate_roots
978            .get(&self.modules[module].crate_idx)
979            .copied()
980    }
981
982    fn resolve(&self, from: usize, path: &UsePath, hops: u8) -> Option<Res> {
983        let segs = &path.segs;
984        let first = segs.first()?;
985        let (mut cur, mut idx) = if path.global {
986            (*self.externs.get(first)?, 1)
987        } else {
988            match first.as_str() {
989                "crate" => (self.crate_root(from)?, 1),
990                "self" => (from, 1),
991                "super" => {
992                    let mut m = from;
993                    let mut k = 0;
994                    while segs.get(k).map(String::as_str) == Some("super") {
995                        m = self.modules[m].parent?;
996                        k += 1;
997                    }
998                    (m, k)
999                }
1000                name => match self.member(from, name, hops) {
1001                    Some(Res::Module(m)) => (m, 1),
1002                    Some(res) => return Some(res),
1003                    None => (*self.externs.get(name)?, 1),
1004                },
1005            }
1006        };
1007        while idx < segs.len() {
1008            match self.member(cur, &segs[idx], hops) {
1009                Some(Res::Module(m)) => cur = m,
1010                Some(res) => return Some(res),
1011                None => return Some(Res::Partial(cur)),
1012            }
1013            idx += 1;
1014        }
1015        Some(Res::Module(cur))
1016    }
1017
1018    /// What `name` means inside `module`: a child module, an item defined
1019    /// there, or the target of a `use` binding or glob (followed up to
1020    /// [`MAX_REEXPORT_HOPS`]).
1021    ///
1022    /// A module split over several files (`#[cfg_attr(…, path)]`
1023    /// alternates) is their union: its own file is asked first, then each
1024    /// alternate in declaration order.
1025    fn member(&self, module: usize, name: &str, hops: u8) -> Option<Res> {
1026        let group =
1027            || std::iter::once(module).chain(self.modules[module].alternates.iter().copied());
1028        for g in group() {
1029            let m = &self.modules[g];
1030            if let Some(&child) = m.children.get(name) {
1031                return Some(Res::Module(child));
1032            }
1033            if m.items.contains(name) {
1034                return Some(Res::Item(g));
1035            }
1036        }
1037        if hops >= MAX_REEXPORT_HOPS {
1038            return None;
1039        }
1040        for g in group() {
1041            if let Some((_, path)) = self.modules[g]
1042                .bindings
1043                .iter()
1044                .find(|(bound, _)| bound == name)
1045            {
1046                return self.resolve(g, path, hops + 1).and_then(|res| match res {
1047                    // A binding whose path leaves the parsed tree names nothing here.
1048                    Res::Partial(_) => None,
1049                    other => Some(other),
1050                });
1051            }
1052        }
1053        for g in group() {
1054            for glob in &self.modules[g].globs {
1055                if let Some(Res::Module(source)) = self.resolve(g, glob, hops + 1)
1056                    && !group().any(|member| member == source)
1057                    && let Some(res) = self.member(source, name, hops + 1)
1058                {
1059                    return Some(res);
1060                }
1061            }
1062        }
1063        None
1064    }
1065
1066    fn into_graph(self) -> RustModuleGraph {
1067        let mut imports: Vec<(String, String)> = Vec::new();
1068        for (idx, module) in self.modules.iter().enumerate() {
1069            for path in &module.refs {
1070                let Some(res) = self.resolve(idx, path, 0) else {
1071                    continue;
1072                };
1073                let (Res::Module(target) | Res::Item(target) | Res::Partial(target)) = res;
1074                let target_file = &self.modules[target].file;
1075                if *target_file == module.file || self.facades.contains(target_file) {
1076                    continue;
1077                }
1078                imports.push((module.file.clone(), target_file.clone()));
1079            }
1080        }
1081        imports.sort();
1082        imports.dedup();
1083        let mut modules = self.module_edges;
1084        modules.sort();
1085        modules.dedup();
1086        RustModuleGraph {
1087            imports,
1088            modules,
1089            mapped: self.mapped,
1090            facades: self.facades,
1091        }
1092    }
1093}
1094
1095fn prev_is(toks: &[Tok], i: usize, tok: &Tok) -> bool {
1096    i > 0 && toks.get(i - 1) == Some(tok)
1097}
1098
1099/// Index of the token after the bracket matching `toks[open]`.
1100fn matching_close(toks: &[Tok], open: usize, open_ch: char, close_ch: char) -> usize {
1101    let mut depth = 0usize;
1102    for (k, tok) in toks.iter().enumerate().skip(open) {
1103        if *tok == Tok::Punct(open_ch) {
1104            depth += 1;
1105        } else if *tok == Tok::Punct(close_ch) {
1106            depth -= 1;
1107            if depth == 0 {
1108                return k + 1;
1109            }
1110        }
1111    }
1112    toks.len()
1113}
1114
1115/// `path = "…"` values of the `cfg_attr(predicate, attr, …)` whose `(` is at
1116/// `toks[open]`, nested `cfg_attr`s included. The predicate is not evaluated.
1117fn cfg_attr_paths(toks: &[Tok], open: usize, out: &mut Vec<String>) {
1118    let close = matching_close(toks, open, '(', ')').saturating_sub(1);
1119    let mut depth = 0usize;
1120    let mut seg_start = open + 1;
1121    let mut predicate = true;
1122    let mut segments: Vec<(usize, usize)> = Vec::new();
1123    for (k, tok) in toks.iter().enumerate().take(close).skip(open + 1) {
1124        match tok {
1125            Tok::Punct('(' | '[' | '{') => depth += 1,
1126            Tok::Punct(')' | ']' | '}') => depth = depth.saturating_sub(1),
1127            Tok::Punct(',') if depth == 0 => {
1128                if !predicate {
1129                    segments.push((seg_start, k));
1130                }
1131                predicate = false;
1132                seg_start = k + 1;
1133            }
1134            _ => {}
1135        }
1136    }
1137    if !predicate {
1138        segments.push((seg_start, close));
1139    }
1140    for (start, end) in segments {
1141        match &toks[start..end] {
1142            [Tok::Ident(attr), Tok::Punct('='), Tok::Str(path)] if attr == "path" => {
1143                out.push(path.clone());
1144            }
1145            [Tok::Ident(attr), Tok::Punct('('), ..] if attr == "cfg_attr" => {
1146                cfg_attr_paths(&toks[..end], start + 1, out);
1147            }
1148            _ => {}
1149        }
1150    }
1151}
1152
1153/// Index of the `;` ending the declaration that starts at `from` (or the end).
1154fn find_semicolon(toks: &[Tok], from: usize) -> usize {
1155    let mut depth = 0usize;
1156    for (k, tok) in toks.iter().enumerate().skip(from) {
1157        match tok {
1158            Tok::Punct('{') => depth += 1,
1159            Tok::Punct('}') => {
1160                if depth == 0 {
1161                    return k;
1162                }
1163                depth -= 1;
1164            }
1165            Tok::Punct(';') if depth == 0 => return k,
1166            _ => {}
1167        }
1168    }
1169    toks.len()
1170}
1171
1172enum UseItem {
1173    Binding(String, UsePath),
1174    Glob(UsePath),
1175}
1176
1177/// Parse one use tree (`a::b::{c, d as e, f::*, self}`) starting at `*i`.
1178fn parse_use_tree(
1179    toks: &[Tok],
1180    i: &mut usize,
1181    mut prefix: Vec<String>,
1182    mut global: bool,
1183    out: &mut Vec<UseItem>,
1184) {
1185    if prefix.is_empty() && toks.get(*i) == Some(&Tok::PathSep) {
1186        global = true;
1187        *i += 1;
1188    }
1189    loop {
1190        match toks.get(*i) {
1191            Some(Tok::Ident(seg)) if toks.get(*i + 1) == Some(&Tok::PathSep) => {
1192                prefix.push(seg.clone());
1193                *i += 2;
1194            }
1195            Some(Tok::Ident(seg)) => {
1196                let seg = seg.clone();
1197                *i += 1;
1198                let alias = if matches!(toks.get(*i), Some(Tok::Ident(a)) if a == "as") {
1199                    let alias = match toks.get(*i + 1) {
1200                        Some(Tok::Ident(a)) => Some(a.clone()),
1201                        _ => None,
1202                    };
1203                    *i += 2;
1204                    alias
1205                } else {
1206                    None
1207                };
1208                let (path, default_name) = if seg == "self" {
1209                    let Some(last) = prefix.last().cloned() else {
1210                        return;
1211                    };
1212                    (prefix, last)
1213                } else {
1214                    let mut path = prefix;
1215                    path.push(seg.clone());
1216                    (path, seg)
1217                };
1218                out.push(UseItem::Binding(
1219                    alias.unwrap_or(default_name),
1220                    UsePath { segs: path, global },
1221                ));
1222                return;
1223            }
1224            Some(Tok::Punct('*')) => {
1225                *i += 1;
1226                if !prefix.is_empty() {
1227                    out.push(UseItem::Glob(UsePath {
1228                        segs: prefix,
1229                        global,
1230                    }));
1231                }
1232                return;
1233            }
1234            Some(Tok::Punct('{')) => {
1235                *i += 1;
1236                loop {
1237                    match toks.get(*i) {
1238                        None => return,
1239                        Some(Tok::Punct('}')) => {
1240                            *i += 1;
1241                            return;
1242                        }
1243                        Some(Tok::Punct(',')) => *i += 1,
1244                        Some(_) => {
1245                            let before = *i;
1246                            parse_use_tree(toks, i, prefix.clone(), global, out);
1247                            if *i == before {
1248                                *i += 1;
1249                            }
1250                        }
1251                    }
1252                }
1253            }
1254            _ => return,
1255        }
1256    }
1257}
1258
1259#[cfg(test)]
1260#[path = "rust_modules_tests.rs"]
1261mod tests;