php-lsp 0.1.54

A PHP Language Server Protocol implementation
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
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
/// Single-pass type inference: collects `$var = new ClassName()` assignments
/// to map variable names to class names.  Used to scope method completions
/// after `->`.
use std::collections::HashMap;

use php_ast::{
    BinaryOp, ClassMemberKind, EnumMemberKind, ExprKind, NamespaceBody, Stmt, StmtKind, TypeHint,
    TypeHintKind,
};
use tower_lsp::lsp_types::Position;

use crate::ast::{ParsedDoc, offset_to_position};
use crate::docblock::{docblock_before, parse_docblock};
use crate::phpstorm_meta::PhpStormMeta;

/// Maps variable name (with `$`) → class name.
#[derive(Debug, Default, Clone)]
pub struct TypeMap(HashMap<String, String>);

impl TypeMap {
    /// Build from a parsed document.
    pub fn from_doc(doc: &ParsedDoc) -> Self {
        Self::from_doc_with_meta(doc, None)
    }

    /// Build from a parsed document, optionally enriched by PHPStorm metadata
    /// for factory-method return type inference.
    pub fn from_doc_with_meta(doc: &ParsedDoc, meta: Option<&PhpStormMeta>) -> Self {
        let method_returns = build_method_returns(doc);
        let mut map = HashMap::new();
        collect_types_stmts(
            doc.source(),
            &doc.program().stmts,
            &mut map,
            meta,
            &method_returns,
        );
        TypeMap(map)
    }

    /// Build from a parsed document plus cross-file docs, optionally enriched
    /// by PHPStorm metadata. Method-return-type inference spans all provided docs.
    pub fn from_docs_with_meta(
        doc: &ParsedDoc,
        other_docs: &[std::sync::Arc<ParsedDoc>],
        meta: Option<&PhpStormMeta>,
    ) -> Self {
        let mut method_returns = build_method_returns(doc);
        for other in other_docs {
            let other_returns = build_method_returns(other);
            for (class, methods) in other_returns {
                method_returns.entry(class).or_default().extend(methods);
            }
        }
        let mut map = HashMap::new();
        collect_types_stmts(
            doc.source(),
            &doc.program().stmts,
            &mut map,
            meta,
            &method_returns,
        );
        TypeMap(map)
    }

    /// Returns the class name for a variable, e.g. `get("$obj")` → `Some("Foo")`.
    pub fn get<'a>(&'a self, var: &str) -> Option<&'a str> {
        self.0.get(var).map(|s| s.as_str())
    }
}

/// Pre-build a map of class_name → method_name → return_class_name from all given docs.
pub fn build_method_returns(doc: &ParsedDoc) -> HashMap<String, HashMap<String, String>> {
    let mut out = HashMap::new();
    collect_method_returns_stmts(doc.source(), &doc.program().stmts, &mut out);
    out
}

fn collect_method_returns_stmts(
    source: &str,
    stmts: &[Stmt<'_, '_>],
    out: &mut HashMap<String, HashMap<String, String>>,
) {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) => {
                let class_name = match c.name {
                    Some(n) => n.to_string(),
                    None => continue,
                };
                for member in c.members.iter() {
                    if let ClassMemberKind::Method(m) = &member.kind
                        && let Some(ret) =
                            extract_method_return_class(source, member.span.start, m, &class_name)
                    {
                        out.entry(class_name.clone())
                            .or_default()
                            .insert(m.name.to_string(), ret);
                    }
                }
            }
            StmtKind::Trait(t) => {
                let trait_name = t.name.to_string();
                for member in t.members.iter() {
                    if let ClassMemberKind::Method(m) = &member.kind
                        && let Some(ret) =
                            extract_method_return_class(source, member.span.start, m, &trait_name)
                    {
                        out.entry(trait_name.clone())
                            .or_default()
                            .insert(m.name.to_string(), ret);
                    }
                }
            }
            StmtKind::Enum(e) => {
                let enum_name = e.name.to_string();
                for member in e.members.iter() {
                    if let EnumMemberKind::Method(m) = &member.kind
                        && let Some(ret) =
                            extract_method_return_class(source, member.span.start, m, &enum_name)
                    {
                        out.entry(enum_name.clone())
                            .or_default()
                            .insert(m.name.to_string(), ret);
                    }
                }
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body {
                    collect_method_returns_stmts(source, inner, out);
                }
            }
            _ => {}
        }
    }
}

fn extract_method_return_class(
    source: &str,
    member_start: u32,
    m: &php_ast::MethodDecl<'_, '_>,
    enclosing_class: &str,
) -> Option<String> {
    // 1. AST return type hint takes priority
    if let Some(hint) = &m.return_type
        && let Some(s) = type_hint_to_class_string(hint, Some(enclosing_class))
    {
        return Some(s);
    }
    // 2. @return docblock fallback
    if let Some(raw) = docblock_before(source, member_start) {
        let db = parse_docblock(&raw);
        if let Some(ret) = db.return_type {
            for part in ret.type_hint.split('|') {
                let part = part.trim().trim_start_matches('\\').trim_start_matches('?');
                let short = part.rsplit('\\').next().unwrap_or(part);
                if short == "self" || short == "static" {
                    return Some(enclosing_class.to_string());
                }
                let first = short.chars().next().unwrap_or('_');
                if first.is_uppercase() && !matches!(short, "void" | "never" | "null") {
                    return Some(short.to_string());
                }
            }
        }
    }
    None
}

/// Extract a class-name string from a type hint using mir's type resolver.
/// - `Named(Foo)` → `"Foo"`, `Named(\App\Foo)` → `"Foo"` (short name)
/// - `Nullable(Named(Foo))` → `"Foo"` (strips the nullable wrapper)
/// - `Union([Named(Foo), Named(Bar)])` → `"Foo|Bar"`
/// - `self` / `static` with `enclosing` → returns the enclosing short name
/// - Primitives and unrecognised kinds → `None`
fn type_hint_to_class_string(
    hint: &TypeHint<'_, '_>,
    enclosing_class: Option<&str>,
) -> Option<String> {
    use mir_types::Atomic;
    let union = mir_analyzer::parser::type_from_hint(hint, enclosing_class);
    let classes: Vec<String> = union
        .types
        .iter()
        .filter_map(|a| match a {
            Atomic::TNamedObject { fqcn, .. }
            | Atomic::TSelf { fqcn }
            | Atomic::TStaticObject { fqcn }
            | Atomic::TParent { fqcn } => {
                let short = fqcn.rsplit('\\').next().unwrap_or(fqcn.as_ref());
                Some(short.to_string())
            }
            _ => None,
        })
        .collect();
    if classes.is_empty() {
        None
    } else {
        Some(classes.join("|"))
    }
}

fn collect_types_stmts(
    source: &str,
    stmts: &[Stmt<'_, '_>],
    map: &mut HashMap<String, String>,
    meta: Option<&PhpStormMeta>,
    method_returns: &HashMap<String, HashMap<String, String>>,
) {
    for stmt in stmts {
        // Check for `/** @var ClassName $varName */` docblock before this statement.
        if let Some(raw) = docblock_before(source, stmt.span.start) {
            let db = parse_docblock(&raw);
            if let Some(type_str) = db.var_type {
                // Only map object types (starts with uppercase or backslash).
                // type_str may be a union like "Foo|null"; take the first class part.
                let class_name = type_str
                    .split('|')
                    .map(|p| p.trim().trim_start_matches('\\').trim_start_matches('?'))
                    .find(|p| p.chars().next().map(|c| c.is_uppercase()).unwrap_or(false))
                    .and_then(|p| p.rsplit('\\').next())
                    .map(|p| p.to_string());
                if let Some(class_name) = class_name {
                    if let Some(vname) = db.var_name {
                        // `@var Foo $obj` — explicit variable name.
                        map.insert(format!("${}", vname.as_str()), class_name);
                    } else if let StmtKind::Expression(e) = &stmt.kind {
                        // `@var Foo` above `$obj = ...` — infer from the LHS.
                        if let ExprKind::Assign(a) = &e.kind
                            && let ExprKind::Variable(vn) = &a.target.kind
                        {
                            map.insert(format!("${}", vn.as_str()), class_name);
                        }
                    }
                }
            }
        }

        match &stmt.kind {
            StmtKind::Expression(e) => collect_types_expr(source, e, map, meta, method_returns),
            StmtKind::Function(f) => {
                // Read @param docblock hints — fills in types for untyped params
                if let Some(raw) = docblock_before(source, stmt.span.start) {
                    let db = parse_docblock(&raw);
                    for param in &db.params {
                        // For union types, collect all class parts joined by |
                        let classes: Vec<&str> = param
                            .type_hint
                            .split('|')
                            .map(|p| p.trim().trim_start_matches('\\').trim_start_matches('?'))
                            .filter(|p| p.chars().next().map(|c| c.is_uppercase()).unwrap_or(false))
                            .filter_map(|p| p.rsplit('\\').next())
                            .collect();
                        if !classes.is_empty() {
                            let key = if param.name.starts_with('$') {
                                param.name.clone()
                            } else {
                                format!("${}", param.name)
                            };
                            map.entry(key).or_insert_with(|| classes.join("|"));
                        }
                    }
                }
                for p in f.params.iter() {
                    if let Some(hint) = &p.type_hint
                        && let Some(class_str) = type_hint_to_class_string(hint, None)
                    {
                        map.insert(format!("${}", p.name), class_str);
                    }
                }
                collect_types_stmts(source, &f.body, map, meta, method_returns);
            }
            StmtKind::Class(c) => {
                let class_name = c.name.map(|n| n.to_string());
                for member in c.members.iter() {
                    if let ClassMemberKind::Method(m) = &member.kind {
                        // Read @param docblock hints — fills in types for untyped params
                        if let Some(raw) = docblock_before(source, member.span.start) {
                            let db = parse_docblock(&raw);
                            for param in &db.params {
                                // For union types, collect all class parts joined by |
                                let classes: Vec<&str> = param
                                    .type_hint
                                    .split('|')
                                    .map(|p| {
                                        p.trim().trim_start_matches('\\').trim_start_matches('?')
                                    })
                                    .filter(|p| {
                                        p.chars().next().map(|c| c.is_uppercase()).unwrap_or(false)
                                    })
                                    .filter_map(|p| p.rsplit('\\').next())
                                    .collect();
                                if !classes.is_empty() {
                                    let key = if param.name.starts_with('$') {
                                        param.name.clone()
                                    } else {
                                        format!("${}", param.name)
                                    };
                                    map.entry(key).or_insert_with(|| classes.join("|"));
                                }
                            }
                        }
                        for p in m.params.iter() {
                            if let Some(hint) = &p.type_hint
                                && let Some(class_str) =
                                    type_hint_to_class_string(hint, class_name.as_deref())
                            {
                                map.insert(format!("${}", p.name), class_str);
                            }
                        }
                        if let Some(body) = &m.body {
                            collect_types_stmts(source, body, map, meta, method_returns);
                        }
                    }
                }
            }
            StmtKind::Trait(t) => {
                for member in t.members.iter() {
                    if let ClassMemberKind::Method(m) = &member.kind {
                        for p in m.params.iter() {
                            if let Some(hint) = &p.type_hint
                                && let Some(class_str) = type_hint_to_class_string(hint, None)
                            {
                                map.insert(format!("${}", p.name), class_str);
                            }
                        }
                        if let Some(body) = &m.body {
                            collect_types_stmts(source, body, map, meta, method_returns);
                        }
                    }
                }
            }
            StmtKind::Enum(e) => {
                for member in e.members.iter() {
                    if let EnumMemberKind::Method(m) = &member.kind {
                        for p in m.params.iter() {
                            if let Some(hint) = &p.type_hint
                                && let Some(class_str) = type_hint_to_class_string(hint, None)
                            {
                                map.insert(format!("${}", p.name), class_str);
                            }
                        }
                        if let Some(body) = &m.body {
                            collect_types_stmts(source, body, map, meta, method_returns);
                        }
                    }
                }
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body {
                    collect_types_stmts(source, inner, map, meta, method_returns);
                }
            }
            // if ($x instanceof Foo) — narrow $x to Foo inside the then-branch
            StmtKind::If(if_stmt) => {
                // Check whether the condition is a simple `$var instanceof ClassName`.
                if let ExprKind::Binary(b) = &if_stmt.condition.kind
                    && b.op == BinaryOp::Instanceof
                    && let (ExprKind::Variable(var_name), ExprKind::Identifier(class)) =
                        (&b.left.kind, &b.right.kind)
                {
                    let var_key = format!("${}", var_name.as_str());
                    let narrowed = class
                        .as_str()
                        .trim_start_matches('\\')
                        .rsplit('\\')
                        .next()
                        .unwrap_or(class)
                        .to_string();
                    // Insert narrowed type then recurse into then-branch.
                    // The flat map keeps the last write, so code after the if-block
                    // may see the narrowed type — acceptable trade-off for a simple
                    // single-pass map.
                    map.insert(var_key, narrowed);
                }
                collect_types_stmts(
                    source,
                    std::slice::from_ref(if_stmt.then_branch),
                    map,
                    meta,
                    method_returns,
                );
                for elseif in if_stmt.elseif_branches.iter() {
                    collect_types_stmts(
                        source,
                        std::slice::from_ref(&elseif.body),
                        map,
                        meta,
                        method_returns,
                    );
                }
                if let Some(else_branch) = if_stmt.else_branch {
                    collect_types_stmts(
                        source,
                        std::slice::from_ref(else_branch),
                        map,
                        meta,
                        method_returns,
                    );
                }
            }

            // foreach ($arr as $item) — propagate element type from $arr[] to $item
            StmtKind::Foreach(f) => {
                if let ExprKind::Variable(arr_name) = &f.expr.kind {
                    let elem_key = format!("${}[]", arr_name.as_str());
                    if let Some(elem_type) = map.get(&elem_key).cloned()
                        && let ExprKind::Variable(val_name) = &f.value.kind
                    {
                        map.insert(format!("${}", val_name.as_str()), elem_type);
                    }
                }
                collect_types_stmts(
                    source,
                    std::slice::from_ref(f.body),
                    map,
                    meta,
                    method_returns,
                );
            }
            // try { ... } catch (FooException $e) { ... }
            // Map the catch variable to the first caught exception class.
            StmtKind::TryCatch(t) => {
                collect_types_stmts(source, &t.body, map, meta, method_returns);
                for catch in t.catches.iter() {
                    if let Some(var_name) = &catch.var
                        && let Some(first_type) = catch.types.first()
                    {
                        let class_name = first_type
                            .to_string_repr()
                            .trim_start_matches('\\')
                            .rsplit('\\')
                            .next()
                            .unwrap_or("")
                            .to_string();
                        if !class_name.is_empty() {
                            map.insert(format!("${}", var_name), class_name);
                        }
                    }
                    collect_types_stmts(source, &catch.body, map, meta, method_returns);
                }
                if let Some(finally) = &t.finally {
                    collect_types_stmts(source, finally, map, meta, method_returns);
                }
            }

            // static $var = expr — infer type from the default value expression.
            StmtKind::StaticVar(vars) => {
                for var in vars.iter() {
                    let var_key = format!("${}", var.name);
                    if let Some(default) = &var.default {
                        if let ExprKind::New(new_expr) = &default.kind
                            && let Some(class_name) = extract_class_name(new_expr.class)
                        {
                            map.insert(var_key.clone(), class_name);
                        }
                        if let ExprKind::Array(_) = &default.kind {
                            map.insert(var_key, "array".to_string());
                        }
                    }
                }
            }

            _ => {}
        }
    }
}

fn collect_types_expr(
    source: &str,
    expr: &php_ast::Expr<'_, '_>,
    map: &mut HashMap<String, String>,
    meta: Option<&PhpStormMeta>,
    method_returns: &HashMap<String, HashMap<String, String>>,
) {
    match &expr.kind {
        ExprKind::Assign(assign) => {
            if let ExprKind::Variable(var_name) = &assign.target.kind {
                // Handle ??= (null coalescing assignment): only assigns if null
                // so use or_insert (existing type takes precedence)
                if assign.op == php_ast::AssignOp::Coalesce {
                    if let ExprKind::New(new_expr) = &assign.value.kind
                        && let Some(class_name) = extract_class_name(new_expr.class)
                    {
                        map.entry(format!("${}", var_name.as_str()))
                            .or_insert(class_name);
                    }
                    collect_types_expr(source, assign.value, map, meta, method_returns);
                    return;
                }
                if let ExprKind::New(new_expr) = &assign.value.kind
                    && let Some(class_name) = extract_class_name(new_expr.class)
                {
                    map.insert(format!("${}", var_name.as_str()), class_name);
                }
                // $result = $obj->method() — infer result type from method's return type
                if let ExprKind::MethodCall(mc) = &assign.value.kind
                    && let (ExprKind::Variable(obj_var), ExprKind::Identifier(method_name)) =
                        (&mc.object.kind, &mc.method.kind)
                    && let Some(obj_class) = map.get(&format!("${}", obj_var.as_str())).cloned()
                    && let Some(class_rets) = method_returns.get(&obj_class)
                    && let Some(ret_type) = class_rets.get(method_name.as_str())
                {
                    map.insert(format!("${}", var_name.as_str()), ret_type.clone());
                }
                // PHPStorm meta: `$var = $obj->make(SomeClass::class)`
                if let Some(meta) = meta
                    && let Some(inferred) = infer_from_meta_method_call(assign.value, map, meta)
                {
                    map.insert(format!("${}", var_name.as_str()), inferred);
                }
                // $result = array_map(fn($x): Foo => ..., $arr) → $result[] = Foo
                if let Some(elem_type) = extract_array_callback_return_type(assign.value) {
                    map.insert(format!("${}[]", var_name.as_str()), elem_type);
                }
            }
            collect_types_expr(source, assign.value, map, meta, method_returns);
        }

        // Closure::bind($fn, $obj) → $this maps to $obj's class
        ExprKind::StaticMethodCall(s) => {
            if let ExprKind::Identifier(class) = &s.class.kind
                && class.as_str() == "Closure"
                && s.method == "bind"
                && let Some(obj_arg) = s.args.get(1)
                && let Some(cls) = resolve_var_type_str(&obj_arg.value, map)
            {
                map.insert("$this".to_string(), cls);
            }
        }

        // $fn->bindTo($obj) or $fn->call($obj) → $this maps to $obj's class
        ExprKind::MethodCall(m) => {
            if let ExprKind::Identifier(method) = &m.method.kind {
                let mname = method.as_str();
                if (mname == "bindTo" || mname == "call")
                    && let Some(obj_arg) = m.args.first()
                    && let Some(cls) = resolve_var_type_str(&obj_arg.value, map)
                {
                    map.insert("$this".to_string(), cls);
                }
            }
        }

        // Walk closure bodies so inner assignments are also captured
        ExprKind::Closure(c) => {
            for p in c.params.iter() {
                if let Some(hint) = &p.type_hint
                    && let TypeHintKind::Named(name) = &hint.kind
                {
                    map.insert(format!("${}", p.name), name.to_string_repr().to_string());
                }
            }
            // Snapshot captured `use` variable types from the outer scope so they
            // remain resolvable inside the closure body even if the body walk
            // encounters assignments that would shadow them.
            let use_var_snapshot: Vec<(String, String)> = c
                .use_vars
                .iter()
                .filter_map(|uv| {
                    let key = format!("${}", uv.name);
                    map.get(&key).map(|ty| (key, ty.clone()))
                })
                .collect();
            collect_types_stmts(source, &c.body, map, meta, method_returns);
            // Restore captured variable types: inner assignments inside the closure
            // body should not affect the outer scope's type for completions.
            for (key, ty) in use_var_snapshot {
                map.insert(key, ty);
            }
        }

        ExprKind::ArrowFunction(af) => {
            for p in af.params.iter() {
                if let Some(hint) = &p.type_hint
                    && let TypeHintKind::Named(name) = &hint.kind
                {
                    map.insert(format!("${}", p.name), name.to_string_repr().to_string());
                }
            }
            collect_types_expr(source, af.body, map, meta, method_returns);
        }

        _ => {}
    }
}

/// For `array_map`/`array_filter` calls: extract the return type of the first
/// (callback) argument if it has an explicit type hint, e.g.
/// `array_map(fn($x): Foo => $x->transform(), $arr)` → `"Foo"`.
fn extract_array_callback_return_type(expr: &php_ast::Expr<'_, '_>) -> Option<String> {
    let ExprKind::FunctionCall(call) = &expr.kind else {
        return None;
    };
    let fn_name = match &call.name.kind {
        ExprKind::Identifier(n) => n.as_str(),
        _ => return None,
    };
    if fn_name != "array_map" && fn_name != "array_filter" {
        return None;
    }
    let callback_arg = call.args.first()?;
    extract_callback_return_type(&callback_arg.value)
}

/// Extract the return-type class name from a Closure or ArrowFunction expression.
fn extract_callback_return_type(expr: &php_ast::Expr<'_, '_>) -> Option<String> {
    let hint = match &expr.kind {
        ExprKind::Closure(c) => c.return_type.as_ref()?,
        ExprKind::ArrowFunction(af) => af.return_type.as_ref()?,
        _ => return None,
    };
    if let TypeHintKind::Named(name) = &hint.kind {
        let s = name.to_string_repr();
        let base = s.trim_start_matches('\\');
        let short = base.rsplit('\\').next().unwrap_or(base);
        if short
            .chars()
            .next()
            .map(|c| c.is_uppercase())
            .unwrap_or(false)
        {
            return Some(short.to_string());
        }
    }
    None
}

/// Look up the class of a `$variable` expression from the current map.
fn resolve_var_type_str(
    expr: &php_ast::Expr<'_, '_>,
    map: &HashMap<String, String>,
) -> Option<String> {
    if let ExprKind::Variable(v) = &expr.kind {
        map.get(&format!("${}", v.as_str())).cloned()
    } else {
        None
    }
}

fn extract_class_name(expr: &php_ast::Expr<'_, '_>) -> Option<String> {
    match &expr.kind {
        ExprKind::Identifier(name) => Some(name.as_str().to_string()),
        _ => None,
    }
}

/// Try to infer the return type of `$obj->method(SomeClass::class)` using the
/// PHPStorm meta map.  `map` is consulted to resolve `$obj`'s class.
fn infer_from_meta_method_call(
    expr: &php_ast::Expr<'_, '_>,
    var_map: &HashMap<String, String>,
    meta: &PhpStormMeta,
) -> Option<String> {
    let ExprKind::MethodCall(m) = &expr.kind else {
        return None;
    };
    // Resolve the receiver's type.
    let receiver_class = match &m.object.kind {
        ExprKind::Variable(v) => {
            let key = format!("${}", v.as_str());
            var_map.get(&key)?.clone()
        }
        _ => return None,
    };
    // Get the method name.
    let method_name = match &m.method.kind {
        ExprKind::Identifier(n) => n.to_string(),
        _ => return None,
    };
    // Get the first argument as a class name string.
    let arg = m.args.first()?;
    let arg_str = match &arg.value.kind {
        ExprKind::String(s) => s.trim_start_matches('\\').to_string(),
        ExprKind::ClassConstAccess(c) if c.member == "class" => match &c.class.kind {
            ExprKind::Identifier(n) => n
                .trim_start_matches('\\')
                .rsplit('\\')
                .next()
                .unwrap_or(n)
                .to_string(),
            _ => return None,
        },
        _ => return None,
    };
    meta.resolve_return_type(&receiver_class, &method_name, &arg_str)
        .map(|s| s.to_string())
}

/// Return the direct parent class name of `class_name` in `doc`, if any.
pub fn parent_class_name(doc: &ParsedDoc, class_name: &str) -> Option<String> {
    parent_in_stmts(&doc.program().stmts, class_name)
}

fn parent_in_stmts(stmts: &[Stmt<'_, '_>], class_name: &str) -> Option<String> {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) if c.name == Some(class_name) => {
                return c.extends.as_ref().map(|n| n.to_string_repr().to_string());
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body
                    && let found @ Some(_) = parent_in_stmts(inner, class_name)
                {
                    return found;
                }
            }
            _ => {}
        }
    }
    None
}

/// All members of a named class split by kind and static-ness.
#[derive(Debug, Default)]
pub struct ClassMembers {
    /// (name, is_static)
    pub methods: Vec<(String, bool)>,
    /// (name, is_static)
    pub properties: Vec<(String, bool)>,
    /// Names of readonly properties (PHP 8.1+).
    pub readonly_properties: Vec<String>,
    pub constants: Vec<String>,
    /// Direct parent class name, if any.
    pub parent: Option<String>,
    /// Trait names used by this class (`use Foo, Bar;`).
    pub trait_uses: Vec<String>,
}

/// Return all members (methods, properties, constants) of `class_name`.
/// Also returns the direct parent class name via `ClassMembers::parent`.
pub fn members_of_class(doc: &ParsedDoc, class_name: &str) -> ClassMembers {
    let mut out = ClassMembers::default();
    out.parent = collect_members_stmts(doc.source(), &doc.program().stmts, class_name, &mut out);
    out
}

fn collect_members_stmts(
    source: &str,
    stmts: &[Stmt<'_, '_>],
    class_name: &str,
    out: &mut ClassMembers,
) -> Option<String> {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) if c.name == Some(class_name) => {
                // Check docblock for @property and @method tags
                if let Some(raw) = docblock_before(source, stmt.span.start) {
                    let db = parse_docblock(&raw);
                    for prop in &db.properties {
                        out.properties.push((prop.name.clone(), false));
                    }
                    for method in &db.methods {
                        out.methods.push((method.name.clone(), method.is_static));
                    }
                }
                for member in c.members.iter() {
                    match &member.kind {
                        ClassMemberKind::Method(m) => {
                            out.methods.push((m.name.to_string(), m.is_static));
                            // Constructor-promoted params become instance properties.
                            if m.name == "__construct" {
                                for p in m.params.iter() {
                                    if p.visibility.is_some() {
                                        out.properties.push((p.name.to_string(), false));
                                        // Detect `readonly` in the source text before the
                                        // param name (the AST does not expose this flag on
                                        // Param, so we scan the raw text of the param span).
                                        let param_src =
                                            &source[p.span.start as usize..p.span.end as usize];
                                        if param_src.contains("readonly") {
                                            out.readonly_properties.push(p.name.to_string());
                                        }
                                    }
                                }
                            }
                        }
                        ClassMemberKind::Property(p) => {
                            out.properties.push((p.name.to_string(), p.is_static));
                            if p.is_readonly {
                                out.readonly_properties.push(p.name.to_string());
                            }
                        }
                        ClassMemberKind::ClassConst(c) => {
                            out.constants.push(c.name.to_string());
                        }
                        ClassMemberKind::TraitUse(t) => {
                            for name in t.traits.iter() {
                                out.trait_uses.push(name.to_string_repr().to_string());
                            }
                        }
                    }
                }
                return c.extends.as_ref().map(|n| n.to_string_repr().to_string());
            }
            StmtKind::Enum(e) if e.name == class_name => {
                let is_backed = e.scalar_type.is_some();
                // Every enum instance exposes `->name`; backed enums also expose `->value`.
                out.properties.push(("name".to_string(), false));
                if is_backed {
                    out.properties.push(("value".to_string(), false));
                }
                // Built-in static methods present on every enum.
                out.methods.push(("cases".to_string(), true));
                if is_backed {
                    out.methods.push(("from".to_string(), true));
                    out.methods.push(("tryFrom".to_string(), true));
                }
                // User-declared cases, methods, and constants.
                for member in e.members.iter() {
                    match &member.kind {
                        EnumMemberKind::Case(c) => {
                            out.constants.push(c.name.to_string());
                        }
                        EnumMemberKind::Method(m) => {
                            out.methods.push((m.name.to_string(), m.is_static));
                        }
                        EnumMemberKind::ClassConst(c) => {
                            out.constants.push(c.name.to_string());
                        }
                        _ => {}
                    }
                }
                return None; // enums have no parent class
            }
            StmtKind::Trait(t) if t.name == class_name => {
                for member in t.members.iter() {
                    match &member.kind {
                        ClassMemberKind::Method(m) => {
                            out.methods.push((m.name.to_string(), m.is_static));
                        }
                        ClassMemberKind::Property(p) => {
                            out.properties.push((p.name.to_string(), p.is_static));
                        }
                        ClassMemberKind::ClassConst(c) => {
                            out.constants.push(c.name.to_string());
                        }
                        ClassMemberKind::TraitUse(t) => {
                            for name in t.traits.iter() {
                                out.trait_uses.push(name.to_string_repr().to_string());
                            }
                        }
                    }
                }
                return None; // traits have no parent
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body {
                    let result = collect_members_stmts(source, inner, class_name, out);
                    if result.is_some() {
                        return result;
                    }
                }
            }
            _ => {}
        }
    }
    None
}

/// Return the `@mixin` class names declared in `class_name`'s docblock.
pub fn mixin_classes_of(doc: &ParsedDoc, class_name: &str) -> Vec<String> {
    let source = doc.source();
    mixin_classes_in_stmts(source, &doc.program().stmts, class_name)
}

fn mixin_classes_in_stmts(source: &str, stmts: &[Stmt<'_, '_>], class_name: &str) -> Vec<String> {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) if c.name == Some(class_name) => {
                if let Some(raw) = docblock_before(source, stmt.span.start) {
                    return parse_docblock(&raw).mixins;
                }
                return vec![];
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body {
                    let found = mixin_classes_in_stmts(source, inner, class_name);
                    if !found.is_empty() {
                        return found;
                    }
                }
            }
            _ => {}
        }
    }
    vec![]
}

/// Return the name of the class whose body contains `position`, or `None`.
pub fn enclosing_class_at(source: &str, doc: &ParsedDoc, position: Position) -> Option<String> {
    enclosing_class_in_stmts(source, &doc.program().stmts, position)
}

fn enclosing_class_in_stmts(source: &str, stmts: &[Stmt<'_, '_>], pos: Position) -> Option<String> {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) => {
                let start = offset_to_position(source, stmt.span.start).line;
                let end = offset_to_position(source, stmt.span.end).line;
                if pos.line >= start && pos.line <= end {
                    return c.name.map(|n| n.to_string());
                }
            }
            StmtKind::Enum(e) => {
                let start = offset_to_position(source, stmt.span.start).line;
                let end = offset_to_position(source, stmt.span.end).line;
                if pos.line >= start && pos.line <= end {
                    return Some(e.name.to_string());
                }
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body
                    && let Some(found) = enclosing_class_in_stmts(source, inner, pos)
                {
                    return Some(found);
                }
            }
            _ => {}
        }
    }
    None
}

/// Return the parameter names of the function or method named `func_name`.
pub fn params_of_function(doc: &ParsedDoc, func_name: &str) -> Vec<String> {
    let mut out = Vec::new();
    collect_params_stmts(&doc.program().stmts, func_name, &mut out);
    out
}

/// Return the parameter names of `method_name` on class `class_name`.
/// Primarily used to offer named-argument completions for attribute constructors.
pub fn params_of_method(doc: &ParsedDoc, class_name: &str, method_name: &str) -> Vec<String> {
    let mut out = Vec::new();
    collect_method_params_stmts(&doc.program().stmts, class_name, method_name, &mut out);
    out
}

fn collect_method_params_stmts(
    stmts: &[php_ast::Stmt<'_, '_>],
    class_name: &str,
    method_name: &str,
    out: &mut Vec<String>,
) {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) if c.name == Some(class_name) => {
                for member in c.members.iter() {
                    if let ClassMemberKind::Method(m) = &member.kind
                        && m.name == method_name
                    {
                        for p in m.params.iter() {
                            out.push(p.name.to_string());
                        }
                        return;
                    }
                }
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body {
                    collect_method_params_stmts(inner, class_name, method_name, out);
                }
            }
            _ => {}
        }
    }
}

/// Returns `true` if `class_name` is declared as an `enum` in `doc`.
pub fn is_enum(doc: &ParsedDoc, class_name: &str) -> bool {
    is_enum_in_stmts(&doc.program().stmts, class_name)
}

fn is_enum_in_stmts(stmts: &[Stmt<'_, '_>], name: &str) -> bool {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Enum(e) if e.name == name => return true,
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body
                    && is_enum_in_stmts(inner, name)
                {
                    return true;
                }
            }
            _ => {}
        }
    }
    false
}

/// Returns `true` if `class_name` is a *backed* enum (`enum Foo: string` /
/// `enum Foo: int`) in `doc`.  Backed enums have a `->value` property.
pub fn is_backed_enum(doc: &ParsedDoc, class_name: &str) -> bool {
    is_backed_enum_in_stmts(&doc.program().stmts, class_name)
}

fn is_backed_enum_in_stmts(stmts: &[Stmt<'_, '_>], name: &str) -> bool {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Enum(e) if e.name == name => return e.scalar_type.is_some(),
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body
                    && is_backed_enum_in_stmts(inner, name)
                {
                    return true;
                }
            }
            _ => {}
        }
    }
    false
}

fn collect_params_stmts(stmts: &[Stmt<'_, '_>], func_name: &str, out: &mut Vec<String>) {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Function(f) if f.name == func_name => {
                for p in f.params.iter() {
                    out.push(p.name.to_string());
                }
                return;
            }
            StmtKind::Class(c) => {
                for member in c.members.iter() {
                    if let ClassMemberKind::Method(m) = &member.kind
                        && m.name == func_name
                    {
                        for p in m.params.iter() {
                            out.push(p.name.to_string());
                        }
                        return;
                    }
                }
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body {
                    collect_params_stmts(inner, func_name, out);
                }
            }
            _ => {}
        }
    }
}

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

    #[test]
    fn infers_type_from_new_expression() {
        let src = "<?php\n$obj = new Foo();";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(tm.get("$obj"), Some("Foo"));
    }

    #[test]
    fn unknown_variable_returns_none() {
        let src = "<?php\n$obj = new Foo();";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert!(tm.get("$other").is_none());
    }

    #[test]
    fn multiple_assignments() {
        let src = "<?php\n$a = new Foo();\n$b = new Bar();";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(tm.get("$a"), Some("Foo"));
        assert_eq!(tm.get("$b"), Some("Bar"));
    }

    #[test]
    fn later_assignment_overwrites() {
        let src = "<?php\n$a = new Foo();\n$a = new Bar();";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(tm.get("$a"), Some("Bar"));
    }

    #[test]
    fn infers_type_from_typed_param() {
        let src = "<?php\nfunction process(Mailer $mailer): void { $mailer-> }";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(tm.get("$mailer"), Some("Mailer"));
    }

    #[test]
    fn parent_class_name_finds_parent() {
        let src = "<?php\nclass Base {}\nclass Child extends Base {}";
        let doc = ParsedDoc::parse(src.to_string());
        assert_eq!(parent_class_name(&doc, "Child"), Some("Base".to_string()));
    }

    #[test]
    fn parent_class_name_returns_none_for_top_level() {
        let src = "<?php\nclass Base {}";
        let doc = ParsedDoc::parse(src.to_string());
        assert!(parent_class_name(&doc, "Base").is_none());
    }

    #[test]
    fn members_of_class_includes_parent_field() {
        let src = "<?php\nclass Base {}\nclass Child extends Base {}";
        let doc = ParsedDoc::parse(src.to_string());
        let m = members_of_class(&doc, "Child");
        assert_eq!(m.parent.as_deref(), Some("Base"));
    }

    #[test]
    fn members_of_class_finds_methods() {
        let src = "<?php\nclass Calc { public function add() {} public function sub() {} }";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "Calc");
        let names: Vec<&str> = members.methods.iter().map(|(n, _)| n.as_str()).collect();
        assert!(names.contains(&"add"), "missing 'add'");
        assert!(names.contains(&"sub"), "missing 'sub'");
    }

    #[test]
    fn members_of_unknown_class_is_empty() {
        let src = "<?php\nclass Calc { public function add() {} }";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "Unknown");
        assert!(members.methods.is_empty());
    }

    #[test]
    fn constructor_promoted_params_appear_as_properties() {
        let src = "<?php\nclass Point {\n    public function __construct(\n        public float $x,\n        public float $y,\n    ) {}\n}";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "Point");
        let prop_names: Vec<&str> = members.properties.iter().map(|(n, _)| n.as_str()).collect();
        assert!(
            prop_names.contains(&"x"),
            "promoted param x should be a property"
        );
        assert!(
            prop_names.contains(&"y"),
            "promoted param y should be a property"
        );
    }

    #[test]
    fn promoted_readonly_params_appear_in_readonly_properties() {
        let src = "<?php\nclass User {\n    public function __construct(\n        public readonly string $name,\n        public int $age,\n    ) {}\n}";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "User");
        let prop_names: Vec<&str> = members.properties.iter().map(|(n, _)| n.as_str()).collect();
        assert!(
            prop_names.contains(&"name"),
            "promoted param name should be a property"
        );
        assert!(
            prop_names.contains(&"age"),
            "promoted param age should be a property"
        );
        assert!(
            members.readonly_properties.contains(&"name".to_string()),
            "readonly promoted param name should be in readonly_properties"
        );
        assert!(
            !members.readonly_properties.contains(&"age".to_string()),
            "non-readonly promoted param age should not be in readonly_properties"
        );
    }

    #[test]
    fn enum_instance_members_include_name() {
        let src = "<?php\nenum Status { case Active; case Inactive; }";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "Status");
        let prop_names: Vec<&str> = members.properties.iter().map(|(n, _)| n.as_str()).collect();
        assert!(
            prop_names.contains(&"name"),
            "pure enum should expose ->name"
        );
        assert!(
            !prop_names.contains(&"value"),
            "pure enum should not expose ->value"
        );
    }

    #[test]
    fn backed_enum_exposes_value_and_factory_methods() {
        let src = "<?php\nenum Color: string { case Red = 'red'; }";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "Color");
        let prop_names: Vec<&str> = members.properties.iter().map(|(n, _)| n.as_str()).collect();
        let method_names: Vec<&str> = members.methods.iter().map(|(n, _)| n.as_str()).collect();
        assert!(
            prop_names.contains(&"value"),
            "backed enum should expose ->value"
        );
        assert!(
            method_names.contains(&"from"),
            "backed enum should have ::from()"
        );
        assert!(
            method_names.contains(&"tryFrom"),
            "backed enum should have ::tryFrom()"
        );
        assert!(
            method_names.contains(&"cases"),
            "enum should have ::cases()"
        );
    }

    #[test]
    fn enum_cases_appear_as_constants() {
        let src = "<?php\nenum Status { case Active; case Inactive; }";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "Status");
        assert!(members.constants.contains(&"Active".to_string()));
        assert!(members.constants.contains(&"Inactive".to_string()));
    }

    #[test]
    fn trait_members_are_collected() {
        let src = "<?php\ntrait Logging { public function log() {} public string $logFile; }";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "Logging");
        let method_names: Vec<&str> = members.methods.iter().map(|(n, _)| n.as_str()).collect();
        let prop_names: Vec<&str> = members.properties.iter().map(|(n, _)| n.as_str()).collect();
        assert!(
            method_names.contains(&"log"),
            "trait method log should be collected"
        );
        assert!(
            prop_names.contains(&"logFile"),
            "trait property logFile should be collected"
        );
    }

    #[test]
    fn class_with_trait_use_lists_trait() {
        let src = "<?php\ntrait Logging { public function log() {} }\nclass App { use Logging; }";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "App");
        assert!(
            members.trait_uses.contains(&"Logging".to_string()),
            "should list used trait"
        );
    }

    #[test]
    fn var_docblock_with_explicit_varname_infers_type() {
        let src = "<?php\n/** @var Mailer $mailer */\n$mailer = $container->get('mailer');";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$mailer"),
            Some("Mailer"),
            "@var with explicit name should map the variable"
        );
    }

    #[test]
    fn var_docblock_without_varname_infers_from_assignment() {
        let src = "<?php\n/** @var Repository */\n$repo = $this->getRepository();";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$repo"),
            Some("Repository"),
            "@var without name should use assignment LHS"
        );
    }

    #[test]
    fn var_docblock_does_not_map_primitive_types() {
        let src = "<?php\n/** @var string */\n$name = 'hello';";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        // Primitives (lowercase) should not be mapped as class names.
        assert!(
            tm.get("$name").is_none(),
            "primitive @var should not produce a class mapping"
        );
    }

    #[test]
    fn var_nullable_docblock_maps_to_class() {
        // `@var ?Foo $x` is now normalised to `Foo|null` by the mir parser.
        // The type_map must still infer the class name `Foo`, not `Foo|null`.
        let src = "<?php\n/** @var ?Mailer $mailer */\n$mailer = null;";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$mailer"),
            Some("Mailer"),
            "@var ?Foo should map to 'Foo', not 'Foo|null'"
        );
    }

    #[test]
    fn var_union_docblock_maps_first_class() {
        // `@var Foo|null $x` — first class-type component should be used.
        let src = "<?php\n/** @var Repository|null $repo */\n$repo = null;";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$repo"),
            Some("Repository"),
            "@var Foo|null should map to 'Foo', not 'Foo|null'"
        );
    }

    #[test]
    fn is_enum_pure() {
        let src = "<?php\nenum Suit { case Hearts; case Clubs; }";
        let doc = ParsedDoc::parse(src.to_string());
        assert!(is_enum(&doc, "Suit"));
        assert!(!is_backed_enum(&doc, "Suit"));
    }

    #[test]
    fn is_backed_enum_string() {
        let src = "<?php\nenum Status: string { case Active = 'active'; }";
        let doc = ParsedDoc::parse(src.to_string());
        assert!(is_enum(&doc, "Status"));
        assert!(is_backed_enum(&doc, "Status"));
    }

    #[test]
    fn is_enum_false_for_class() {
        let src = "<?php\nclass Foo {}";
        let doc = ParsedDoc::parse(src.to_string());
        assert!(!is_enum(&doc, "Foo"));
        assert!(!is_backed_enum(&doc, "Foo"));
    }

    #[test]
    fn array_map_with_typed_closure_populates_element_type() {
        let src = "<?php\n$objs = new Foo();\n$result = array_map(fn($x): Bar => $x->transform(), $objs);";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$result[]"),
            Some("Bar"),
            "array_map with typed fn callback should store element type as $result[]"
        );
    }

    #[test]
    fn foreach_propagates_array_map_element_type() {
        let src = "<?php\n$items = array_map(fn($x): Widget => $x, []);\nforeach ($items as $item) { $item-> }";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$item"),
            Some("Widget"),
            "foreach over array_map result should propagate element type to loop variable"
        );
    }

    #[test]
    fn closure_use_var_type_is_available_inside_body() {
        let src = "<?php\n$svc = new PaymentService();\n$fn = function() use ($svc) { $svc->process(); };";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$svc"),
            Some("PaymentService"),
            "captured use variable should retain its outer type inside closure body"
        );
    }

    #[test]
    fn closure_use_var_inner_assignment_does_not_override_outer_type() {
        // If inside a closure we assign $svc = new Other(), the outer $svc type
        // should be restored after walking the closure body (or_insert semantics).
        let src = "<?php\n$svc = new PaymentService();\n$fn = function() use ($svc) { $svc = new OtherService(); };";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        // The snapshot restore ensures $svc retains PaymentService for the outer scope.
        assert_eq!(
            tm.get("$svc"),
            Some("PaymentService"),
            "outer type should not be overwritten by inner assignment in closure"
        );
    }

    #[test]
    fn closure_bind_maps_this_to_obj_class() {
        let src = "<?php\n$service = new Mailer();\n$fn = Closure::bind(function() {}, $service);";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$this"),
            Some("Mailer"),
            "Closure::bind with typed object should map $this to that class"
        );
    }

    #[test]
    fn instanceof_narrows_variable_type() {
        let src = "<?php\nif ($x instanceof Foo) { $x->foo(); }";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$x"),
            Some("Foo"),
            "instanceof should narrow $x to Foo inside the if body"
        );
    }

    #[test]
    fn instanceof_narrows_fqn_to_short_name() {
        let src = "<?php\nif ($x instanceof App\\Services\\Mailer) { $x->send(); }";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$x"),
            Some("Mailer"),
            "instanceof with FQN should narrow to short name"
        );
    }

    #[test]
    fn closure_bind_to_maps_this_to_obj_class() {
        let src = "<?php\n$svc = new Logger();\n$fn = function() {};\n$bound = $fn->bindTo($svc);";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$this"),
            Some("Logger"),
            "bindTo() should map $this to the bound object's class"
        );
    }

    #[test]
    fn param_docblock_type_inferred() {
        let src = "<?php\n/**\n * @param Mailer $mailer\n */\nfunction send($mailer) { $mailer-> }";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(tm.get("$mailer"), Some("Mailer"));
    }

    #[test]
    fn param_docblock_does_not_override_ast_hint() {
        let src = "<?php\n/**\n * @param OtherClass $x\n */\nfunction foo(Foo $x) {}";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        // AST type hint takes precedence over docblock (AST processed after, overwrites)
        assert_eq!(tm.get("$x"), Some("Foo"));
    }

    #[test]
    fn method_chain_return_type_from_ast_hint() {
        let src = "<?php\nclass Repo {\n    public function findFirst(): User { }\n}\nclass User { public function getName(): string {} }\n$repo = new Repo();\n$user = $repo->findFirst();";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(tm.get("$user"), Some("User"));
    }

    #[test]
    fn method_chain_return_type_from_docblock() {
        let src = "<?php\nclass Repo {\n    /** @return Product */\n    public function latest() {}\n}\n$repo = new Repo();\n$product = $repo->latest();";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(tm.get("$product"), Some("Product"));
    }

    #[test]
    fn not_null_check_preserves_existing_type() {
        let src = "<?php\n$x = new Foo();\nif ($x !== null) { $x-> }";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(tm.get("$x"), Some("Foo"));
    }

    #[test]
    fn self_return_type_resolves_to_class() {
        let src = "<?php\nclass Builder {\n    public function setName(string $n): self { return $this; }\n}\n$b = new Builder();\n$b2 = $b->setName('x');";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(tm.get("$b2"), Some("Builder"));
    }

    #[test]
    fn null_coalesce_assign_infers_type() {
        let src = "<?php\n$obj ??= new Foo();";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(tm.get("$obj"), Some("Foo"));
    }

    #[test]
    fn docblock_property_appears_in_members() {
        let src =
            "<?php\n/**\n * @property string $email\n * @property-read int $id\n */\nclass User {}";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "User");
        let props: Vec<&str> = members.properties.iter().map(|(n, _)| n.as_str()).collect();
        assert!(props.contains(&"email"));
        assert!(props.contains(&"id"));
    }

    #[test]
    fn docblock_method_appears_in_members() {
        let src = "<?php\n/**\n * @method User find(int $id)\n * @method static Builder where(string $col, mixed $val)\n */\nclass Model {}";
        let doc = ParsedDoc::parse(src.to_string());
        let members = members_of_class(&doc, "Model");
        let method_names: Vec<&str> = members.methods.iter().map(|(n, _)| n.as_str()).collect();
        assert!(method_names.contains(&"find"));
        assert!(method_names.contains(&"where"));
        let where_static = members
            .methods
            .iter()
            .find(|(n, _)| n == "where")
            .map(|(_, s)| *s);
        assert_eq!(where_static, Some(true));
    }

    #[test]
    fn union_type_param_maps_both_classes() {
        // function f(Foo|Bar $x) — both Foo and Bar should be in the union type string
        let src = "<?php\nfunction f(Foo|Bar $x) {}";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        let val = tm.get("$x").expect("$x should be in the type map");
        assert!(
            val.contains("Foo"),
            "union type should contain 'Foo', got: {}",
            val
        );
        assert!(
            val.contains("Bar"),
            "union type should contain 'Bar', got: {}",
            val
        );
    }

    #[test]
    fn nullable_param_resolves_to_class() {
        // function f(?Foo $x) — $x should map to Foo (nullable stripped)
        let src = "<?php\nfunction f(?Foo $x) {}";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$x"),
            Some("Foo"),
            "nullable type hint ?Foo should map $x to Foo"
        );
    }

    #[test]
    fn static_return_type_resolves_to_class() {
        // A method returning `: static` inside `class Builder` — result should map to `Builder`
        let src = concat!(
            "<?php\n",
            "class Builder {\n",
            "    public function build(): static { return $this; }\n",
            "}\n",
            "$b = new Builder();\n",
            "$b2 = $b->build();\n",
        );
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$b2"),
            Some("Builder"),
            "method returning :static should resolve to the enclosing class 'Builder'"
        );
    }

    #[test]
    fn null_assignment_does_not_overwrite_class() {
        // $x = new Foo(); $x = null; — $x type should stay Foo because
        // assigning null does not overwrite a known class type in the single-pass map.
        let src = "<?php\n$x = new Foo();\n$x = null;\n";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        // The single-pass type map does not treat null as a class, so the last
        // successful class assignment (Foo) persists.
        assert_eq!(
            tm.get("$x"),
            Some("Foo"),
            "$x should retain its Foo type after being assigned null"
        );
    }

    #[test]
    fn infers_type_from_assignment_inside_trait_method() {
        let src = "<?php\ntrait Builder { public function make(): void { $obj = new Widget(); } }";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$obj"),
            Some("Widget"),
            "type map should walk into trait method bodies"
        );
    }

    #[test]
    fn infers_type_from_assignment_inside_enum_method() {
        let src = "<?php\nenum Color { case Red; public function make(): void { $obj = new Palette(); } }";
        let doc = ParsedDoc::parse(src.to_string());
        let tm = TypeMap::from_doc(&doc);
        assert_eq!(
            tm.get("$obj"),
            Some("Palette"),
            "type map should walk into enum method bodies"
        );
    }
}