lean-ctx-engine 3.12.13

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
// SPDX-License-Identifier: Apache-2.0
//! Structural Rust module resolution for the project graph (gh-2269).
//!
//! Rust import edges cannot be derived from a `use` string alone: the same
//! module is reached through `crate::`, `super::`, `self::`, a workspace crate
//! name, a `pub use` re-export chain or a glob, and a module's file depends on
//! `foo.rs` vs `foo/mod.rs` and `#[path]`. This resolver builds the module tree
//! of every Cargo target in the project (no compiler, no build scripts) and
//! resolves each `use` path and each fully qualified path in code to the file
//! that *defines* the named item:
//!
//! - crate roots come from each `Cargo.toml` (`[lib]`, bins, tests, examples,
//!   benches, build script), workspace crates are named by their library name
//!   with `-` mapped to `_`, renamed dependencies (`package = "…"`) included;
//! - `mod x;` follows `x.rs`, `x/mod.rs` and `#[path = "…"]`; a
//!   `#[cfg_attr(…, path = "…")]` target is an additional file of the same
//!   module (the configuration is not evaluated, so every existing candidate
//!   is loaded and the module is their union); inline `mod x { … }` blocks are
//!   modules of their own (so `super::` inside an inline `mod tests` is the
//!   file's module);
//! - `pub use` re-exports and globs are followed up to four hops;
//! - strings and comments are skipped, so a module named only in a comment or a
//!   string is not a dependency.
//!
//! Facade modules — crate roots and `mod.rs` files that declare child files —
//! never receive an import edge: almost every file reaches its imports through
//! them, and an edge there would make every impact the whole workspace. Their
//! `mod` declarations are still recorded as `module` edges.

use std::collections::{HashMap, HashSet, VecDeque};
use std::path::Path;

/// `use` re-export / glob hops followed to the defining module.
const MAX_REEXPORT_HOPS: u8 = 4;
/// Size cap for a manifest read from disk.
const MAX_MANIFEST_BYTES: u64 = 1024 * 1024;
/// Size cap for a source read from disk (matches the edge builder's cap).
const MAX_SOURCE_BYTES: u64 = 2 * 1024 * 1024;

/// Edges and coverage produced by [`resolve_workspace`].
#[derive(Debug, Default)]
pub struct RustModuleGraph {
    /// `(from, to)` file pairs: `from` names an item defined in `to` through a
    /// `use` path or a fully qualified path. Sorted, deduplicated, no self edges.
    pub imports: Vec<(String, String)>,
    /// `(parent, child)` file pairs for `mod child;` declarations (incl.
    /// `#[path]`). Sorted and deduplicated.
    pub modules: Vec<(String, String)>,
    /// Every `.rs` file placed in a crate's module tree. Only these files have
    /// structurally resolved imports; for any other `.rs` file dependents are
    /// unknown.
    pub mapped: HashSet<String>,
    /// Crate roots and `mod.rs` files with child files (see module docs).
    pub facades: HashSet<String>,
}

/// Graph edge kind of a resolved Rust use (`(from, to)` in [`RustModuleGraph::imports`]).
pub const IMPORT_EDGE_KIND: &str = "import";
/// Weight of an [`IMPORT_EDGE_KIND`] edge in the project graph.
pub const IMPORT_EDGE_WEIGHT: f32 = 1.0;
/// Graph edge kind of a `mod child;` declaration (`(parent, child)` in [`RustModuleGraph::modules`]).
pub const MODULE_EDGE_KIND: &str = "module";
/// Weight of a [`MODULE_EDGE_KIND`] edge in the project graph.
pub const MODULE_EDGE_WEIGHT: f32 = 0.8;

impl RustModuleGraph {
    /// The resolved edges as project-graph edges, imports first, each list in
    /// its sorted order. Every graph builder (the `graph_index` scan and the
    /// `ctx_impact` property-graph build) records Rust edges through this one
    /// conversion, so both answer the same impact question identically.
    pub fn index_edges(&self) -> Vec<super::IndexEdge> {
        let edge = |(from, to): &(String, String), kind: &str, weight: f32| super::IndexEdge {
            from: from.clone(),
            to: to.clone(),
            kind: kind.to_string(),
            weight,
        };
        self.imports
            .iter()
            .map(|pair| edge(pair, IMPORT_EDGE_KIND, IMPORT_EDGE_WEIGHT))
            .chain(
                self.modules
                    .iter()
                    .map(|pair| edge(pair, MODULE_EDGE_KIND, MODULE_EDGE_WEIGHT)),
            )
            .collect()
    }
}

/// Why the dependents of a Rust file cannot be listed from the resolved
/// graph, or `None` when they can. `declared`: some file declares it with
/// `mod` (it has an incoming [`MODULE_EDGE_KIND`] edge); `declares_children`:
/// it declares child files itself. Every impact answer for a `.rs` file asks
/// this before it may say that nothing depends on the file.
pub fn unresolved_dependents_reason(
    declared: bool,
    declares_children: bool,
) -> Option<&'static str> {
    match (declared, declares_children) {
        (true, _) => None,
        (false, true) => Some(
            "it is a crate root; uses of its items are recorded against the modules that define them",
        ),
        (false, false) => Some(
            "it is not reached from any crate root's module tree, so Rust paths to it are not resolved",
        ),
    }
}

/// The advice that follows an unknown-dependents answer.
pub const UNKNOWN_DEPENDENTS_ADVICE: &str =
    "Search for its module path (e.g. `git grep`) before assuming nothing depends on it.";

/// Resolve the Rust module graph of every Cargo target below `root`.
///
/// `rs_files` are project-relative paths as the caller keys them (`\` on
/// Windows, where the graph index keeps the platform separator); `contents`
/// is an optional in-memory cache keyed the same way (files missing from it
/// are read from disk, size-capped). The graph names every file by the
/// caller's own key.
pub fn resolve_workspace(
    root: &Path,
    rs_files: &[String],
    contents: &HashMap<String, String>,
) -> RustModuleGraph {
    if !rs_files.iter().any(|f| f.contains('\\')) {
        return resolve_slash_separated(root, rs_files, contents);
    }
    // The resolver joins and splits module paths on `/`: resolve under
    // `/`-separated names, then hand every file back under the caller's key.
    let caller_key: HashMap<String, &String> =
        rs_files.iter().map(|f| (f.replace('\\', "/"), f)).collect();
    let files: Vec<String> = rs_files.iter().map(|f| f.replace('\\', "/")).collect();
    let slash_contents: HashMap<String, String> = contents
        .iter()
        .map(|(f, text)| (f.replace('\\', "/"), text.clone()))
        .collect();
    let graph = resolve_slash_separated(root, &files, &slash_contents);
    let key = |f: &String| {
        caller_key
            .get(f)
            .map_or_else(|| f.clone(), |k| (*k).clone())
    };
    let pairs = |list: Vec<(String, String)>| {
        let mut out: Vec<(String, String)> = list.iter().map(|(a, b)| (key(a), key(b))).collect();
        out.sort();
        out.dedup();
        out
    };
    RustModuleGraph {
        imports: pairs(graph.imports),
        modules: pairs(graph.modules),
        mapped: graph.mapped.iter().map(key).collect(),
        facades: graph.facades.iter().map(key).collect(),
    }
}

/// [`resolve_workspace`] for `/`-separated project-relative paths.
fn resolve_slash_separated(
    root: &Path,
    rs_files: &[String],
    contents: &HashMap<String, String>,
) -> RustModuleGraph {
    let file_set: HashSet<&str> = rs_files
        .iter()
        .map(String::as_str)
        .filter(|f| is_rs(f))
        .collect();
    if file_set.is_empty() {
        return RustModuleGraph::default();
    }
    let manifests = discover_manifests(root, &file_set);
    let mut tree = ModuleTree::default();
    for (crate_idx, krate) in manifests.crates.iter().enumerate() {
        tree.load_crate(crate_idx, &krate.root_file, root, &file_set, contents);
    }
    for (name, crate_idx) in &manifests.externs {
        if let Some(&root_mod) = tree.crate_roots.get(crate_idx) {
            tree.externs.insert(name.clone(), root_mod);
        }
    }
    tree.into_graph()
}

fn is_rs(path: &str) -> bool {
    Path::new(path)
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("rs"))
}

// ---------------------------------------------------------------------------
// Manifests
// ---------------------------------------------------------------------------

struct CrateTarget {
    /// Project-relative path of the target's root source file.
    root_file: String,
}

#[derive(Default)]
struct Manifests {
    crates: Vec<CrateTarget>,
    /// Extern crate name (library name or dependency alias) -> index into
    /// `crates` of the library target it names.
    externs: HashMap<String, usize>,
}

fn join_rel(dir: &str, rest: &str) -> String {
    let joined = if dir.is_empty() {
        rest.to_string()
    } else {
        format!("{dir}/{rest}")
    };
    normalize_rel(&joined)
}

/// Collapse `.` and `..` segments of a `/`-separated relative path.
fn normalize_rel(path: &str) -> String {
    let mut parts: Vec<&str> = Vec::new();
    for seg in path.split(['/', '\\']) {
        match seg {
            "" | "." => {}
            ".." => {
                parts.pop();
            }
            s => parts.push(s),
        }
    }
    parts.join("/")
}

fn parent_dir(file: &str) -> &str {
    file.rsplit_once('/').map_or("", |(dir, _)| dir)
}

fn crate_ident(name: &str) -> String {
    name.replace('-', "_")
}

fn read_capped(path: &Path, cap: u64) -> Option<String> {
    let meta = path.metadata().ok()?;
    if !meta.is_file() || meta.len() > cap {
        return None;
    }
    crate::core::text_decode::read_text(path).ok()
}

/// Every `Cargo.toml` in the ancestry of a `.rs` file, parsed into targets.
fn discover_manifests(root: &Path, file_set: &HashSet<&str>) -> Manifests {
    let mut dirs: HashSet<&str> = HashSet::new();
    for file in file_set {
        let mut dir = parent_dir(file);
        loop {
            if !dirs.insert(dir) {
                break;
            }
            if dir.is_empty() {
                break;
            }
            dir = parent_dir(dir);
        }
    }
    let mut manifest_dirs: Vec<&str> = dirs
        .into_iter()
        .filter(|dir| root.join(dir).join("Cargo.toml").is_file())
        .collect();
    manifest_dirs.sort_unstable();

    let mut out = Manifests::default();
    let mut lib_of_package: HashMap<String, usize> = HashMap::new();
    let mut aliases: Vec<(String, String)> = Vec::new();
    let mut seen_roots: HashSet<String> = HashSet::new();

    for dir in manifest_dirs {
        let Some(text) = read_capped(&root.join(dir).join("Cargo.toml"), MAX_MANIFEST_BYTES) else {
            continue;
        };
        let Ok(manifest) = text.parse::<toml::Table>() else {
            continue;
        };
        collect_aliases(&manifest, &mut aliases);
        let Some(package) = manifest.get("package").and_then(toml::Value::as_table) else {
            continue;
        };
        let Some(package_name) = package.get("name").and_then(toml::Value::as_str) else {
            continue;
        };
        let mut push_root = |file: String, out: &mut Manifests| -> Option<usize> {
            if !file_set.contains(file.as_str()) || !seen_roots.insert(file.clone()) {
                return None;
            }
            out.crates.push(CrateTarget { root_file: file });
            Some(out.crates.len() - 1)
        };

        // Library target.
        let lib = manifest.get("lib").and_then(toml::Value::as_table);
        let lib_path = lib
            .and_then(|l| l.get("path"))
            .and_then(toml::Value::as_str)
            .map_or_else(|| join_rel(dir, "src/lib.rs"), |p| join_rel(dir, p));
        let lib_name = lib
            .and_then(|l| l.get("name"))
            .and_then(toml::Value::as_str)
            .map_or_else(|| crate_ident(package_name), crate_ident);
        if let Some(idx) = push_root(lib_path, &mut out) {
            out.externs.entry(lib_name).or_insert(idx);
            lib_of_package.insert(crate_ident(package_name), idx);
        }

        // Explicit [[bin]]/[[test]]/[[example]]/[[bench]] paths.
        for section in ["bin", "test", "example", "bench"] {
            for target in manifest
                .get(section)
                .and_then(toml::Value::as_array)
                .into_iter()
                .flatten()
                .filter_map(toml::Value::as_table)
            {
                if let Some(path) = target.get("path").and_then(toml::Value::as_str) {
                    push_root(join_rel(dir, path), &mut out);
                } else if section == "bin"
                    && let Some(name) = target.get("name").and_then(toml::Value::as_str)
                {
                    push_root(join_rel(dir, &format!("src/bin/{name}.rs")), &mut out);
                    push_root(join_rel(dir, &format!("src/bin/{name}/main.rs")), &mut out);
                }
            }
        }

        // Auto-discovered targets.
        push_root(join_rel(dir, "src/main.rs"), &mut out);
        match package.get("build") {
            Some(toml::Value::String(path)) => {
                push_root(join_rel(dir, path), &mut out);
            }
            Some(toml::Value::Boolean(false)) => {}
            _ => {
                push_root(join_rel(dir, "build.rs"), &mut out);
            }
        }
        for target_dir in ["src/bin", "tests", "examples", "benches"] {
            let prefix = format!("{}/", join_rel(dir, target_dir));
            let mut found: Vec<&str> = file_set
                .iter()
                .copied()
                .filter(|f| {
                    f.strip_prefix(prefix.as_str()).is_some_and(|rest| {
                        !rest.contains('/')
                            || (rest.split('/').count() == 2 && rest.ends_with("/main.rs"))
                    })
                })
                .collect();
            found.sort_unstable();
            for file in found {
                push_root(file.to_string(), &mut out);
            }
        }
    }

    for (alias, package) in aliases {
        if let Some(&idx) = lib_of_package.get(&package) {
            out.externs.entry(alias).or_insert(idx);
        }
    }
    out
}

/// Renamed dependencies (`alias = { package = "real" }`) in every dependency
/// table of a manifest, as `(alias, package)` crate identifiers.
fn collect_aliases(manifest: &toml::Table, out: &mut Vec<(String, String)>) {
    fn from_deps(deps: Option<&toml::Value>, out: &mut Vec<(String, String)>) {
        let Some(deps) = deps.and_then(toml::Value::as_table) else {
            return;
        };
        for (alias, spec) in deps {
            if let Some(package) = spec
                .as_table()
                .and_then(|t| t.get("package"))
                .and_then(toml::Value::as_str)
            {
                out.push((crate_ident(alias), crate_ident(package)));
            }
        }
    }
    for table in ["dependencies", "dev-dependencies", "build-dependencies"] {
        from_deps(manifest.get(table), out);
    }
    if let Some(targets) = manifest.get("target").and_then(toml::Value::as_table) {
        for spec in targets.values().filter_map(toml::Value::as_table) {
            for table in ["dependencies", "dev-dependencies", "build-dependencies"] {
                from_deps(spec.get(table), out);
            }
        }
    }
    if let Some(workspace) = manifest.get("workspace").and_then(toml::Value::as_table) {
        from_deps(workspace.get("dependencies"), out);
    }
}

// ---------------------------------------------------------------------------
// Lexer
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq)]
enum Tok {
    Ident(String),
    Str(String),
    PathSep,
    Punct(char),
}

fn is_ident_start(b: u8) -> bool {
    b.is_ascii_alphabetic() || b == b'_' || b >= 0x80
}

fn is_ident_continue(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_' || b >= 0x80
}

/// Tokens of a Rust source with comments, literals and lifetimes dropped
/// (string literal contents are kept for `#[path = "…"]`).
fn lex(src: &str) -> Vec<Tok> {
    let b = src.as_bytes();
    let n = b.len();
    let mut out = Vec::new();
    let mut i = 0;
    while i < n {
        let c = b[i];
        if c.is_ascii_whitespace() {
            i += 1;
        } else if c == b'/' && b.get(i + 1) == Some(&b'/') {
            while i < n && b[i] != b'\n' {
                i += 1;
            }
        } else if c == b'/' && b.get(i + 1) == Some(&b'*') {
            let mut depth = 1usize;
            i += 2;
            while i < n && depth > 0 {
                if b[i] == b'/' && b.get(i + 1) == Some(&b'*') {
                    depth += 1;
                    i += 2;
                } else if b[i] == b'*' && b.get(i + 1) == Some(&b'/') {
                    depth -= 1;
                    i += 2;
                } else {
                    i += 1;
                }
            }
        } else if let Some((value, end)) = lex_string_literal(src, i) {
            out.push(Tok::Str(value));
            i = end;
        } else if c == b'\'' {
            i = skip_char_or_lifetime(b, i);
        } else if c == b'r'
            && b.get(i + 1) == Some(&b'#')
            && b.get(i + 2).is_some_and(|&x| is_ident_start(x))
        {
            let start = i + 2;
            i = start;
            while i < n && is_ident_continue(b[i]) {
                i += 1;
            }
            out.push(Tok::Ident(src[start..i].to_string()));
        } else if is_ident_start(c) {
            let start = i;
            while i < n && is_ident_continue(b[i]) {
                i += 1;
            }
            out.push(Tok::Ident(src[start..i].to_string()));
        } else if c.is_ascii_digit() {
            while i < n && is_ident_continue(b[i]) {
                i += 1;
            }
        } else if c == b':' && b.get(i + 1) == Some(&b':') {
            out.push(Tok::PathSep);
            i += 2;
        } else {
            out.push(Tok::Punct(char::from(c)));
            i += 1;
        }
    }
    out
}

/// A string literal (`"…"`, `b"…"`, `c"…"`, raw `r#"…"#` and its byte/C
/// forms) starting at `i`: its contents and the index after it.
fn lex_string_literal(src: &str, i: usize) -> Option<(String, usize)> {
    let bytes = src.as_bytes();
    let mut pos = i;
    if matches!(bytes.get(pos), Some(b'b' | b'c')) {
        pos += 1;
    }
    if bytes.get(pos) == Some(&b'r') {
        let mut open = pos + 1;
        let mut hashes = 0usize;
        while bytes.get(open) == Some(&b'#') {
            hashes += 1;
            open += 1;
        }
        if bytes.get(open) != Some(&b'"') {
            return None;
        }
        let start = open + 1;
        let mut scan = start;
        while scan < bytes.len() {
            if bytes[scan] == b'"' && (1..=hashes).all(|h| bytes.get(scan + h) == Some(&b'#')) {
                return Some((src[start..scan].to_string(), scan + 1 + hashes));
            }
            scan += 1;
        }
        return Some((src[start..].to_string(), bytes.len()));
    }
    if bytes.get(pos) != Some(&b'"') {
        return None;
    }
    let start = pos + 1;
    let mut scan = start;
    while scan < bytes.len() {
        match bytes[scan] {
            b'\\' => scan += 2,
            b'"' => return Some((src[start..scan].to_string(), scan + 1)),
            _ => scan += 1,
        }
    }
    Some((src[start.min(bytes.len())..].to_string(), bytes.len()))
}

/// Skip a char literal (`'a'`, `'\n'`, `'\u{..}'`) or a lifetime (`'a`)
/// starting at the quote `i`; returns the index after it.
fn skip_char_or_lifetime(b: &[u8], i: usize) -> usize {
    let n = b.len();
    if b.get(i + 1) == Some(&b'\\') {
        // Skip the escaped character itself, then scan to the closing quote.
        let mut m = i + 3;
        while m < n && b[m] != b'\'' && b[m] != b'\n' {
            m += 1;
        }
        return (m + 1).min(n);
    }
    // One (possibly multi-byte) character followed by a closing quote.
    let mut next = i + 2;
    while next < n && (b[next] & 0xC0) == 0x80 {
        next += 1;
    }
    if b.get(next) == Some(&b'\'') {
        return next + 1;
    }
    let mut m = i + 1;
    while m < n && is_ident_continue(b[m]) {
        m += 1;
    }
    m.max(i + 1)
}

// ---------------------------------------------------------------------------
// Module tree
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
struct UsePath {
    segs: Vec<String>,
    /// Leading `::` (extern crate only).
    global: bool,
}

#[derive(Debug)]
struct Module {
    crate_idx: usize,
    /// File that holds this module's items (inline modules share their file).
    file: String,
    parent: Option<usize>,
    /// Directory where `mod x;` children of this module are looked up.
    child_dir: String,
    children: HashMap<String, usize>,
    items: HashSet<String>,
    bindings: Vec<(String, UsePath)>,
    globs: Vec<UsePath>,
    /// Paths whose target this module's file depends on.
    refs: Vec<UsePath>,
    /// Other files of the same `mod x;` declaration (`#[cfg_attr(…, path)]`
    /// candidates); a name visible in any of them is visible in the module.
    alternates: Vec<usize>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Res {
    Module(usize),
    /// An item defined in this module.
    Item(usize),
    /// The path reached this module, but its next segment is not visible to
    /// the parser (e.g. generated by a macro).
    Partial(usize),
}

#[derive(Debug, Clone, Copy)]
enum Scope {
    Module(usize),
    /// A macro invocation body (`cfg_if! { … }`): items stay module items.
    MacroBody,
    /// Any other block (fn body, impl, struct, trait): not module items.
    Block,
}

const ITEM_KEYWORDS: [&str; 8] = [
    "fn", "struct", "enum", "trait", "type", "const", "static", "union",
];

const KEYWORDS: [&str; 12] = [
    "fn", "struct", "enum", "trait", "type", "const", "static", "union", "unsafe", "async",
    "extern", "mut",
];

/// `#[path]` attributes seen since the last item, for the next `mod x;`.
#[derive(Default)]
struct PendingPaths {
    /// `#[path = "…"]`.
    plain: Option<String>,
    /// `path = "…"` inside `#[cfg_attr(…)]`, in source order.
    cfg: Vec<String>,
}

#[derive(Default)]
struct ModuleTree {
    modules: Vec<Module>,
    /// Crate index -> its root module.
    crate_roots: HashMap<usize, usize>,
    externs: HashMap<String, usize>,
    module_edges: Vec<(String, String)>,
    mapped: HashSet<String>,
    facades: HashSet<String>,
}

impl ModuleTree {
    fn new_module(
        &mut self,
        crate_idx: usize,
        file: &str,
        parent: Option<usize>,
        child_dir: String,
    ) -> usize {
        self.modules.push(Module {
            crate_idx,
            file: file.to_string(),
            parent,
            child_dir,
            children: HashMap::new(),
            items: HashSet::new(),
            bindings: Vec::new(),
            globs: Vec::new(),
            refs: Vec::new(),
            alternates: Vec::new(),
        });
        self.modules.len() - 1
    }

    fn load_crate(
        &mut self,
        crate_idx: usize,
        root_file: &str,
        root: &Path,
        file_set: &HashSet<&str>,
        contents: &HashMap<String, String>,
    ) {
        let root_mod = self.new_module(
            crate_idx,
            root_file,
            None,
            parent_dir(root_file).to_string(),
        );
        self.crate_roots.insert(crate_idx, root_mod);
        self.facades.insert(root_file.to_string());
        let mut loaded: HashSet<String> = HashSet::new();
        let mut queue: VecDeque<(usize, String)> = VecDeque::new();
        queue.push_back((root_mod, root_file.to_string()));
        while let Some((module, file)) = queue.pop_front() {
            if !loaded.insert(file.clone()) {
                continue;
            }
            let text = match contents.get(&file) {
                Some(cached) => Some(std::borrow::Cow::Borrowed(cached.as_str())),
                None => {
                    read_capped(&root.join(&file), MAX_SOURCE_BYTES).map(std::borrow::Cow::Owned)
                }
            };
            let Some(text) = text else { continue };
            self.mapped.insert(file.clone());
            let children = self.parse_file(module, &file, &lex(&text), file_set);
            if !children.is_empty() && file.rsplit('/').next() == Some("mod.rs") {
                self.facades.insert(file.clone());
            }
            for (child, child_file) in children {
                self.module_edges.push((file.clone(), child_file.clone()));
                if !loaded.contains(&child_file) {
                    queue.push_back((child, child_file));
                }
            }
        }
    }

    /// Record the items, `use` declarations, paths and child modules of one
    /// file; returns the file child modules declared in it.
    fn parse_file(
        &mut self,
        file_module: usize,
        file: &str,
        toks: &[Tok],
        file_set: &HashSet<&str>,
    ) -> Vec<(usize, String)> {
        let crate_idx = self.modules[file_module].crate_idx;
        let mut children = Vec::new();
        let mut stack: Vec<Scope> = vec![Scope::Module(file_module)];
        let mut pending = PendingPaths::default();
        let mut i = 0usize;
        let current = |stack: &[Scope]| -> usize {
            stack
                .iter()
                .rev()
                .find_map(|s| match s {
                    Scope::Module(m) => Some(*m),
                    _ => None,
                })
                .unwrap_or(file_module)
        };
        let ident_at = |k: usize| -> Option<&str> {
            match toks.get(k) {
                Some(Tok::Ident(s)) => Some(s.as_str()),
                _ => None,
            }
        };
        while i < toks.len() {
            let tok = &toks[i];
            match tok {
                Tok::Punct('#') => {
                    let mut j = i + 1;
                    if toks.get(j) == Some(&Tok::Punct('!')) {
                        j += 1;
                    }
                    if toks.get(j) != Some(&Tok::Punct('[')) {
                        i += 1;
                        continue;
                    }
                    let end = matching_close(toks, j, '[', ']');
                    if end == j + 5
                        && ident_at(j + 1) == Some("path")
                        && toks.get(j + 2) == Some(&Tok::Punct('='))
                        && let Some(Tok::Str(path)) = toks.get(j + 3)
                    {
                        pending.plain = Some(path.clone());
                    } else if ident_at(j + 1) == Some("cfg_attr")
                        && toks.get(j + 2) == Some(&Tok::Punct('('))
                    {
                        cfg_attr_paths(&toks[..end], j + 2, &mut pending.cfg);
                    }
                    i = end;
                }
                Tok::Ident(kw) if kw == "mod" => {
                    let module = current(&stack);
                    match (ident_at(i + 1), toks.get(i + 2)) {
                        (Some(name), Some(Tok::Punct(';'))) => {
                            let candidates =
                                self.child_files(module, name, &pending, &stack, file_set);
                            let mut group: Vec<usize> = Vec::with_capacity(candidates.len());
                            for (child_file, child_dir) in candidates {
                                let child = self.new_module(
                                    crate_idx,
                                    &child_file,
                                    Some(module),
                                    child_dir,
                                );
                                if group.is_empty() {
                                    self.modules[module]
                                        .children
                                        .insert(name.to_string(), child);
                                }
                                group.push(child);
                                children.push((child, child_file));
                            }
                            for &member in &group {
                                self.modules[member].alternates =
                                    group.iter().copied().filter(|&m| m != member).collect();
                            }
                            i += 3;
                        }
                        (Some(name), Some(Tok::Punct('{'))) => {
                            let child_dir = join_rel(&self.modules[module].child_dir, name);
                            let child = self.new_module(crate_idx, file, Some(module), child_dir);
                            self.modules[module]
                                .children
                                .insert(name.to_string(), child);
                            stack.push(Scope::Module(child));
                            i += 3;
                        }
                        _ => i += 1,
                    }
                    pending = PendingPaths::default();
                }
                Tok::Ident(kw) if kw == "use" && !prev_is(toks, i, &Tok::PathSep) => {
                    let module = current(&stack);
                    let end = find_semicolon(toks, i + 1);
                    let mut items = Vec::new();
                    let mut k = i + 1;
                    parse_use_tree(&toks[..end], &mut k, Vec::new(), false, &mut items);
                    let m = &mut self.modules[module];
                    for item in items {
                        match item {
                            UseItem::Binding(name, path) => {
                                m.refs.push(path.clone());
                                m.bindings.push((name, path));
                            }
                            UseItem::Glob(path) => {
                                m.refs.push(path.clone());
                                m.globs.push(path);
                            }
                        }
                    }
                    pending = PendingPaths::default();
                    i = end + 1;
                }
                Tok::Ident(kw) if kw == "extern" && ident_at(i + 1) == Some("crate") => {
                    let module = current(&stack);
                    if let Some(name) = ident_at(i + 2).filter(|n| *n != "self") {
                        let alias = if ident_at(i + 3) == Some("as") {
                            ident_at(i + 4).unwrap_or(name)
                        } else {
                            name
                        };
                        self.modules[module].bindings.push((
                            alias.to_string(),
                            UsePath {
                                segs: vec![name.to_string()],
                                global: true,
                            },
                        ));
                    }
                    i = find_semicolon(toks, i) + 1;
                }
                Tok::Ident(kw)
                    if ITEM_KEYWORDS.contains(&kw.as_str())
                        && !matches!(stack.last(), Some(Scope::Block)) =>
                {
                    if let Some(name) =
                        ident_at(i + 1).filter(|n| !KEYWORDS.contains(n) && *n != "_")
                    {
                        let module = current(&stack);
                        self.modules[module].items.insert(name.to_string());
                    }
                    i += 1;
                }
                Tok::Ident(kw)
                    if kw == "macro_rules"
                        && toks.get(i + 1) == Some(&Tok::Punct('!'))
                        && !matches!(stack.last(), Some(Scope::Block)) =>
                {
                    if let Some(name) = ident_at(i + 2) {
                        let module = current(&stack);
                        self.modules[module].items.insert(name.to_string());
                    }
                    i += 2;
                }
                Tok::Ident(first)
                    if toks.get(i + 1) == Some(&Tok::PathSep)
                        && !prev_is(toks, i, &Tok::PathSep)
                        && !prev_is(toks, i, &Tok::Punct('$'))
                        && (i == 0 || ident_at(i - 1) != Some("in"))
                        && first != "Self" =>
                {
                    let mut segs = vec![first.clone()];
                    let mut k = i + 1;
                    while toks.get(k) == Some(&Tok::PathSep) {
                        match toks.get(k + 1) {
                            Some(Tok::Ident(seg)) => {
                                segs.push(seg.clone());
                                k += 2;
                            }
                            _ => break,
                        }
                    }
                    let module = current(&stack);
                    self.modules[module].refs.push(UsePath {
                        segs,
                        global: false,
                    });
                    i = k;
                }
                Tok::Punct('{') => {
                    let macro_body = prev_is(toks, i, &Tok::Punct('!'))
                        || (i >= 2
                            && toks.get(i - 2) == Some(&Tok::Punct('!'))
                            && ident_at(i - 1).is_some());
                    stack.push(if macro_body {
                        Scope::MacroBody
                    } else {
                        Scope::Block
                    });
                    pending = PendingPaths::default();
                    i += 1;
                }
                Tok::Punct('}') => {
                    if stack.len() > 1 {
                        stack.pop();
                    }
                    pending = PendingPaths::default();
                    i += 1;
                }
                Tok::Punct(';') => {
                    pending = PendingPaths::default();
                    i += 1;
                }
                _ => i += 1,
            }
        }
        children
    }

    /// Files and child directories of `mod name;` declared in `module`: the
    /// file Rust loads without configuration (`#[path]`, else `name.rs` /
    /// `name/mod.rs`) first, then each existing `#[cfg_attr(…, path)]`
    /// target. Missing files are skipped; duplicates are listed once.
    fn child_files(
        &self,
        module: usize,
        name: &str,
        pending: &PendingPaths,
        stack: &[Scope],
        file_set: &HashSet<&str>,
    ) -> Vec<(String, String)> {
        let m = &self.modules[module];
        // Outside inline modules `#[path]` is relative to the declaring
        // file's directory; inside them, to the inline module's directory.
        let inline = stack
            .iter()
            .filter(|s| matches!(s, Scope::Module(_)))
            .count()
            > 1;
        let path_base = if inline {
            m.child_dir.as_str()
        } else {
            parent_dir(&m.file)
        };
        let by_path = |path: &str| -> Option<(String, String)> {
            let file = join_rel(path_base, path);
            file_set
                .contains(file.as_str())
                .then(|| (file.clone(), parent_dir(&file).to_string()))
        };

        let mut out: Vec<(String, String)> = Vec::new();
        let primary = if let Some(path) = pending.plain.as_deref() {
            by_path(path)
        } else {
            let child_dir = join_rel(&m.child_dir, name);
            let flat = join_rel(&m.child_dir, &format!("{name}.rs"));
            let nested = join_rel(&child_dir, "mod.rs");
            if file_set.contains(flat.as_str()) {
                Some((flat, child_dir))
            } else {
                file_set
                    .contains(nested.as_str())
                    .then_some((nested, child_dir))
            }
        };
        out.extend(primary);
        for path in &pending.cfg {
            if let Some(candidate) = by_path(path)
                && !out.iter().any(|(file, _)| *file == candidate.0)
            {
                out.push(candidate);
            }
        }
        out
    }

    // -- resolution --------------------------------------------------------

    fn crate_root(&self, module: usize) -> Option<usize> {
        self.crate_roots
            .get(&self.modules[module].crate_idx)
            .copied()
    }

    fn resolve(&self, from: usize, path: &UsePath, hops: u8) -> Option<Res> {
        let segs = &path.segs;
        let first = segs.first()?;
        let (mut cur, mut idx) = if path.global {
            (*self.externs.get(first)?, 1)
        } else {
            match first.as_str() {
                "crate" => (self.crate_root(from)?, 1),
                "self" => (from, 1),
                "super" => {
                    let mut m = from;
                    let mut k = 0;
                    while segs.get(k).map(String::as_str) == Some("super") {
                        m = self.modules[m].parent?;
                        k += 1;
                    }
                    (m, k)
                }
                name => match self.member(from, name, hops) {
                    Some(Res::Module(m)) => (m, 1),
                    Some(res) => return Some(res),
                    None => (*self.externs.get(name)?, 1),
                },
            }
        };
        while idx < segs.len() {
            match self.member(cur, &segs[idx], hops) {
                Some(Res::Module(m)) => cur = m,
                Some(res) => return Some(res),
                None => return Some(Res::Partial(cur)),
            }
            idx += 1;
        }
        Some(Res::Module(cur))
    }

    /// What `name` means inside `module`: a child module, an item defined
    /// there, or the target of a `use` binding or glob (followed up to
    /// [`MAX_REEXPORT_HOPS`]).
    ///
    /// A module split over several files (`#[cfg_attr(…, path)]`
    /// alternates) is their union: its own file is asked first, then each
    /// alternate in declaration order.
    fn member(&self, module: usize, name: &str, hops: u8) -> Option<Res> {
        let group =
            || std::iter::once(module).chain(self.modules[module].alternates.iter().copied());
        for g in group() {
            let m = &self.modules[g];
            if let Some(&child) = m.children.get(name) {
                return Some(Res::Module(child));
            }
            if m.items.contains(name) {
                return Some(Res::Item(g));
            }
        }
        if hops >= MAX_REEXPORT_HOPS {
            return None;
        }
        for g in group() {
            if let Some((_, path)) = self.modules[g]
                .bindings
                .iter()
                .find(|(bound, _)| bound == name)
            {
                return self.resolve(g, path, hops + 1).and_then(|res| match res {
                    // A binding whose path leaves the parsed tree names nothing here.
                    Res::Partial(_) => None,
                    other => Some(other),
                });
            }
        }
        for g in group() {
            for glob in &self.modules[g].globs {
                if let Some(Res::Module(source)) = self.resolve(g, glob, hops + 1)
                    && !group().any(|member| member == source)
                    && let Some(res) = self.member(source, name, hops + 1)
                {
                    return Some(res);
                }
            }
        }
        None
    }

    fn into_graph(self) -> RustModuleGraph {
        let mut imports: Vec<(String, String)> = Vec::new();
        for (idx, module) in self.modules.iter().enumerate() {
            for path in &module.refs {
                let Some(res) = self.resolve(idx, path, 0) else {
                    continue;
                };
                let (Res::Module(target) | Res::Item(target) | Res::Partial(target)) = res;
                let target_file = &self.modules[target].file;
                if *target_file == module.file || self.facades.contains(target_file) {
                    continue;
                }
                imports.push((module.file.clone(), target_file.clone()));
            }
        }
        imports.sort();
        imports.dedup();
        let mut modules = self.module_edges;
        modules.sort();
        modules.dedup();
        RustModuleGraph {
            imports,
            modules,
            mapped: self.mapped,
            facades: self.facades,
        }
    }
}

fn prev_is(toks: &[Tok], i: usize, tok: &Tok) -> bool {
    i > 0 && toks.get(i - 1) == Some(tok)
}

/// Index of the token after the bracket matching `toks[open]`.
fn matching_close(toks: &[Tok], open: usize, open_ch: char, close_ch: char) -> usize {
    let mut depth = 0usize;
    for (k, tok) in toks.iter().enumerate().skip(open) {
        if *tok == Tok::Punct(open_ch) {
            depth += 1;
        } else if *tok == Tok::Punct(close_ch) {
            depth -= 1;
            if depth == 0 {
                return k + 1;
            }
        }
    }
    toks.len()
}

/// `path = "…"` values of the `cfg_attr(predicate, attr, …)` whose `(` is at
/// `toks[open]`, nested `cfg_attr`s included. The predicate is not evaluated.
fn cfg_attr_paths(toks: &[Tok], open: usize, out: &mut Vec<String>) {
    let close = matching_close(toks, open, '(', ')').saturating_sub(1);
    let mut depth = 0usize;
    let mut seg_start = open + 1;
    let mut predicate = true;
    let mut segments: Vec<(usize, usize)> = Vec::new();
    for (k, tok) in toks.iter().enumerate().take(close).skip(open + 1) {
        match tok {
            Tok::Punct('(' | '[' | '{') => depth += 1,
            Tok::Punct(')' | ']' | '}') => depth = depth.saturating_sub(1),
            Tok::Punct(',') if depth == 0 => {
                if !predicate {
                    segments.push((seg_start, k));
                }
                predicate = false;
                seg_start = k + 1;
            }
            _ => {}
        }
    }
    if !predicate {
        segments.push((seg_start, close));
    }
    for (start, end) in segments {
        match &toks[start..end] {
            [Tok::Ident(attr), Tok::Punct('='), Tok::Str(path)] if attr == "path" => {
                out.push(path.clone());
            }
            [Tok::Ident(attr), Tok::Punct('('), ..] if attr == "cfg_attr" => {
                cfg_attr_paths(&toks[..end], start + 1, out);
            }
            _ => {}
        }
    }
}

/// Index of the `;` ending the declaration that starts at `from` (or the end).
fn find_semicolon(toks: &[Tok], from: usize) -> usize {
    let mut depth = 0usize;
    for (k, tok) in toks.iter().enumerate().skip(from) {
        match tok {
            Tok::Punct('{') => depth += 1,
            Tok::Punct('}') => {
                if depth == 0 {
                    return k;
                }
                depth -= 1;
            }
            Tok::Punct(';') if depth == 0 => return k,
            _ => {}
        }
    }
    toks.len()
}

enum UseItem {
    Binding(String, UsePath),
    Glob(UsePath),
}

/// Parse one use tree (`a::b::{c, d as e, f::*, self}`) starting at `*i`.
fn parse_use_tree(
    toks: &[Tok],
    i: &mut usize,
    mut prefix: Vec<String>,
    mut global: bool,
    out: &mut Vec<UseItem>,
) {
    if prefix.is_empty() && toks.get(*i) == Some(&Tok::PathSep) {
        global = true;
        *i += 1;
    }
    loop {
        match toks.get(*i) {
            Some(Tok::Ident(seg)) if toks.get(*i + 1) == Some(&Tok::PathSep) => {
                prefix.push(seg.clone());
                *i += 2;
            }
            Some(Tok::Ident(seg)) => {
                let seg = seg.clone();
                *i += 1;
                let alias = if matches!(toks.get(*i), Some(Tok::Ident(a)) if a == "as") {
                    let alias = match toks.get(*i + 1) {
                        Some(Tok::Ident(a)) => Some(a.clone()),
                        _ => None,
                    };
                    *i += 2;
                    alias
                } else {
                    None
                };
                let (path, default_name) = if seg == "self" {
                    let Some(last) = prefix.last().cloned() else {
                        return;
                    };
                    (prefix, last)
                } else {
                    let mut path = prefix;
                    path.push(seg.clone());
                    (path, seg)
                };
                out.push(UseItem::Binding(
                    alias.unwrap_or(default_name),
                    UsePath { segs: path, global },
                ));
                return;
            }
            Some(Tok::Punct('*')) => {
                *i += 1;
                if !prefix.is_empty() {
                    out.push(UseItem::Glob(UsePath {
                        segs: prefix,
                        global,
                    }));
                }
                return;
            }
            Some(Tok::Punct('{')) => {
                *i += 1;
                loop {
                    match toks.get(*i) {
                        None => return,
                        Some(Tok::Punct('}')) => {
                            *i += 1;
                            return;
                        }
                        Some(Tok::Punct(',')) => *i += 1,
                        Some(_) => {
                            let before = *i;
                            parse_use_tree(toks, i, prefix.clone(), global, out);
                            if *i == before {
                                *i += 1;
                            }
                        }
                    }
                }
            }
            _ => return,
        }
    }
}

#[cfg(test)]
#[path = "rust_modules_tests.rs"]
mod tests;