mir-analyzer 0.65.0

Analysis engine for the mir PHP static analyzer
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
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
use php_ast::ast::{BinaryOp, MagicConstKind};
use php_ast::owned::visitor::{walk_owned_expr, OwnedVisitor};
use php_ast::owned::{Expr, ExprKind};
use rustc_hash::FxHashMap;
use std::ops::ControlFlow;
use std::path::{Component, Path, PathBuf};
use thiserror::Error;

// ---------------------------------------------------------------------------
// Error
// ---------------------------------------------------------------------------

#[derive(Debug, Error)]
pub enum ComposerError {
    #[error("composer I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("composer JSON error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("composer.json has no autoload section")]
    MissingAutoload,
}

// ---------------------------------------------------------------------------
// Psr4Map
// ---------------------------------------------------------------------------

/// PSR-4 / PSR-0 / classmap / files autoload mapping, built from `composer.json`
/// and `vendor/composer/installed.json`.
///
/// `project_entries` covers `autoload.psr-4` / `autoload-dev.psr-4` for the
/// project itself; `project_psr0_entries` covers `autoload.psr-0` /
/// `autoload-dev.psr-0` (kept separate because PSR-0 file-path construction
/// differs from PSR-4 — see [`Self::resolve`]). `vendor_entries` /
/// `vendor_psr0_entries` cover the same keys from each installed package.
/// `project_extra_paths` and `vendor_extra_paths` collect the (prefix-less)
/// `classmap` and `files` entries as raw paths, plus the PSR-0 dirs themselves
/// (for bulk file-list walking) — files are kept as-is, dirs are walked when
/// assembling the file list.
///
/// All prefix lists are sorted longest-prefix-first for correct prefix matching.
#[derive(Clone)]
pub struct Psr4Map {
    project_entries: Vec<(String, PathBuf)>,
    vendor_entries: Vec<(String, PathBuf)>,
    project_psr0_entries: Vec<(String, PathBuf)>,
    vendor_psr0_entries: Vec<(String, PathBuf)>,
    project_extra_paths: Vec<PathBuf>,
    vendor_extra_paths: Vec<PathBuf>,
    /// Pre-resolved FQCN → file map from `vendor/composer/autoload_classmap.php`.
    /// Covers packages using `classmap:` autoload (non-PSR-4) so they can be
    /// lazy-loaded by FQCN without parsing every classmap directory eagerly.
    /// Key is the FQCN with single backslashes (e.g. `AWS\\CRT\\Auth\\Signing`
    /// in source becomes `AWS\CRT\Auth\Signing` here, matching what PHP code
    /// uses at call sites).
    classmap: FxHashMap<String, PathBuf>,
    /// Files registered via `autoload.files` (project + vendor). These contain
    /// unbound global functions/constants that are NOT FQCN-resolvable, so they
    /// must be eagerly parsed even in lazy mode. Read from
    /// `vendor/composer/autoload_files.php` if present, falling back to the
    /// per-package `installed.json` walk.
    vendor_eager_files: Vec<PathBuf>,
    #[allow(dead_code)] // used by issue #50 (lazy FQCN resolution)
    root: PathBuf,
}

fn ensure_trailing_backslash(prefix: &str) -> String {
    if prefix.ends_with('\\') {
        prefix.to_string()
    } else {
        format!("{prefix}\\")
    }
}

/// Append `(prefix, base.join(dir))` to `entries` for every dir-string in `value`
/// (which may be a JSON string or an array of strings).
fn collect_prefix_dirs(
    value: &serde_json::Value,
    prefix: &str,
    base: &Path,
    entries: &mut Vec<(String, PathBuf)>,
) {
    let pfx = ensure_trailing_backslash(prefix);
    if let Some(d) = value.as_str() {
        entries.push((pfx, base.join(d)));
    } else if let Some(arr) = value.as_array() {
        for item in arr {
            if let Some(d) = item.as_str() {
                entries.push((pfx.clone(), base.join(d)));
            }
        }
    }
}

/// Same as [`collect_prefix_dirs`] but keeps the prefix exactly as written in
/// `composer.json` (no forced trailing backslash). PSR-0 prefixes are matched
/// as literal string prefixes by Composer — e.g. a PEAR-style `"Old_"` key has
/// no namespace separator at all, so appending one would break prefix matching.
fn collect_prefix_dirs_raw(
    value: &serde_json::Value,
    prefix: &str,
    base: &Path,
    entries: &mut Vec<(String, PathBuf)>,
) {
    if let Some(d) = value.as_str() {
        entries.push((prefix.to_string(), base.join(d)));
    } else if let Some(arr) = value.as_array() {
        for item in arr {
            if let Some(d) = item.as_str() {
                entries.push((prefix.to_string(), base.join(d)));
            }
        }
    }
}

/// Append every string in `value` (a JSON array) to `out` as `base.join(s)`.
fn collect_path_array(value: &serde_json::Value, base: &Path, out: &mut Vec<PathBuf>) {
    if let Some(arr) = value.as_array() {
        for item in arr {
            if let Some(s) = item.as_str() {
                out.push(base.join(s));
            }
        }
    }
}

fn parse_autoload_section(
    autoload: &serde_json::Value,
    base: &Path,
    entries: &mut Vec<(String, PathBuf)>,
    psr0_entries: &mut Vec<(String, PathBuf)>,
    extras: &mut Vec<PathBuf>,
) {
    if let Some(map) = autoload.get("psr-4").and_then(|v| v.as_object()) {
        for (prefix, dir) in map {
            collect_prefix_dirs(dir, prefix, base, entries);
        }
    }
    // PSR-0 maps prefix → dir similarly to PSR-4, but the class-name-to-file
    // resolution differs (namespace separators AND trailing underscores in the
    // class basename become directories — see `psr0_logical_path`), so these
    // go into their own prefix list rather than `entries`. We ALSO keep
    // pushing the raw dirs into `extras` so bulk file discovery (project/vendor
    // file listing) still walks them, same as before.
    if let Some(map) = autoload.get("psr-0").and_then(|v| v.as_object()) {
        for (prefix, dir) in map {
            collect_prefix_dirs_raw(dir, prefix, base, psr0_entries);
            if let Some(d) = dir.as_str() {
                extras.push(base.join(d));
            } else if let Some(arr) = dir.as_array() {
                for item in arr {
                    if let Some(d) = item.as_str() {
                        extras.push(base.join(d));
                    }
                }
            }
        }
    }
    if let Some(cm) = autoload.get("classmap") {
        collect_path_array(cm, base, extras);
    }
    if let Some(files) = autoload.get("files") {
        collect_path_array(files, base, extras);
    }
}

/// Parse a Composer-generated `autoload_classmap.php` or `autoload_files.php`.
///
/// The format is mechanically generated and stable:
///
/// ```text
/// <?php
/// $vendorDir = dirname(__DIR__);
/// $baseDir = dirname($vendorDir);
/// return array(
///     'KEY' => $vendorDir . '/relative/path.php',
///     'OTHER' => $baseDir . '/other/path.php',
/// );
/// ```
///
/// Returns `(key, absolute_path)` pairs. Unparseable lines are silently
/// skipped — a stale or hand-edited file degrades gracefully.
///
/// `key` is returned with PHP-escape-sequence handling for backslashes (`\\` → `\`).
fn parse_composer_autoload_array(
    content: &str,
    vendor_dir: &Path,
    base_dir: &Path,
) -> Vec<(String, PathBuf)> {
    let mut out = Vec::new();
    for line in content.lines() {
        let line = line.trim();
        // Find `'KEY' => $VAR . 'PATH'` or `"KEY" => $VAR . "PATH"`.
        let (key, rest) = match extract_quoted(line) {
            Some(p) => p,
            None => continue,
        };
        let rest = rest.trim_start();
        let rest = match rest.strip_prefix("=>") {
            Some(r) => r.trim_start(),
            None => continue,
        };
        let (var, rest) = match rest.strip_prefix('$') {
            Some(r) => {
                let end = r
                    .find(|c: char| !c.is_ascii_alphanumeric() && c != '_')
                    .unwrap_or(r.len());
                (&r[..end], &r[end..])
            }
            None => continue,
        };
        let rest = rest.trim_start();
        let rest = match rest.strip_prefix('.') {
            Some(r) => r.trim_start(),
            None => continue,
        };
        let (path_frag, _) = match extract_quoted(rest) {
            Some(p) => p,
            None => continue,
        };
        let base = match var {
            "vendorDir" => vendor_dir,
            "baseDir" => base_dir,
            _ => continue,
        };
        // path_frag begins with '/' relative to the chosen base.
        let path_rel = path_frag.trim_start_matches('/');
        out.push((key, base.join(path_rel)));
    }
    out
}

/// Pull a PHP single- or double-quoted string from the start of `s`, decoding
/// `\\` → `\` and `\'` / `\"` → the corresponding quote. Returns `(decoded, tail)`
/// where `tail` is the slice after the closing quote.
fn extract_quoted(s: &str) -> Option<(String, &str)> {
    let mut it = s.char_indices();
    let (_, quote) = it.next()?;
    if quote != '\'' && quote != '"' {
        return None;
    }
    let mut out = String::new();
    let mut escape = false;
    for (i, ch) in it {
        if escape {
            out.push(ch);
            escape = false;
        } else if ch == '\\' {
            escape = true;
        } else if ch == quote {
            return Some((out, &s[i + ch.len_utf8()..]));
        } else {
            out.push(ch);
        }
    }
    None
}

fn parse_vendor(
    root: &Path,
    entries: &mut Vec<(String, PathBuf)>,
    psr0_entries: &mut Vec<(String, PathBuf)>,
    extras: &mut Vec<PathBuf>,
) {
    let installed_path = root.join("vendor/composer/installed.json");
    let content = match std::fs::read_to_string(&installed_path) {
        Ok(c) => c,
        Err(_) => return,
    };
    let value: serde_json::Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(e) => {
            eprintln!(
                "mir: warning: failed to parse {}: {e} (vendor PSR-4 map will be empty)",
                installed_path.display()
            );
            return;
        }
    };

    let packages = if let Some(arr) = value.get("packages").and_then(|v| v.as_array()) {
        arr.clone()
    } else if let Some(arr) = value.as_array() {
        arr.clone()
    } else {
        return;
    };

    let vendor_dir = root.join("vendor");

    for pkg in &packages {
        let pkg_name = pkg.get("name").and_then(|v| v.as_str()).unwrap_or("");
        let pkg_dir = vendor_dir.join(pkg_name);
        if let Some(autoload) = pkg.get("autoload") {
            parse_autoload_section(autoload, &pkg_dir, entries, psr0_entries, extras);
        }
    }
}

/// Read `vendor/composer/autoload_classmap.php`. Returns an empty map if the
/// file is absent or unreadable — callers fall back to the project-defined
/// PSR-4 entries which still cover the typical case.
///
/// Uses lossy UTF-8 decoding because some real-world classmap files contain
/// stray Latin-1 bytes (e.g. Laravel's includes a `\xa9` key from a vendor
/// package). Lossy decoding only affects the malformed FQCN itself — every
/// other entry parses correctly.
fn read_classmap(vendor_dir: &Path, base_dir: &Path) -> FxHashMap<String, PathBuf> {
    let path = vendor_dir.join("composer/autoload_classmap.php");
    let Ok(bytes) = std::fs::read(&path) else {
        return FxHashMap::default();
    };
    let content = String::from_utf8_lossy(&bytes);
    parse_composer_autoload_array(&content, vendor_dir, base_dir)
        .into_iter()
        .collect()
}

/// Read `vendor/composer/autoload_files.php`. Falls back to walking
/// `installed.json` if the generated file is absent — covers projects that
/// haven't run `composer dump-autoload --optimize`.
fn read_files_autoload(vendor_dir: &Path, base_dir: &Path) -> Vec<PathBuf> {
    let path = vendor_dir.join("composer/autoload_files.php");
    if let Ok(bytes) = std::fs::read(&path) {
        let content = String::from_utf8_lossy(&bytes);
        return parse_composer_autoload_array(&content, vendor_dir, base_dir)
            .into_iter()
            .map(|(_, p)| p)
            .filter(|p| p.is_file())
            .collect();
    }
    // Fallback: walk installed.json packages for autoload.files entries only.
    let installed_path = vendor_dir.join("composer/installed.json");
    let content = match std::fs::read_to_string(&installed_path) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };
    let value: serde_json::Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(e) => {
            eprintln!(
                "mir: warning: failed to parse {}: {e} (autoload.files from vendor will be empty)",
                installed_path.display()
            );
            return Vec::new();
        }
    };
    let packages = if let Some(arr) = value.get("packages").and_then(|v| v.as_array()) {
        arr.clone()
    } else if let Some(arr) = value.as_array() {
        arr.clone()
    } else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for pkg in &packages {
        let pkg_name = pkg.get("name").and_then(|v| v.as_str()).unwrap_or("");
        let pkg_dir = vendor_dir.join(pkg_name);
        if let Some(files) = pkg.get("autoload").and_then(|a| a.get("files")) {
            collect_path_array(files, &pkg_dir, &mut out);
        }
    }
    let _ = base_dir; // unused in fallback path (paths are package-relative)
    out.into_iter().filter(|p| p.is_file()).collect()
}

/// Build a PSR-0 relative file path from a class name, per Composer's own
/// `ClassLoader::findFileWithExtension`: namespace separators always become
/// directory separators, but `_` only becomes a directory separator within
/// the last (class-name) segment — a namespaced `App\Foo_Bar` stays
/// `App/Foo_Bar.php`, while a PEAR-style `Foo_Bar` (no namespace) becomes
/// `Foo/Bar.php`.
fn psr0_logical_path(key: &str) -> PathBuf {
    let logical = match key.rfind('\\') {
        Some(pos) => {
            let (namespace, class_name) = key.split_at(pos + 1);
            format!(
                "{}{}",
                namespace.replace('\\', "/"),
                class_name.replace('_', "/")
            )
        }
        None => key.replace('_', "/"),
    };
    PathBuf::from(logical).with_extension("php")
}

impl Psr4Map {
    pub fn from_composer(root: &Path) -> Result<Self, ComposerError> {
        let composer_path = root.join("composer.json");
        let content = std::fs::read_to_string(&composer_path)?;
        let value: serde_json::Value = serde_json::from_str(&content)?;

        let has_autoload = value.get("autoload").is_some() || value.get("autoload-dev").is_some();
        if !has_autoload {
            return Err(ComposerError::MissingAutoload);
        }

        let mut project_entries: Vec<(String, PathBuf)> = Vec::new();
        let mut project_psr0_entries: Vec<(String, PathBuf)> = Vec::new();
        let mut project_extra_paths: Vec<PathBuf> = Vec::new();

        if let Some(autoload) = value.get("autoload") {
            parse_autoload_section(
                autoload,
                root,
                &mut project_entries,
                &mut project_psr0_entries,
                &mut project_extra_paths,
            );
        }
        if let Some(autoload) = value.get("autoload-dev") {
            parse_autoload_section(
                autoload,
                root,
                &mut project_entries,
                &mut project_psr0_entries,
                &mut project_extra_paths,
            );
        }

        project_entries.sort_by_key(|b| std::cmp::Reverse(b.0.len()));
        project_psr0_entries.sort_by_key(|b| std::cmp::Reverse(b.0.len()));

        let mut vendor_entries: Vec<(String, PathBuf)> = Vec::new();
        let mut vendor_psr0_entries: Vec<(String, PathBuf)> = Vec::new();
        let mut vendor_extra_paths: Vec<PathBuf> = Vec::new();
        parse_vendor(
            root,
            &mut vendor_entries,
            &mut vendor_psr0_entries,
            &mut vendor_extra_paths,
        );
        vendor_entries.sort_by_key(|b| std::cmp::Reverse(b.0.len()));
        vendor_psr0_entries.sort_by_key(|b| std::cmp::Reverse(b.0.len()));

        // Read composer-generated FQCN → file map from autoload_classmap.php.
        // When present this is the source of truth for non-PSR-4 vendor classes,
        // letting lazy-mode resolve them without parsing whole classmap dirs.
        let vendor_dir = root.join("vendor");
        let classmap = read_classmap(&vendor_dir, root);

        // Eager-load list = autoload.files entries (project + vendor). These
        // hold unbound globals (functions, constants, polyfills) that the lazy
        // FQCN-based resolver cannot reach.
        let vendor_eager_files = read_files_autoload(&vendor_dir, root);

        Ok(Psr4Map {
            project_entries,
            vendor_entries,
            project_psr0_entries,
            vendor_psr0_entries,
            project_extra_paths,
            vendor_extra_paths,
            classmap,
            vendor_eager_files,
            root: root.to_path_buf(),
        })
    }

    pub fn project_files(&self) -> Vec<PathBuf> {
        let mut out = Vec::new();
        for (_, dir) in &self.project_entries {
            crate::batch::collect_php_files(dir, &mut out);
        }
        for path in &self.project_extra_paths {
            collect_php_path(path, &mut out);
        }
        expand_via_local_requires(&mut out);
        out
    }

    pub fn vendor_files(&self) -> Vec<PathBuf> {
        let mut out = Vec::new();
        for (_, dir) in &self.vendor_entries {
            crate::batch::collect_php_files(dir, &mut out);
        }
        for path in &self.vendor_extra_paths {
            collect_php_path(path, &mut out);
        }
        out
    }

    /// Resolve a fully-qualified class name to a file path using longest-prefix-first matching.
    /// Returns `None` if no prefix matches or the mapped file does not exist on disk.
    ///
    /// Resolution order:
    /// 1. PSR-4 project entries (longest-prefix-first).
    /// 2. PSR-4 vendor entries (longest-prefix-first).
    /// 3. PSR-0 project entries (longest-prefix-first).
    /// 4. PSR-0 vendor entries (longest-prefix-first).
    /// 5. Classmap from `vendor/composer/autoload_classmap.php` — exact FQCN match.
    ///
    /// PSR-4 wins over PSR-0 wins over classmap because Composer's runtime
    /// resolver uses the same order; this matches what the PHP code being
    /// analyzed actually sees.
    pub fn resolve(&self, fqcn: &str) -> Option<PathBuf> {
        let key = fqcn.trim_start_matches('\\');
        for (prefix, dir) in self
            .project_entries
            .iter()
            .chain(self.vendor_entries.iter())
        {
            if key.starts_with(prefix.as_str()) {
                let relative = &key[prefix.len()..];
                let file_path = dir.join(relative.replace('\\', "/")).with_extension("php");
                if file_path.exists() {
                    return Some(file_path);
                }
            }
        }
        for (prefix, dir) in self
            .project_psr0_entries
            .iter()
            .chain(self.vendor_psr0_entries.iter())
        {
            if !prefix.is_empty() && !key.starts_with(prefix.as_str()) {
                continue;
            }
            let file_path = dir.join(psr0_logical_path(key));
            if file_path.exists() {
                return Some(file_path);
            }
        }
        if let Some(path) = self.classmap.get(key) {
            if path.exists() {
                return Some(path.clone());
            }
        }
        None
    }

    /// Vendor files that must be eagerly parsed in lazy mode: `autoload.files`
    /// entries from composer. These hold globals (functions, constants,
    /// polyfills) that the FQCN-based lazy resolver cannot reach because they
    /// have no namespace mapping.
    ///
    /// Returns just the existing `.php` files; missing entries (stale generated
    /// file) are dropped.
    pub fn vendor_eager_files(&self) -> Vec<PathBuf> {
        self.vendor_eager_files.clone()
    }

    /// Every vendor file the analyzer should index eagerly, for the
    /// rust-analyzer-style static-input model: the union of
    ///
    /// 1. [`Self::vendor_files`] — PSR-4 / PSR-0 walked directories + extra paths,
    /// 2. classmap file targets — packages that use `classmap:` autoload (no
    ///    PSR-4 prefix), which [`Self::vendor_files`] does NOT walk, and
    /// 3. [`Self::vendor_eager_files`] — `autoload.files` globals.
    ///
    /// Deduplicated by path. Non-existent classmap targets (stale generated
    /// file) are skipped. This is the work-list a consumer feeds to the chunked
    /// background indexer ([`crate::AnalysisSession::index_batch`]).
    pub fn all_vendor_files(&self) -> Vec<PathBuf> {
        let mut seen: rustc_hash::FxHashSet<PathBuf> = rustc_hash::FxHashSet::default();
        let mut out = Vec::new();
        let mut push = |p: PathBuf, out: &mut Vec<PathBuf>| {
            if seen.insert(p.clone()) {
                out.push(p);
            }
        };
        for p in self.vendor_files() {
            push(p, &mut out);
        }
        // Classmap-only packages are not covered by vendor_files() (which walks
        // only PSR-4/PSR-0 dirs + extra paths). Include their file targets.
        for p in self.classmap.values() {
            if p.is_file() {
                push(p.clone(), &mut out);
            }
        }
        for p in self.vendor_eager_files() {
            push(p, &mut out);
        }
        out
    }

    /// Number of FQCN entries known to the classmap. Used by callers that want
    /// to log/verify the classmap loaded successfully.
    pub fn classmap_len(&self) -> usize {
        self.classmap.len()
    }
}

/// Collect `.php` files from `path`. If `path` is a file, push it directly
/// (when it has a `.php` extension); if it is a directory, walk it.
fn collect_php_path(path: &Path, out: &mut Vec<PathBuf>) {
    let Ok(meta) = std::fs::metadata(path) else {
        return;
    };
    if meta.is_file() {
        if path.extension().and_then(|e| e.to_str()) == Some("php") {
            out.push(path.to_path_buf());
        }
    } else if meta.is_dir() {
        crate::batch::collect_php_files(path, out);
    }
}

/// Follows `require`/`include` targets reaching outside every autoload root
/// (composer.json's autoload sections are otherwise the sole "this file is
/// part of the project" signal) and adds any that resolve to a real `.php`
/// file, recursing since a newly-added file may itself reach further
/// out-of-root files. Only statically-resolvable target shapes are
/// followed: a literal string, and `__DIR__` / `dirname(__FILE__)`
/// concatenated with a literal string — the common manual-bootstrap idiom
/// (e.g. `require_once __DIR__ . '/../legacy/bootstrap.php'`). A bare
/// literal with no `__DIR__` is resolved relative to the including file's
/// own directory, the conventional meaning for this idiom in practice.
/// Files under a `vendor` directory are skipped — those are already reached
/// through the composer autoload machinery, and re-adding them here would
/// double-index vendor code as project code.
fn expand_via_local_requires(out: &mut Vec<PathBuf>) {
    let mut seen: rustc_hash::FxHashSet<PathBuf> = out.iter().cloned().collect();
    let mut queue: Vec<PathBuf> = out.clone();
    while let Some(file) = queue.pop() {
        let Some(dir) = file.parent() else {
            continue;
        };
        let Ok(text) = std::fs::read_to_string(&file) else {
            continue;
        };
        // Cheap bailout: skip the full parse for the (common) majority of
        // files that don't even mention require/include.
        if !text.contains("require") && !text.contains("include") {
            continue;
        }
        let parsed = php_rs_parser::parse(&text);
        let mut scanner = IncludeTargetScanner {
            dir,
            targets: Vec::new(),
        };
        let _ = scanner.visit_program(&parsed.program);
        for target in scanner.targets {
            let resolved = if Path::new(&target).is_absolute() {
                PathBuf::from(target)
            } else {
                dir.join(target)
            };
            let resolved = lexically_normalize(&resolved);
            if resolved.extension().and_then(|e| e.to_str()) != Some("php") {
                continue;
            }
            if resolved.components().any(|c| c.as_os_str() == "vendor") {
                continue;
            }
            if !resolved.is_file() {
                continue;
            }
            if seen.insert(resolved.clone()) {
                out.push(resolved.clone());
                queue.push(resolved);
            }
        }
    }
}

/// Collapses `.`/`..` components lexically instead of relying on the OS to
/// resolve them, since a `__DIR__`-derived base can be a Windows verbatim
/// (`\\?\`-prefixed) path — those disable `..` resolution by the OS, so a
/// naively-concatenated `\\?\C:\...\src/../legacy/helpers.php` would never
/// resolve to a real file even though the target genuinely exists.
fn lexically_normalize(path: &Path) -> PathBuf {
    let mut components = path.components().peekable();
    let mut ret = if let Some(c @ Component::Prefix(_)) = components.peek().copied() {
        components.next();
        PathBuf::from(c.as_os_str())
    } else {
        PathBuf::new()
    };

    for component in components {
        match component {
            Component::Prefix(_) => unreachable!(),
            Component::RootDir => ret.push(component.as_os_str()),
            Component::CurDir => {}
            Component::ParentDir => {
                ret.pop();
            }
            Component::Normal(c) => ret.push(c),
        }
    }
    ret
}

struct IncludeTargetScanner<'a> {
    dir: &'a Path,
    targets: Vec<String>,
}

impl OwnedVisitor for IncludeTargetScanner<'_> {
    fn visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
        if let ExprKind::Include(_, inner) = &expr.kind {
            if let Some(target) = resolve_static_include_target(inner, self.dir) {
                self.targets.push(target);
            }
        }
        walk_owned_expr(self, expr)
    }
}

/// Statically evaluates the include-target expression shapes real code
/// actually uses: a literal string, `__DIR__` / `dirname(__FILE__)`, and `.`
/// concatenations of those. Anything else (a variable, a non-`dirname` call)
/// can't be resolved without running the program, so is left alone.
fn resolve_static_include_target(expr: &Expr, dir: &Path) -> Option<String> {
    match &expr.kind {
        ExprKind::String(s) => Some(s.to_string()),
        ExprKind::MagicConst(MagicConstKind::Dir) => Some(dir.to_string_lossy().into_owned()),
        ExprKind::Parenthesized(inner) => resolve_static_include_target(inner, dir),
        ExprKind::Binary(b) if b.op == BinaryOp::Concat => {
            let left = resolve_static_include_target(&b.left, dir)?;
            let right = resolve_static_include_target(&b.right, dir)?;
            Some(format!("{left}{right}"))
        }
        ExprKind::FunctionCall(call) => {
            let ExprKind::Identifier(name) = &call.name.kind else {
                return None;
            };
            if !name.eq_ignore_ascii_case("dirname") {
                return None;
            }
            let arg = call.args.first()?;
            matches!(arg.value.kind, ExprKind::MagicConst(MagicConstKind::File))
                .then(|| dir.to_string_lossy().into_owned())
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    fn make_temp_project(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("mir_psr4_{name}"));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn parse_project_entries() {
        let root = make_temp_project("parse_project_entries");
        fs::write(
            root.join("composer.json"),
            r#"{
                "autoload": {
                    "psr-4": { "App\\": "src/", "App\\Models\\": "src/models/" }
                },
                "autoload-dev": {
                    "psr-4": { "Tests\\": "tests/" }
                }
            }"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();

        let prefixes: Vec<&str> = map
            .project_entries
            .iter()
            .map(|(p, _)| p.as_str())
            .collect();
        assert!(prefixes.contains(&"App\\Models\\"), "missing App\\Models\\");
        assert!(prefixes.contains(&"App\\"), "missing App\\");
        assert!(prefixes.contains(&"Tests\\"), "missing Tests\\");
    }

    #[test]
    fn longest_prefix_first() {
        let root = make_temp_project("longest_prefix_first");
        fs::write(
            root.join("composer.json"),
            r#"{
                "autoload": {
                    "psr-4": { "App\\": "src/", "App\\Models\\": "src/models/" }
                }
            }"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();

        assert_eq!(map.project_entries[0].0, "App\\Models\\");
    }

    #[test]
    fn missing_autoload_section_is_error() {
        let root = make_temp_project("missing_autoload");
        fs::write(root.join("composer.json"), r#"{ "name": "my/pkg" }"#).unwrap();

        let result = Psr4Map::from_composer(&root);
        assert!(
            matches!(result, Err(ComposerError::MissingAutoload)),
            "expected MissingAutoload error"
        );
    }

    #[test]
    fn composer_v2_installed() {
        let root = make_temp_project("composer_v2");
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let vendor_dir = root.join("vendor/composer");
        fs::create_dir_all(&vendor_dir).unwrap();
        fs::write(
            vendor_dir.join("installed.json"),
            r#"{
                "packages": [
                    {
                        "name": "vendor/pkg",
                        "autoload": { "psr-4": { "Vendor\\Pkg\\": "src/" } }
                    }
                ]
            }"#,
        )
        .unwrap();
        fs::create_dir_all(root.join("vendor/vendor/pkg/src")).unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let prefixes: Vec<&str> = map.vendor_entries.iter().map(|(p, _)| p.as_str()).collect();
        assert!(prefixes.contains(&"Vendor\\Pkg\\"), "missing Vendor\\Pkg\\");
    }

    #[test]
    fn composer_v1_installed() {
        let root = make_temp_project("composer_v1");
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let vendor_dir = root.join("vendor/composer");
        fs::create_dir_all(&vendor_dir).unwrap();
        fs::write(
            vendor_dir.join("installed.json"),
            r#"[
                {
                    "name": "vendor/pkg",
                    "autoload": { "psr-4": { "Vendor\\Pkg\\": "src/" } }
                }
            ]"#,
        )
        .unwrap();
        fs::create_dir_all(root.join("vendor/vendor/pkg/src")).unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let prefixes: Vec<&str> = map.vendor_entries.iter().map(|(p, _)| p.as_str()).collect();
        assert!(prefixes.contains(&"Vendor\\Pkg\\"), "missing Vendor\\Pkg\\");
    }

    #[test]
    fn missing_installed_json() {
        let root = make_temp_project("missing_installed");
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();
        let map = Psr4Map::from_composer(&root).unwrap();
        assert!(map.vendor_entries.is_empty());
    }

    #[test]
    fn project_files_returns_php_files() {
        let root = make_temp_project("project_files");
        let src = root.join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(src.join("Foo.php"), "<?php class Foo {}").unwrap();
        fs::write(src.join("README.md"), "not php").unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("Foo.php"));
    }

    // -----------------------------------------------------------------------
    // project_files() — require/include reaching outside every autoload root
    // (Sector C7)
    // -----------------------------------------------------------------------

    #[test]
    fn project_files_follows_dir_relative_require() {
        let root = make_temp_project("require_dir_relative");
        let src = root.join("src");
        let legacy = root.join("legacy");
        fs::create_dir_all(&src).unwrap();
        fs::create_dir_all(&legacy).unwrap();
        fs::write(
            src.join("Bootstrap.php"),
            "<?php require_once __DIR__ . '/../legacy/bootstrap.php'; class Bootstrap {}",
        )
        .unwrap();
        fs::write(
            legacy.join("bootstrap.php"),
            "<?php function legacy_init() {}",
        )
        .unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert_eq!(files.len(), 2, "expected Bootstrap.php + bootstrap.php");
        assert!(files.iter().any(|f| f.ends_with("bootstrap.php")));
    }

    #[test]
    fn project_files_follows_dirname_file_require() {
        let root = make_temp_project("require_dirname_file");
        let src = root.join("src");
        let legacy = root.join("legacy");
        fs::create_dir_all(&src).unwrap();
        fs::create_dir_all(&legacy).unwrap();
        fs::write(
            src.join("Bootstrap.php"),
            "<?php require_once dirname(__FILE__) . '/../legacy/bootstrap.php'; class Bootstrap {}",
        )
        .unwrap();
        fs::write(
            legacy.join("bootstrap.php"),
            "<?php function legacy_init() {}",
        )
        .unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert!(files.iter().any(|f| f.ends_with("bootstrap.php")));
    }

    #[test]
    fn project_files_follows_bare_literal_require_relative_to_including_file() {
        let root = make_temp_project("require_bare_literal");
        let src = root.join("src");
        let legacy = root.join("legacy");
        fs::create_dir_all(&src).unwrap();
        fs::create_dir_all(&legacy).unwrap();
        fs::write(
            src.join("Bootstrap.php"),
            "<?php require_once '../legacy/bootstrap.php'; class Bootstrap {}",
        )
        .unwrap();
        fs::write(
            legacy.join("bootstrap.php"),
            "<?php function legacy_init() {}",
        )
        .unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert!(files.iter().any(|f| f.ends_with("bootstrap.php")));
    }

    #[test]
    fn project_files_follows_require_transitively() {
        let root = make_temp_project("require_transitive");
        let src = root.join("src");
        let legacy = root.join("legacy");
        fs::create_dir_all(&src).unwrap();
        fs::create_dir_all(&legacy).unwrap();
        fs::write(
            src.join("Bootstrap.php"),
            "<?php require_once __DIR__ . '/../legacy/a.php';",
        )
        .unwrap();
        fs::write(
            legacy.join("a.php"),
            "<?php require_once __DIR__ . '/b.php';",
        )
        .unwrap();
        fs::write(legacy.join("b.php"), "<?php function b() {}").unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert!(files.iter().any(|f| f.ends_with("a.php")));
        assert!(files.iter().any(|f| f.ends_with("b.php")));
    }

    #[test]
    fn project_files_require_cycle_does_not_hang() {
        let root = make_temp_project("require_cycle");
        let src = root.join("src");
        let legacy = root.join("legacy");
        fs::create_dir_all(&src).unwrap();
        fs::create_dir_all(&legacy).unwrap();
        fs::write(
            src.join("Bootstrap.php"),
            "<?php require_once __DIR__ . '/../legacy/a.php';",
        )
        .unwrap();
        fs::write(
            legacy.join("a.php"),
            "<?php require_once __DIR__ . '/b.php';",
        )
        .unwrap();
        fs::write(
            legacy.join("b.php"),
            "<?php require_once __DIR__ . '/a.php';",
        )
        .unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert_eq!(
            files.len(),
            3,
            "each file discovered exactly once despite the cycle"
        );
    }

    #[test]
    fn project_files_missing_require_target_is_skipped() {
        let root = make_temp_project("require_missing_target");
        let src = root.join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("Bootstrap.php"),
            "<?php require_once __DIR__ . '/../legacy/does_not_exist.php';",
        )
        .unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert_eq!(files.len(), 1, "only Bootstrap.php itself");
    }

    #[test]
    fn project_files_dynamic_require_target_not_followed() {
        let root = make_temp_project("require_dynamic_target");
        let src = root.join("src");
        let legacy = root.join("legacy");
        fs::create_dir_all(&src).unwrap();
        fs::create_dir_all(&legacy).unwrap();
        fs::write(
            src.join("Bootstrap.php"),
            "<?php $path = getPath(); require_once $path;",
        )
        .unwrap();
        fs::write(
            legacy.join("bootstrap.php"),
            "<?php function legacy_init() {}",
        )
        .unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert_eq!(
            files.len(),
            1,
            "a non-statically-resolvable require target must not be followed"
        );
    }

    #[test]
    fn project_files_require_into_vendor_is_skipped() {
        let root = make_temp_project("require_into_vendor");
        let src = root.join("src");
        let vendor_pkg = root.join("vendor/some/pkg");
        fs::create_dir_all(&src).unwrap();
        fs::create_dir_all(&vendor_pkg).unwrap();
        fs::write(
            src.join("Bootstrap.php"),
            "<?php require_once __DIR__ . '/../vendor/some/pkg/lib.php';",
        )
        .unwrap();
        fs::write(vendor_pkg.join("lib.php"), "<?php function lib() {}").unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert_eq!(
            files.len(),
            1,
            "vendor-reaching require must not be indexed as a project file"
        );
    }

    #[test]
    fn resolve_existing_file() {
        let root = make_temp_project("resolve_existing");
        let models = root.join("src/models");
        fs::create_dir_all(&models).unwrap();
        fs::write(models.join("User.php"), "<?php class User {}").unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\Models\\":"src/models/","App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let result = map.resolve("App\\Models\\User");
        assert!(result.is_some(), "expected a resolved path");
        assert!(result.unwrap().ends_with("User.php"));
    }

    #[test]
    fn resolve_missing_file() {
        let root = make_temp_project("resolve_missing");
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let result = map.resolve("App\\Models\\User");
        assert!(result.is_none());
    }

    #[test]
    fn boundary_check() {
        let root = make_temp_project("boundary_check");
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        // "App\" must NOT match "Application\Foo"
        let result = map.resolve("Application\\Foo");
        assert!(
            result.is_none(),
            "App\\ prefix must not match Application\\Foo"
        );
    }

    #[test]
    fn array_valued_psr4_dirs() {
        let root = make_temp_project("array_dirs");
        let src = root.join("src");
        let lib = root.join("lib");
        fs::create_dir_all(&src).unwrap();
        fs::create_dir_all(&lib).unwrap();
        fs::write(src.join("Foo.php"), "<?php class Foo {}").unwrap();
        fs::write(lib.join("Bar.php"), "<?php class Bar {}").unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":["src/","lib/"]}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        // Both dirs should be in project_entries
        assert_eq!(
            map.project_entries.len(),
            2,
            "expected 2 entries for array-valued dir"
        );
        let files = map.project_files();
        assert_eq!(files.len(), 2, "expected Foo.php and Bar.php");
    }

    // -----------------------------------------------------------------------
    // classmap / files / psr-0 — vendor and project
    // -----------------------------------------------------------------------

    #[test]
    fn project_classmap_dir_is_collected() {
        let root = make_temp_project("project_classmap");
        let lib = root.join("lib");
        fs::create_dir_all(&lib).unwrap();
        fs::write(lib.join("Legacy.php"), "<?php class Legacy {}").unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"classmap":["lib/"]}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("Legacy.php"));
    }

    #[test]
    fn project_files_autoload_is_collected() {
        let root = make_temp_project("project_files_autoload");
        fs::write(root.join("helpers.php"), "<?php function my_helper() {}").unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"files":["helpers.php"]}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("helpers.php"));
    }

    #[test]
    fn project_psr0_dir_is_collected() {
        let root = make_temp_project("project_psr0");
        let lib = root.join("legacy");
        fs::create_dir_all(&lib).unwrap();
        fs::write(lib.join("Old.php"), "<?php class Old {}").unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-0":{"":"legacy/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.project_files();
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("Old.php"));
    }

    #[test]
    fn vendor_classmap_is_collected() {
        let root = make_temp_project("vendor_classmap");
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();
        let vendor_dir = root.join("vendor/composer");
        fs::create_dir_all(&vendor_dir).unwrap();
        fs::write(
            vendor_dir.join("installed.json"),
            r#"{
                "packages": [{
                    "name": "vendor/pkg",
                    "autoload": { "classmap": ["src/"] }
                }]
            }"#,
        )
        .unwrap();
        let pkg_src = root.join("vendor/vendor/pkg/src");
        fs::create_dir_all(&pkg_src).unwrap();
        fs::write(pkg_src.join("Legacy.php"), "<?php class Legacy {}").unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.vendor_files();
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("Legacy.php"));
    }

    #[test]
    fn vendor_files_autoload_is_collected() {
        let root = make_temp_project("vendor_files_autoload");
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();
        let vendor_dir = root.join("vendor/composer");
        fs::create_dir_all(&vendor_dir).unwrap();
        fs::write(
            vendor_dir.join("installed.json"),
            r#"{
                "packages": [{
                    "name": "vendor/pkg",
                    "autoload": { "files": ["bootstrap.php"] }
                }]
            }"#,
        )
        .unwrap();
        let pkg_dir = root.join("vendor/vendor/pkg");
        fs::create_dir_all(&pkg_dir).unwrap();
        fs::write(
            pkg_dir.join("bootstrap.php"),
            "<?php function pkg_bootstrap() {}",
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.vendor_files();
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("bootstrap.php"));
    }

    #[test]
    fn resolve_psr0_project_namespaced_class() {
        let root = make_temp_project("resolve_psr0_project_namespaced");
        let mailer_dir = root.join("src/Mailer");
        fs::create_dir_all(&mailer_dir).unwrap();
        fs::write(
            mailer_dir.join("Message.php"),
            "<?php namespace Mailer; class Message {}",
        )
        .unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-0":{"Mailer\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let result = map.resolve("Mailer\\Message");
        assert!(result.is_some(), "expected a resolved PSR-0 path");
        assert!(result.unwrap().ends_with("Mailer/Message.php"));
    }

    #[test]
    fn resolve_psr0_pear_style_class_with_underscores() {
        let root = make_temp_project("resolve_psr0_pear_style");
        let old_dir = root.join("src/Old");
        fs::create_dir_all(&old_dir).unwrap();
        fs::write(old_dir.join("Thing.php"), "<?php class Old_Thing {}").unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-0":{"Old_":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let result = map.resolve("Old_Thing");
        assert!(result.is_some(), "expected a resolved PSR-0 path");
        assert!(result.unwrap().ends_with("Old/Thing.php"));
    }

    #[test]
    fn resolve_psr0_vendor_class() {
        let root = make_temp_project("resolve_psr0_vendor");
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();
        let vendor_dir = root.join("vendor/composer");
        fs::create_dir_all(&vendor_dir).unwrap();
        fs::write(
            vendor_dir.join("installed.json"),
            r#"{
                "packages": [{
                    "name": "vendor/pkg",
                    "autoload": { "psr-0": { "Old_": "src/" } }
                }]
            }"#,
        )
        .unwrap();
        let pkg_src = root.join("vendor/vendor/pkg/src/Old");
        fs::create_dir_all(&pkg_src).unwrap();
        fs::write(pkg_src.join("Thing.php"), "<?php class Old_Thing {}").unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let result = map.resolve("Old_Thing");
        assert!(result.is_some(), "expected a resolved PSR-0 vendor path");
        assert!(result.unwrap().ends_with("Old/Thing.php"));
    }

    #[test]
    fn resolve_psr0_prefix_must_still_match() {
        let root = make_temp_project("resolve_psr0_prefix_mismatch");
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-0":{"Mailer\\":"src/"}}}"#,
        )
        .unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let result = map.resolve("Other\\Message");
        assert!(
            result.is_none(),
            "Mailer\\ psr-0 prefix must not match Other\\Message"
        );
    }

    #[test]
    fn vendor_psr0_is_collected() {
        let root = make_temp_project("vendor_psr0");
        fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
        )
        .unwrap();
        let vendor_dir = root.join("vendor/composer");
        fs::create_dir_all(&vendor_dir).unwrap();
        fs::write(
            vendor_dir.join("installed.json"),
            r#"{
                "packages": [{
                    "name": "vendor/pkg",
                    "autoload": { "psr-0": { "Old_": "src/" } }
                }]
            }"#,
        )
        .unwrap();
        let pkg_src = root.join("vendor/vendor/pkg/src/Old");
        fs::create_dir_all(&pkg_src).unwrap();
        fs::write(pkg_src.join("Thing.php"), "<?php class Old_Thing {}").unwrap();

        let map = Psr4Map::from_composer(&root).unwrap();
        let files = map.vendor_files();
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("Thing.php"));
    }
}