mir-analyzer 0.59.2

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
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
//! End-to-end verification of Phase 1 and Phase 2 API improvements.
//!
//! Phase 1 (analyzer's job):
//! - hover() returns real HoverInfo (no longer a stub)
//! - Name enum for type-safe identity
//! - Result types for lookups (NotFound vs NoSourceLocation)
//! - Hierarchical DocumentSymbol (classes contain method/property children)
//!
//! Phase 2 (boundary fixes):
//! - ProjectAnalyzer builder pattern
//! - with_cache_dir() avoids Arc wrapping
//! - ReferenceKind::Variable uses Arc<str>
//! - mir_codebase types re-exported

use std::sync::Arc;

use mir_analyzer::{AnalysisSession, Name, PhpVersion, SymbolLookupError};

#[test]
fn hover_returns_real_info_for_function() {
    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("test.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         /**\n\
          * Adds two integers and returns the sum.\n\
          */\n\
         function add(int $a, int $b): int { return $a + $b; }\n",
    );

    session.ingest_file(file.clone(), source.clone());

    let hover = session
        .hover(&Name::function("add"))
        .expect("add() should be resolvable");

    assert!(
        hover.docstring.is_some(),
        "Docstring should be populated from the docblock description"
    );
    assert!(
        hover
            .docstring
            .as_ref()
            .unwrap()
            .contains("Adds two integers"),
        "Docstring should include the description text, got: {:?}",
        hover.docstring
    );
    assert!(
        hover.definition.is_some(),
        "Function should have a source location"
    );
}

#[test]
fn hover_returns_not_found_for_unknown_symbol() {
    let session = AnalysisSession::new(PhpVersion::LATEST);
    let result = session.hover(&Name::function("nonexistent_function_xyz"));
    assert_eq!(result.unwrap_err(), SymbolLookupError::NotFound);
}

#[test]
fn symbol_method_normalizes_case() {
    // PHP methods are case-insensitive — the Name enum should normalize.
    let s1 = Name::method("Foo", "Bar");
    let s2 = Name::method("Foo", "bar");
    let s3 = Name::method("Foo", "BAR");

    assert_eq!(s1, s2);
    assert_eq!(s1, s3);
    assert_eq!(s1.codebase_key(), "meth:Foo::bar");
}

#[test]
fn definition_of_returns_result_with_distinct_errors() {
    let session = AnalysisSession::new(PhpVersion::LATEST);

    // Class never registered → NotFound
    let err = session
        .definition_of(&Name::class("CompletelyMadeUp"))
        .unwrap_err();
    assert_eq!(err, SymbolLookupError::NotFound);
}

#[test]
fn document_symbols_returns_hierarchical_tree() {
    use mir_analyzer::symbol::DeclarationKind;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("hierarchy.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         class Container {\n\
             public int $count = 0;\n\
             const VERSION = 1;\n\
             public function add(int $n): void {}\n\
             public function reset(): void {}\n\
         }\n",
    );

    session.ingest_file(file.clone(), source.clone());

    let symbols = session.document_symbols(file.as_ref());
    let container = symbols
        .iter()
        .find(|s| s.name.as_ref() == "Container")
        .expect("Container class should be in document symbols");

    assert_eq!(container.kind, DeclarationKind::Class);
    assert!(
        !container.children.is_empty(),
        "Class should have children (methods, properties, constants)"
    );

    // Should contain methods, property, constant
    let kinds: Vec<DeclarationKind> = container.children.iter().map(|c| c.kind).collect();
    assert!(
        kinds.contains(&DeclarationKind::Method),
        "Should have at least one method child, got: {kinds:?}"
    );
}

#[test]
fn references_to_takes_typed_symbol() {
    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("refs.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         function helper(): void {}\n\
         function caller(): void { helper(); helper(); }\n",
    );

    session.ingest_file(file.clone(), source.clone());

    // Now run pass 2 to record references
    use mir_analyzer::FileAnalyzer;
    let parsed = php_rs_parser::parse(&source);
    let _analysis = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    // New typed API: pass Name::function, not &str
    let refs = session
        .indexed_references_to(
            &Name::function("helper"),
            std::slice::from_ref(&file),
            false,
            &|| false,
        )
        .expect("not cancelled");
    assert!(
        refs.iter().any(|(f, _)| f.as_ref() == file.as_ref()),
        "Should find references to helper in {}",
        file
    );
}

#[test]
fn analysis_session_builder_pattern() {
    use mir_analyzer::{AnalysisSession, BatchOptions, PhpVersion};

    // Builder pattern is chainable.
    let _session = AnalysisSession::new(PhpVersion::LATEST);

    // Dead-code reporting is opted in by removing the dead-code names from
    // BatchOptions::suppressed_issue_kinds.
    let mut opts =
        BatchOptions::new().with_suppressed(mir_analyzer::dead_code_issue_kinds().iter().copied());
    for kind in mir_analyzer::dead_code_issue_kinds() {
        opts.suppressed_issue_kinds.remove(*kind);
    }
}

#[test]
fn analysis_session_with_cache_dir() {
    // New convenience constructor avoids Arc::new wrapping at call site
    let temp = std::env::temp_dir().join("mir_test_cache_xyz");
    let _session = AnalysisSession::new(PhpVersion::LATEST).with_cache_dir(&temp);
    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn symbol_kind_variable_uses_arc_str() {
    use mir_analyzer::symbol::ReferenceKind;

    let kind = ReferenceKind::Variable(Arc::from("count"));
    match kind {
        ReferenceKind::Variable(name) => {
            // Arc<str> can be compared via as_ref()
            assert_eq!(name.as_ref(), "count");
        }
        _ => panic!("expected Variable"),
    }
}

#[test]
fn re_exports_available_at_crate_root() {
    // Should not require depending on mir_codebase
    let _: mir_analyzer::Visibility = mir_analyzer::Visibility::Public;
    // DeclaredParam and TemplateParam should also be reachable as types
    let _name: &'static str = std::any::type_name::<mir_analyzer::DeclaredParam>();
    let _name: &'static str = std::any::type_name::<mir_analyzer::TemplateParam>();
}

#[test]
fn contains_function_class_method_typed_queries() {
    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ingest_file(
        Arc::from("typed.php"),
        Arc::from(
            "<?php\n\
             class Worker { public function run(): void {} }\n\
             function helper(): void {}\n",
        ),
    );

    // Class / function / method are checkable without poking at internals
    assert!(session.contains_class("Worker"));
    assert!(session.contains_function("helper"));
    assert!(session.contains_method("Worker", "run"));
    // PHP method case insensitivity
    assert!(session.contains_method("Worker", "RUN"));
    assert!(session.contains_method("Worker", "Run"));

    assert!(!session.contains_class("DoesNotExist"));
    assert!(!session.contains_function("does_not_exist_xyz"));
    assert!(!session.contains_method("Worker", "missing"));
}

#[test]
fn resolved_symbol_to_symbol_bridges_pass2_with_queries() {
    use mir_analyzer::symbol::ReferenceKind;
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("bridge.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         function helper(): void {}\n\
         function caller(): void { helper(); }\n",
    );

    session.ingest_file(file.clone(), source.clone());

    let parsed = php_rs_parser::parse(&source);
    let analysis = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    let helper_call = analysis
        .symbols
        .iter()
        .find(|s| matches!(&s.kind, ReferenceKind::FunctionCall(name) if name.as_ref() == "helper"))
        .expect("should record helper() call in caller body");

    let typed_symbol = helper_call
        .to_symbol()
        .expect("FunctionCall should convert to Name");

    assert_eq!(typed_symbol, Name::function("helper"));

    // The typed Name can be passed directly to references_to
    let refs = session
        .indexed_references_to(&typed_symbol, std::slice::from_ref(&file), false, &|| false)
        .expect("not cancelled");
    assert!(refs.iter().any(|(f, _)| f.as_ref() == file.as_ref()));
}

#[test]
fn method_references_scoped_by_declaring_class() {
    // Verify: findReferences on Foo::toString must NOT return Bar::toString or
    // its call sites — they are unrelated classes with no common ancestor.
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("scope.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         final class Foo { public function toString(): string { return 'foo'; } }\n\
         final class Bar { public function toString(): string { return 'bar'; } }\n\
         (new Foo())->toString();\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let _ = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    let foo_refs = session
        .indexed_references_to(
            &Name::method("Foo", "toString"),
            std::slice::from_ref(&file),
            false,
            &|| false,
        )
        .expect("not cancelled");
    let bar_refs = session
        .indexed_references_to(
            &Name::method("Bar", "toString"),
            std::slice::from_ref(&file),
            false,
            &|| false,
        )
        .expect("not cancelled");

    assert!(
        !foo_refs.is_empty(),
        "Foo::toString should have at least one reference (the call site); got none"
    );
    assert!(
        bar_refs.is_empty(),
        "Bar::toString should have zero references; got {bar_refs:?}"
    );

    let foo_lines: Vec<u32> = foo_refs.iter().map(|(_, r)| r.start.line).collect();
    assert!(
        foo_lines.contains(&4),
        "Expected reference on line 4 (1-based); got {foo_lines:?}"
    );
}

#[test]
fn method_references_end_to_end_symbol_at_flow() {
    // Verify the real findReferences flow: symbol_at → to_symbol() → references_to.
    // The Name built from the resolved symbol at the call position must round-trip
    // back to the same reference.
    use mir_analyzer::symbol::ReferenceKind;
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("e2e.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         final class Foo { public function toString(): string { return 'foo'; } }\n\
         (new Foo())->toString();\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let analysis = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    // "->toString" — skip the "->" (2 bytes) to land on the 't'.
    let call_offset = source.find("->toString").unwrap() as u32 + 2;

    let sym = analysis
        .symbol_at(call_offset)
        .expect("should resolve symbol at toString call site");

    assert!(
        matches!(&sym.kind, ReferenceKind::MethodCall { class, .. } if class.as_ref() == "Foo"),
        "symbol_at should report class Foo; got {:?}",
        sym.kind
    );

    let name = sym.to_symbol().expect("MethodCall should map to a Name");
    let refs = session
        .indexed_references_to(&name, std::slice::from_ref(&file), false, &|| false)
        .expect("not cancelled");

    assert!(
        !refs.is_empty(),
        "references_to via symbol_at flow must find the call site; got none"
    );
}

#[test]
fn global_constant_references_end_to_end_symbol_at_flow() {
    // Global constant usages must enter the reference/symbol pipeline, same as
    // functions/methods/properties/class constants.
    use mir_analyzer::symbol::ReferenceKind;
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("gcnst.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         const FOO = 1;\n\
         echo FOO;\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let analysis = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    let use_offset = source.rfind("FOO").unwrap() as u32;
    let sym = analysis
        .symbol_at(use_offset)
        .expect("should resolve symbol at FOO usage site");

    assert!(
        matches!(&sym.kind, ReferenceKind::GlobalConstant(fqn) if fqn.as_ref() == "FOO"),
        "symbol_at should report global constant FOO; got {:?}",
        sym.kind
    );

    let name = sym
        .to_symbol()
        .expect("GlobalConstant should map to a Name");
    let refs = session
        .indexed_references_to(&name, std::slice::from_ref(&file), false, &|| false)
        .expect("not cancelled");

    assert!(
        !refs.is_empty(),
        "references_to via symbol_at flow must find the `echo FOO;` usage; got none"
    );
}

#[test]
fn method_references_inherited_method_end_to_end() {
    // When Foo inherits toString from Base, record_ref stores the reference
    // under "Base::tostring" (the declaring class). Before this fix, record_symbol
    // stored class "Foo" (the receiver), making symbol_at → references_to return
    // nothing. After the fix both keys agree on the declaring class.
    use mir_analyzer::symbol::ReferenceKind;
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("inherit.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         class Base { public function toString(): string { return 'b'; } }\n\
         final class Foo extends Base {}\n\
         (new Foo())->toString();\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let analysis = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    // "->toString" — skip the "->" (2 bytes) to land on the 't'.
    let call_offset = source.find("->toString").unwrap() as u32 + 2;

    let sym = analysis
        .symbol_at(call_offset)
        .expect("should resolve symbol at toString call");

    let declaring_class = match &sym.kind {
        ReferenceKind::MethodCall { class, .. } => class.as_ref().to_string(),
        other => panic!("unexpected kind: {other:?}"),
    };

    assert_eq!(
        declaring_class, "Base",
        "symbol_at must report the DECLARING class (Base), not the receiver (Foo)"
    );

    let name = sym.to_symbol().expect("MethodCall maps to Name");
    let refs = session
        .indexed_references_to(&name, std::slice::from_ref(&file), false, &|| false)
        .expect("not cancelled");

    assert!(
        !refs.is_empty(),
        "references_to(Base::toString) must find the (new Foo())->toString() call; \
         got none (declaring_class was '{declaring_class}', refs: {refs:?})"
    );
}

#[test]
fn property_references_inherited_property_end_to_end() {
    // When Foo inherits $count from Base, record_ref and record_symbol must both
    // use the declaring class (Base), not the receiver (Foo), so that
    // references_to(Base::count) finds the access site.
    use mir_analyzer::symbol::ReferenceKind;
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("inherit_prop.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         class Base { public int $count = 0; }\n\
         final class Foo extends Base {}\n\
         (new Foo())->count;\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let analysis = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    let prop_offset = source.find("->count").unwrap() as u32 + 2;
    let sym = analysis
        .symbol_at(prop_offset)
        .expect("should resolve symbol at ->count");

    let declaring_class = match &sym.kind {
        ReferenceKind::PropertyAccess { class, .. } => class.as_ref().to_string(),
        other => panic!("unexpected kind: {other:?}"),
    };

    assert_eq!(
        declaring_class, "Base",
        "symbol_at must report the DECLARING class (Base), not the receiver (Foo)"
    );

    let name = sym.to_symbol().expect("PropertyAccess maps to Name");
    let refs = session
        .indexed_references_to(&name, std::slice::from_ref(&file), false, &|| false)
        .expect("not cancelled");

    assert!(
        !refs.is_empty(),
        "references_to(Base::count) must find the (new Foo())->count access; \
         got none (declaring_class was '{declaring_class}', refs: {refs:?})"
    );
}

#[test]
fn property_write_target_appears_in_references() {
    // A plain-assignment write ($this->prop = ...) must show up in find-all-references,
    // same as a read ($this->prop) does.
    use mir_analyzer::FileAnalyzer;
    use mir_analyzer::Name;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("prop_write.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         class Foo {\n\
         private string $v = '';\n\
         function set(string $x): void { $this->v = $x; }\n\
         function get(): string { return $this->v; }\n\
         }\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let _analysis = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    let refs = session
        .indexed_references_to(
            &Name::property("Foo", "v"),
            std::slice::from_ref(&file),
            false,
            &|| false,
        )
        .expect("not cancelled");
    let lines: Vec<u32> = refs.iter().map(|(_, r)| r.start.line).collect();

    assert!(
        lines.contains(&4),
        "expected the write site ($this->v = $x;, line 4) in references_to(Foo::v); got {lines:?}"
    );
    assert!(
        lines.contains(&5),
        "expected the read site (return $this->v;, line 5) in references_to(Foo::v); got {lines:?}"
    );
}

#[test]
fn static_property_write_target_appears_in_references() {
    // Foo::$prop = ..., self::$prop = ..., and static::$prop = ... writes must show up
    // in find-all-references, same as a static property read does.
    use mir_analyzer::FileAnalyzer;
    use mir_analyzer::Name;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("static_prop_write.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         class Counter {\n\
         private static int $n = 0;\n\
         static function bump(): void { self::$n++; }\n\
         static function reset(): void { self::$n = 0; }\n\
         static function get(): int { return Counter::$n; }\n\
         }\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let _analysis = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    let refs = session
        .indexed_references_to(
            &Name::property("Counter", "n"),
            std::slice::from_ref(&file),
            false,
            &|| false,
        )
        .expect("not cancelled");
    let lines: Vec<u32> = refs.iter().map(|(_, r)| r.start.line).collect();

    assert!(
        lines.contains(&5),
        "expected the self::$n = 0; write (line 5) in references_to(Counter::n); got {lines:?}"
    );
    assert!(
        lines.contains(&6),
        "expected the Counter::$n read (line 6) in references_to(Counter::n); got {lines:?}"
    );
}

#[test]
fn property_references_direct_property_end_to_end() {
    // Non-inherited property: references_to(Foo::value) finds the access site.
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("direct_prop.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         class Foo { public string $value = ''; }\n\
         (new Foo())->value;\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let _ = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    let refs = session
        .indexed_references_to(
            &Name::property("Foo", "value"),
            std::slice::from_ref(&file),
            false,
            &|| false,
        )
        .expect("not cancelled");
    assert!(
        !refs.is_empty(),
        "references_to(Foo::value) must find the ->value access; got none"
    );
}

#[test]
fn load_class_with_custom_resolver() {
    use mir_analyzer::{ClassResolver, LoadOutcome};
    use std::path::PathBuf;

    // Custom resolver that maps any FQCN to a temp file we write.
    struct TmpResolver {
        path: PathBuf,
    }
    impl ClassResolver for TmpResolver {
        fn resolve(&self, _fqcn: &str) -> Option<PathBuf> {
            Some(self.path.clone())
        }
    }

    let dir = std::env::temp_dir().join(format!("mir_lazy_test_{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let file_path = dir.join("Resolved.php");
    std::fs::write(&file_path, "<?php\nclass ResolvedByCustom {}\n").unwrap();

    let resolver: Arc<dyn ClassResolver> = Arc::new(TmpResolver {
        path: file_path.clone(),
    });

    let session = AnalysisSession::new(PhpVersion::LATEST).with_class_resolver(resolver);

    // Class is not yet known
    assert!(!session.contains_class("ResolvedByCustom"));

    // First call: should load via resolver
    let outcome = session.load_class("ResolvedByCustom");
    assert_eq!(outcome, LoadOutcome::Loaded);
    assert!(session.contains_class("ResolvedByCustom"));

    // Second call: already loaded
    let outcome = session.load_class("ResolvedByCustom");
    assert_eq!(outcome, LoadOutcome::AlreadyLoaded);

    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn prefetch_imports_loads_unresolved_use_statements() {
    use mir_analyzer::ClassResolver;
    use std::path::PathBuf;
    use std::sync::Mutex;

    // Resolver that maps known FQCNs to files we wrote to disk, and tracks
    // every call so we can assert on prefetch behavior.
    struct TrackedResolver {
        map: std::collections::HashMap<String, PathBuf>,
        calls: Mutex<Vec<String>>,
    }
    impl ClassResolver for TrackedResolver {
        fn resolve(&self, fqcn: &str) -> Option<PathBuf> {
            self.calls.lock().unwrap().push(fqcn.to_string());
            self.map.get(fqcn).cloned()
        }
    }

    let dir = std::env::temp_dir().join(format!("mir_prefetch_test_{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let dep_path = dir.join("Dep.php");
    std::fs::write(&dep_path, "<?php\nnamespace App;\nclass Dep {}\n").unwrap();

    let mut map = std::collections::HashMap::new();
    map.insert("App\\Dep".to_string(), dep_path.clone());

    let resolver = Arc::new(TrackedResolver {
        map,
        calls: Mutex::new(Vec::new()),
    });
    let session = AnalysisSession::new(PhpVersion::LATEST).with_class_resolver(resolver.clone());

    // User opens a file that imports App\Dep but doesn't have Dep in the
    // session yet.
    let opened: Arc<str> = Arc::from("opened.php");
    let opened_src: Arc<str> =
        Arc::from("<?php\nuse App\\Dep;\nclass Caller { public function go(Dep $d): void {} }\n");
    session.ingest_file(opened.clone(), opened_src);

    // Before prefetch: Dep is not in the codebase.
    assert!(!session.contains_class("App\\Dep"));

    // pending_lazy_loads should surface the unresolved import.
    let pending = session.pending_lazy_loads(opened.as_ref());
    assert!(
        pending.iter().any(|s| s.as_ref() == "App\\Dep"),
        "pending should include App\\Dep, got {:?}",
        pending
    );

    // Prefetch loads it.
    let loaded = session.prefetch_imports(opened.as_ref());
    assert!(loaded >= 1, "prefetch should load at least App\\Dep");
    assert!(session.contains_class("App\\Dep"));

    // A second prefetch is a no-op (no pending imports remain).
    assert_eq!(session.pending_lazy_loads(opened.as_ref()).len(), 0);

    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn reanalyze_dependents_runs_in_parallel() {
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    // base.php defines Base. dep_a.php and dep_b.php extend Base.
    let base: Arc<str> = Arc::from("base.php");
    let dep_a: Arc<str> = Arc::from("dep_a.php");
    let dep_b: Arc<str> = Arc::from("dep_b.php");

    session.ingest_file(base.clone(), Arc::from("<?php\nclass Base {}\n"));
    session.ingest_file(dep_a.clone(), Arc::from("<?php\nclass A extends Base {}\n"));
    session.ingest_file(dep_b.clone(), Arc::from("<?php\nclass B extends Base {}\n"));

    // Run Pass 2 on the dependents once so they're recorded as having
    // analyzed against Base.
    for (file, src) in [
        (&dep_a, "<?php\nclass A extends Base {}\n"),
        (&dep_b, "<?php\nclass B extends Base {}\n"),
    ] {
        let parsed = php_rs_parser::parse(src);
        FileAnalyzer::new(&session).analyze(file.clone(), src, &parsed.program, &parsed.source_map);
    }

    // source_of returns the registered source.
    assert!(session.source_of(dep_a.as_ref()).is_some());
    assert_eq!(session.source_of("does-not-exist.php"), None);

    // reanalyze_dependents returns analyses for dependents of base.php.
    // (May be empty if dependency graph wasn't populated — that's still a
    // valid result; the API just shouldn't panic.)
    let analyses = session.reanalyze_dependents(base.as_ref());
    // Sanity: returned files are a subset of the ingested ones.
    for (file, _) in &analyses {
        assert!(file.as_ref() == dep_a.as_ref() || file.as_ref() == dep_b.as_ref());
    }
}

#[test]
fn reanalyze_files_recomputes_the_given_set_only() {
    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let base: Arc<str> = Arc::from("rf_base.php");
    let dependent: Arc<str> = Arc::from("rf_dep.php");
    let unrelated: Arc<str> = Arc::from("rf_other.php");

    session.ingest_file(base.clone(), Arc::from("<?php\nclass RfBase {}\n"));
    session.ingest_file(
        dependent.clone(),
        Arc::from("<?php\nclass RfDep extends RfBase {}\n"),
    );
    session.ingest_file(
        unrelated.clone(),
        Arc::from("<?php\nfunction rf_free(): void {}\n"),
    );

    // Edit the base: RfBase disappears. Re-analyzing the caller-supplied
    // "open" set must surface the dependent's broken extends without any
    // dependency-graph computation, and must not touch files outside the set.
    session.ingest_file(base.clone(), Arc::from("<?php\nclass RfRenamed {}\n"));

    let open_set = [dependent.clone(), unrelated.clone()];
    let analyses =
        session.reanalyze_files_cancellable(&open_set, &mir_analyzer::IndexCancel::new());

    let files: Vec<&str> = analyses.iter().map(|(f, _)| f.as_ref()).collect();
    assert_eq!(files, vec![dependent.as_ref(), unrelated.as_ref()]);

    let dep_analysis = &analyses[0].1;
    assert!(
        dep_analysis
            .issues
            .iter()
            .any(|i| i.location.file.as_ref() == dependent.as_ref()
                && format!("{:?}", i.kind).contains("RfBase")),
        "dependent must report the missing RfBase after the base edit; got {:?}",
        dep_analysis.issues
    );
    assert!(
        analyses[1].1.issues.is_empty(),
        "unrelated file must stay clean"
    );

    // Files the session doesn't know are skipped, not errored.
    let ghost: [Arc<str>; 1] = [Arc::from("rf_ghost.php")];
    assert!(session
        .reanalyze_files_cancellable(&ghost, &mir_analyzer::IndexCancel::new())
        .is_empty());

    // A pre-cancelled token short-circuits.
    let cancelled = mir_analyzer::IndexCancel::new();
    cancelled.cancel();
    assert!(session
        .reanalyze_files_cancellable(&open_set, &cancelled)
        .is_empty());
}

#[test]
fn load_class_not_resolvable_without_resolver() {
    use mir_analyzer::LoadOutcome;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    let outcome = session.load_class("Some\\Unknown\\Class");
    assert_eq!(outcome, LoadOutcome::NotResolvable);
}

#[test]
fn all_classes_and_all_functions_workspace_iteration() {
    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ingest_file(
        Arc::from("ws.php"),
        Arc::from(
            "<?php\n\
             class Alpha {}\n\
             class Beta {}\n\
             function gamma(): void {}\n",
        ),
    );

    let classes = session.all_classes();
    let class_names: Vec<&str> = classes.iter().map(|(f, _)| f.as_ref()).collect();
    assert!(class_names.contains(&"Alpha"));
    assert!(class_names.contains(&"Beta"));

    let functions = session.all_functions();
    let fn_names: Vec<&str> = functions.iter().map(|(f, _)| f.as_ref()).collect();
    assert!(fn_names.contains(&"gamma"));
}

// Regression: bare FQN references without a `use` statement must be tracked in
// the dependency graph so that `reanalyze_dependents` re-analyzes the referencing
// file when the definition changes.  Currently not implemented — these tests document
// the missing behaviour and should be un-ignored once the bug is fixed.

#[test]
fn reanalyze_dependents_tracks_bare_fqn_new() {
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let service: Arc<str> = Arc::from("service.php");
    let consumer: Arc<str> = Arc::from("consumer.php");

    session.ingest_file(
        service.clone(),
        Arc::from("<?php\nclass Service { public function run(): void {} }\n"),
    );
    session.ingest_file(
        consumer.clone(),
        Arc::from("<?php\nfunction consume(): void { $s = new \\Service(); $s->run(); }\n"),
    );

    let consumer_src = "<?php\nfunction consume(): void { $s = new \\Service(); $s->run(); }\n";
    let parsed = php_rs_parser::parse(consumer_src);
    FileAnalyzer::new(&session).analyze(
        consumer.clone(),
        consumer_src,
        &parsed.program,
        &parsed.source_map,
    );

    let analyses = session.reanalyze_dependents(service.as_ref());
    let dependent_files: Vec<&str> = analyses.iter().map(|(f, _)| f.as_ref()).collect();
    assert!(
        dependent_files.contains(&consumer.as_ref()),
        "consumer.php references Service via bare FQN but was not returned by \
         reanalyze_dependents — dependency graph is missing FQN reference edges"
    );
}

#[test]
fn reanalyze_dependents_tracks_bare_fqn_static_call() {
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let helper: Arc<str> = Arc::from("helper.php");
    let caller: Arc<str> = Arc::from("caller.php");

    session.ingest_file(
        helper.clone(),
        Arc::from("<?php\nclass Helper { public static function go(): void {} }\n"),
    );
    session.ingest_file(
        caller.clone(),
        Arc::from("<?php\nfunction call_it(): void { \\Helper::go(); }\n"),
    );

    let caller_src = "<?php\nfunction call_it(): void { \\Helper::go(); }\n";
    let parsed = php_rs_parser::parse(caller_src);
    FileAnalyzer::new(&session).analyze(
        caller.clone(),
        caller_src,
        &parsed.program,
        &parsed.source_map,
    );

    let analyses = session.reanalyze_dependents(helper.as_ref());
    let dependent_files: Vec<&str> = analyses.iter().map(|(f, _)| f.as_ref()).collect();
    assert!(
        dependent_files.contains(&caller.as_ref()),
        "caller.php references Helper via bare FQN static call but was not returned by \
         reanalyze_dependents — dependency graph is missing FQN reference edges"
    );
}

#[test]
fn dependency_graph_includes_unused_param_type_hint() {
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let service: Arc<str> = Arc::from("service.php");
    let consumer: Arc<str> = Arc::from("consumer.php");

    // Define Service in service.php (namespace Vendor)
    session.ingest_file(
        service.clone(),
        Arc::from("<?php\nnamespace Vendor\nclass Service { }\n"),
    );

    // Use Service in param type hint WITHOUT use statement and WITHOUT using the param
    session.ingest_file(
        consumer.clone(),
        Arc::from("<?php\nnamespace Vendor\nfunction consume(Service $s) { }\n"),
    );

    // Analyze the consumer file to trigger Pass 2
    let consumer_src = "<?php\nnamespace Vendor\nfunction consume(Service $s) { }\n";
    let parsed = php_rs_parser::parse(consumer_src);
    FileAnalyzer::new(&session).analyze(
        consumer.clone(),
        consumer_src,
        &parsed.program,
        &parsed.source_map,
    );

    // Check if consumer is considered a dependent of service
    let dependents = session
        .dependency_graph()
        .transitive_dependents(service.as_ref());
    assert!(
        dependents.contains(&consumer.to_string()),
        "consumer.php should depend on service.php due to type hint in parameter, \
         even though the parameter is unused and there's no use statement"
    );
}

/// `file_structural_deps` is the salsa-tracked query that specifically walks
/// declarations (not body-level references, which are merged in separately by
/// `dependency_graph()` from the reference index). Testing it directly avoids
/// the reference-index path masking these gaps the way an end-to-end
/// `dependency_graph()` test would for widely-referenced constructs like
/// `implements`.
#[test]
fn file_structural_deps_includes_enum_method_param_type_hint() {
    use mir_analyzer::db::{file_structural_deps, MirDatabase};

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.set_file_text(
        Arc::from("/proj/Service.php"),
        Arc::from("<?php\nnamespace Vendor;\nclass Service {}\n"),
    );
    let consumer_src = "<?php\nnamespace Vendor;\nenum Suit {\n    case Hearts;\n    public function make(Service $s): void {}\n}\n";
    session.set_file_text(Arc::from("/proj/Consumer.php"), Arc::from(consumer_src));

    let db = session.snapshot_db();
    let sf = MirDatabase::lookup_source_file(&db, "/proj/Consumer.php")
        .expect("Consumer.php must be registered");
    let deps = file_structural_deps(&db, sf);
    assert!(
        deps.iter().any(|f| f.as_ref() == "/proj/Service.php"),
        "enum method param type hint must produce a structural dep on Service.php; \
         file_structural_deps never iterated defs.slice.enums. Got: {deps:?}"
    );
}

#[test]
fn file_structural_deps_includes_trait_property_and_method_type_hints() {
    use mir_analyzer::db::{file_structural_deps, MirDatabase};

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.set_file_text(
        Arc::from("/proj/Service.php"),
        Arc::from("<?php\nnamespace Vendor;\nclass Service {}\n"),
    );
    let consumer_src =
        "<?php\nnamespace Vendor;\ntrait HasService {\n    public Service $service;\n}\n";
    session.set_file_text(Arc::from("/proj/Consumer.php"), Arc::from(consumer_src));

    let db = session.snapshot_db();
    let sf = MirDatabase::lookup_source_file(&db, "/proj/Consumer.php")
        .expect("Consumer.php must be registered");
    let deps = file_structural_deps(&db, sf);
    assert!(
        deps.iter().any(|f| f.as_ref() == "/proj/Service.php"),
        "trait own-property type hint must produce a structural dep on Service.php; \
         file_structural_deps's trait branch only walked t.traits, never \
         t.own_properties/t.own_methods. Got: {deps:?}"
    );
}

// ──────────────────────────────────────────────────────────────────────────────
// Mutation tests: reanalyze_dependents after definition is removed / renamed.
//
// The correctness gap: when class Foo is deleted from A.php, files referencing
// \Foo were dropped from the dependent set because symbol_defining_file("Foo")
// returned None. The fix maintains a stale_defined_symbols map + a
// symbol_referencers reverse index so the edges survive the deletion.
// ──────────────────────────────────────────────────────────────────────────────

/// Helper: run Pass 2 on `src` under `file` path in `session`.
fn analyze_file(session: &AnalysisSession, file: Arc<str>, src: &str) {
    use mir_analyzer::FileAnalyzer;
    let parsed = php_rs_parser::parse(src);
    FileAnalyzer::new(session).analyze(file, src, &parsed.program, &parsed.source_map);
}

/// Return the set of file paths returned by reanalyze_dependents.
fn dependent_files(session: &AnalysisSession, file: &str) -> std::collections::HashSet<String> {
    session
        .reanalyze_dependents(file)
        .into_iter()
        .map(|(f, _)| f.to_string())
        .collect()
}

#[test]
fn reanalyze_dependents_after_definition_deleted() {
    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let foo: Arc<str> = Arc::from("Foo.php");
    let bar: Arc<str> = Arc::from("Bar.php");

    // Establish: Foo.php defines class Foo, Bar.php references it.
    session.ingest_file(foo.clone(), Arc::from("<?php\nclass Foo {}\n"));
    session.ingest_file(
        bar.clone(),
        Arc::from("<?php\nfunction f(\\Foo $x): void {}\n"),
    );
    let bar_src = "<?php\nfunction f(\\Foo $x): void {}\n";
    analyze_file(&session, bar.clone(), bar_src);

    // Precondition: Bar.php is a dependent before the mutation.
    let before = dependent_files(&session, foo.as_ref());
    assert!(
        before.contains(bar.as_ref()),
        "precondition: Bar.php must be a dependent before deletion; got {:?}",
        before
    );

    // Mutate: remove class Foo from Foo.php.
    session.ingest_file(foo.clone(), Arc::from("<?php\n// class Foo removed\n"));

    // Assert: Bar.php still appears — it has a broken reference that needs re-analysis.
    let after = dependent_files(&session, foo.as_ref());
    assert!(
        after.contains(bar.as_ref()),
        "Bar.php references \\Foo which was deleted from Foo.php — \
         it must still appear in reanalyze_dependents so the broken reference is surfaced; \
         got {:?}",
        after
    );
}

#[test]
fn reanalyze_dependents_after_definition_renamed() {
    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let foo: Arc<str> = Arc::from("Foo.php");
    let bar: Arc<str> = Arc::from("Bar.php");

    session.ingest_file(foo.clone(), Arc::from("<?php\nclass Foo {}\n"));
    session.ingest_file(
        bar.clone(),
        Arc::from("<?php\nfunction f(\\Foo $x): void {}\n"),
    );
    analyze_file(
        &session,
        bar.clone(),
        "<?php\nfunction f(\\Foo $x): void {}\n",
    );

    // Rename: class Foo → class Renamed in the same file.
    session.ingest_file(foo.clone(), Arc::from("<?php\nclass Renamed {}\n"));

    let after = dependent_files(&session, foo.as_ref());
    assert!(
        after.contains(bar.as_ref()),
        "Bar.php references \\Foo which was renamed to \\Renamed in Foo.php — \
         Bar.php must still appear in reanalyze_dependents; got {:?}",
        after
    );
}

#[test]
fn reanalyze_dependents_after_definition_moved() {
    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let a: Arc<str> = Arc::from("A.php");
    let b: Arc<str> = Arc::from("B.php");
    let consumer: Arc<str> = Arc::from("Consumer.php");

    // class Foo initially in A.php.
    session.ingest_file(a.clone(), Arc::from("<?php\nclass Foo {}\n"));
    session.ingest_file(b.clone(), Arc::from("<?php\n// empty\n"));
    session.ingest_file(
        consumer.clone(),
        Arc::from("<?php\nfunction f(\\Foo $x): void {}\n"),
    );
    analyze_file(
        &session,
        consumer.clone(),
        "<?php\nfunction f(\\Foo $x): void {}\n",
    );

    // Move: remove Foo from A.php, add it to B.php.
    session.ingest_file(a.clone(), Arc::from("<?php\n// Foo moved to B.php\n"));
    session.ingest_file(b.clone(), Arc::from("<?php\nclass Foo {}\n"));

    // Consumer.php references \Foo — it must appear as a dependent of A.php
    // (broken reference) AND of B.php (resolved reference).
    let a_deps = dependent_files(&session, a.as_ref());
    assert!(
        a_deps.contains(consumer.as_ref()),
        "Consumer.php must appear as dependent of A.php after Foo is moved out; got {:?}",
        a_deps
    );
    let b_deps = dependent_files(&session, b.as_ref());
    assert!(
        b_deps.contains(consumer.as_ref()),
        "Consumer.php must appear as dependent of B.php after Foo is moved in; got {:?}",
        b_deps
    );
}

#[test]
fn reanalyze_dependents_after_definition_readded() {
    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let foo: Arc<str> = Arc::from("Foo.php");
    let bar: Arc<str> = Arc::from("Bar.php");

    session.ingest_file(foo.clone(), Arc::from("<?php\nclass Foo {}\n"));
    session.ingest_file(
        bar.clone(),
        Arc::from("<?php\nfunction f(\\Foo $x): void {}\n"),
    );
    analyze_file(
        &session,
        bar.clone(),
        "<?php\nfunction f(\\Foo $x): void {}\n",
    );

    // Delete Foo.
    session.ingest_file(foo.clone(), Arc::from("<?php\n// deleted\n"));

    // Re-add Foo. The stale entry should be cleared and the normal dep graph
    // edge restored — Bar.php is still a dependent via the current edge.
    session.ingest_file(foo.clone(), Arc::from("<?php\nclass Foo {}\n"));

    let after = dependent_files(&session, foo.as_ref());
    assert!(
        after.contains(bar.as_ref()),
        "Bar.php must be a dependent of Foo.php after Foo is re-added; got {:?}",
        after
    );
}

#[test]
fn reanalyze_dependents_transitive_after_delete() {
    // A.php defines Foo. B.php references Foo (direct dependent).
    // C.php structurally depends on B.php (e.g. extends a class from B.php).
    // After Foo is deleted from A.php:
    //   - B.php must appear (direct stale dependent)
    //   - C.php must appear (transitive via structural dep on B)
    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let a: Arc<str> = Arc::from("A.php");
    let b: Arc<str> = Arc::from("B.php");
    let c: Arc<str> = Arc::from("C.php");

    session.ingest_file(a.clone(), Arc::from("<?php\nclass Foo {}\n"));
    session.ingest_file(
        b.clone(),
        Arc::from("<?php\nclass Bar { public function f(\\Foo $x): void {} }\n"),
    );
    session.ingest_file(c.clone(), Arc::from("<?php\nclass Baz extends \\Bar {}\n"));

    // Pass 2 on both B and C so their reference edges land in file_referenced_symbols.
    analyze_file(
        &session,
        b.clone(),
        "<?php\nclass Bar { public function f(\\Foo $x): void {} }\n",
    );
    analyze_file(&session, c.clone(), "<?php\nclass Baz extends \\Bar {}\n");

    // Delete Foo from A.php.
    session.ingest_file(a.clone(), Arc::from("<?php\n// Foo deleted\n"));

    let after = dependent_files(&session, a.as_ref());
    assert!(
        after.contains(b.as_ref()),
        "B.php (direct referencer of deleted Foo) must appear; got {:?}",
        after
    );
    assert!(
        after.contains(c.as_ref()),
        "C.php (transitively depends on B.php) must appear; got {:?}",
        after
    );
}

// ──────────────────────────────────────────────────────────────────────────────
// Regression: reanalyze_dependents must not deadlock when many dependents each
// trigger a lazy class-load during warm-up.
//
// `reanalyze_dependents` warms up each dependent via `prepare_ast_for_analysis`,
// which resolves the dependent's direct class references and loads any that
// aren't indexed yet. Loading mutates the shared session salsa storage
// (`load_class` → `ingest_file` takes the salsa write lock and sets inputs).
//
// v0.37.0 moved that warm-up *inside* the parallel rayon worker. With many
// dependents each referencing a not-yet-loaded class, multiple workers entered
// `ingest_file` concurrently while sibling workers held live snapshot clones
// mid-`analyze_file` — quiescing the salsa runtime and deadlocking. On a
// high-fan-out workspace (the symfony LSP feature tests) the call hung
// indefinitely. The fix hoists the input-mutating warm-up out of the parallel
// loop. This test reproduces the condition and asserts the call completes.
// ──────────────────────────────────────────────────────────────────────────────

/// In-memory `ClassResolver`: maps an FQCN to a virtual path. Leading
/// backslash on fully-qualified names is normalized away.
struct MapResolver(std::collections::HashMap<String, std::path::PathBuf>);
impl mir_analyzer::ClassResolver for MapResolver {
    fn resolve(&self, fqcn: &str) -> Option<std::path::PathBuf> {
        self.0.get(fqcn.trim_start_matches('\\')).cloned()
    }
}

/// In-memory `SourceProvider`: serves virtual-path source text.
struct MapProvider(std::collections::HashMap<String, Arc<str>>);
impl mir_analyzer::SourceProvider for MapProvider {
    fn read(&self, path: &str) -> Option<Arc<str>> {
        self.0.get(path).cloned()
    }
}

#[test]
fn reanalyze_dependents_lazy_load_warmup_does_not_deadlock() {
    use std::collections::HashMap;
    use std::path::PathBuf;
    use std::sync::mpsc;
    use std::time::Duration;

    // Enough dependents to guarantee concurrent rayon workers contend on the
    // shared salsa write lock during warm-up.
    const N: usize = 64;

    // Build resolver + provider for the lazily-loaded classes (Lazy0..LazyN).
    // These are NOT ingested up front — the warm-up inside reanalyze_dependents
    // is what faults them in, which is exactly what mutates shared salsa state.
    let mut resolver_map: HashMap<String, PathBuf> = HashMap::new();
    let mut provider_map: HashMap<String, Arc<str>> = HashMap::new();
    for i in 0..N {
        let path = format!("lazy_{i}.php");
        resolver_map.insert(format!("Lazy{i}"), PathBuf::from(&path));
        provider_map.insert(
            path,
            Arc::from(format!("<?php\nclass Lazy{i} {{}}\n").as_str()),
        );
    }

    let session = AnalysisSession::new(PhpVersion::LATEST)
        .with_class_resolver(Arc::new(MapResolver(resolver_map)))
        .with_source_provider(Arc::new(MapProvider(provider_map)));
    session.ensure_all_stubs();

    // Base class every dependent extends — gives each dep a structural edge to
    // base.php (recorded at ingest time), so all deps are transitive dependents.
    session.ingest_file(Arc::from("base.php"), Arc::from("<?php\nclass Base {}\n"));

    // Each dependent `extends \Base` (the dependency edge) and constructs a
    // distinct `\Lazy{i}` in a method body. The Lazy reference is collected by
    // the warm-up and triggers a lazy ingest, since it isn't loaded yet. Only
    // ingest_file is called here (no FileAnalyzer), so Lazy{i} stays unloaded
    // until reanalyze_dependents runs.
    for i in 0..N {
        let path: Arc<str> = Arc::from(format!("dep_{i}.php").as_str());
        let src = format!(
            "<?php\nclass Dep{i} extends \\Base {{ public function go(): void {{ $x = new \\Lazy{i}(); }} }}\n"
        );
        session.ingest_file(path, Arc::from(src.as_str()));
    }

    // Run on a worker thread guarded by a timeout: a regression deadlocks here
    // rather than returning, so recv_timeout is what turns the hang into a
    // failed assertion instead of a hung test binary.
    let session = Arc::new(session);
    let (tx, rx) = mpsc::channel();
    let worker_session = Arc::clone(&session);
    let handle = std::thread::spawn(move || {
        let result = worker_session.reanalyze_dependents("base.php");
        let _ = tx.send(result.len());
    });

    match rx.recv_timeout(Duration::from_secs(60)) {
        Ok(count) => {
            handle.join().expect("worker thread panicked");
            assert_eq!(
                count, N,
                "every Dep{{i}} extends \\Base, so all {N} should be returned as dependents"
            );
        }
        Err(mpsc::RecvTimeoutError::Timeout) => {
            panic!(
                "reanalyze_dependents did not complete within 60s — likely the \
                 in-parallel-worker lazy-load deadlock regressed (v0.37.0 bug)"
            );
        }
        Err(e) => panic!("worker channel error: {e:?}"),
    }
}

#[test]
fn catch_clause_records_class_reference_symbol() {
    // A caught exception type is a class reference just like `new Foo()` or
    // `instanceof Foo` — hover/go-to-definition on it relies on a
    // ResolvedSymbol being recorded, which the catch-clause path previously
    // skipped (it only ever recorded the dead-code `cls:` reference).
    use mir_analyzer::symbol::ReferenceKind;
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("catch.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         final class MyException extends \\Exception {}\n\
         function run(): void {\n\
             try {\n\
                 throw new MyException();\n\
             } catch (MyException $e) {\n\
             }\n\
         }\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let analysis = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    let catch_symbol = analysis.symbols.iter().find(|s| {
        matches!(&s.kind, ReferenceKind::ClassReference(name) if name.as_ref() == "MyException")
            && s.span.start > source.find("catch (").unwrap() as u32
    });
    assert!(
        catch_symbol.is_some(),
        "catch (MyException $e) should record a ClassReference symbol for MyException"
    );
}

#[test]
fn static_property_access_records_symbols() {
    // `Foo::$bar` recorded the dead-code prop:/cls: references but never a
    // ResolvedSymbol, so hover/go-to-definition silently did nothing on a
    // static property access (unlike instance `$obj->prop`, which does).
    use mir_analyzer::symbol::ReferenceKind;
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("static_prop.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         class Counter {\n\
             public static $count = 0;\n\
         }\n\
         function bump(): void {\n\
             Counter::$count = Counter::$count + 1;\n\
         }\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let analysis = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    assert!(
        analysis.symbols.iter().any(|s| matches!(
            &s.kind,
            ReferenceKind::ClassReference(name) if name.as_ref() == "Counter"
        )),
        "Counter::$count should record a ClassReference symbol for Counter"
    );
    assert!(
        analysis.symbols.iter().any(|s| matches!(
            &s.kind,
            ReferenceKind::PropertyAccess { class, property }
                if class.as_ref() == "Counter" && property.as_ref() == "count"
        )),
        "Counter::$count should record a PropertyAccess symbol for Counter::$count"
    );
}

#[test]
fn references_to_finds_extends_implements_and_trait_use() {
    // `extends`, `implements`, and trait `use` name a class/interface/trait
    // just as much as `new Foo()` does — references_to() must find those
    // sites too, not just constructor/static-call/type-hint usages.
    use mir_analyzer::FileAnalyzer;

    let session = AnalysisSession::new(PhpVersion::LATEST);
    session.ensure_all_stubs();

    let file: Arc<str> = Arc::from("hierarchy.php");
    let source: Arc<str> = Arc::from(
        "<?php\n\
         class Base {}\n\
         interface Greets {}\n\
         trait Helper {}\n\
         class Child extends Base implements Greets {\n\
             use Helper;\n\
         }\n",
    );

    session.ingest_file(file.clone(), source.clone());
    let parsed = php_rs_parser::parse(&source);
    let _ = FileAnalyzer::new(&session).analyze(
        file.clone(),
        &source,
        &parsed.program,
        &parsed.source_map,
    );

    let base_refs = session
        .indexed_references_to(
            &Name::class("Base"),
            std::slice::from_ref(&file),
            false,
            &|| false,
        )
        .expect("not cancelled");
    assert!(
        base_refs.iter().any(|(f, _)| f.as_ref() == file.as_ref()),
        "references_to(Base) must find `class Child extends Base`"
    );

    let iface_refs = session
        .indexed_references_to(
            &Name::class("Greets"),
            std::slice::from_ref(&file),
            false,
            &|| false,
        )
        .expect("not cancelled");
    assert!(
        iface_refs.iter().any(|(f, _)| f.as_ref() == file.as_ref()),
        "references_to(Greets) must find `implements Greets`"
    );

    let trait_refs = session
        .indexed_references_to(
            &Name::class("Helper"),
            std::slice::from_ref(&file),
            false,
            &|| false,
        )
        .expect("not cancelled");
    assert!(
        trait_refs.iter().any(|(f, _)| f.as_ref() == file.as_ref()),
        "references_to(Helper) must find `use Helper;`"
    );
}