phpantom_lsp 0.7.0

Fast PHP language server with deep type intelligence. Generics, Laravel, PHPStan annotations. Ready in an instant.
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
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
/// Type resolution for completion subjects.
///
/// This module contains the core entry points for resolving a completion
/// subject (e.g. `$this`, `self`, `static`, `$var`, `$this->prop`,
/// `ClassName`) to a concrete `ClassInfo` so that the correct completion
/// items can be offered.
///
/// The resolution logic is split across several sibling modules:
///
/// - [`super::call_resolution`]: Call expression and callable target
///   resolution (method calls, static calls, function calls, constructor
///   calls, signature help, named-argument completion).
/// - [`super::type_resolution`]: Type-hint string to `ClassInfo` mapping
///   (unions, intersections, generics, type aliases, object shapes).
/// - [`super::source_helpers`]: Source-text scanning helpers (closure return
///   types, first-class callable resolution, `new` expression parsing,
///   array access segment walking).
/// - [`super::variable_resolution`]: Variable type resolution via
///   assignment scanning and parameter type hints.
/// - [`super::type_narrowing`]: instanceof / assert / custom type guard
///   narrowing.
/// - [`super::closure_resolution`]: Closure and arrow-function parameter
///   resolution.
/// - [`crate::inheritance`]: Class inheritance merging (traits, mixins,
///   parent chain).
/// - [`super::conditional_resolution`]: PHPStan conditional return type
///   resolution at call sites.
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;

use crate::Backend;
use crate::docblock;
use crate::inheritance::resolve_property_type_hint;
use crate::php_type::PhpType;
use crate::subject_expr::SubjectExpr;
use crate::types::*;
use crate::util::{find_class_by_name, is_self_or_static, resolve_class_keyword};
use crate::virtual_members::resolve_class_fully_maybe_cached;

/// Type alias for the optional function-loader closure passed through
/// the resolution chain.  Reduces clippy `type_complexity` warnings.
pub(crate) type FunctionLoaderFn<'a> = Option<&'a dyn Fn(&str) -> Option<FunctionInfo>>;

/// Type alias for the optional constant-value-loader closure passed
/// through the resolution chain.  Given a constant name, returns
/// `Some(Some(value))` when the constant exists with a known value,
/// `Some(None)` when it exists but the value is unknown, and `None`
/// when the constant was not found.
pub(crate) type ConstantLoaderFn<'a> = Option<&'a dyn Fn(&str) -> Option<Option<String>>>;

/// Bundles optional cross-file loader callbacks so they can be threaded
/// through the resolution chain as a single argument instead of one
/// parameter per loader.
#[derive(Clone, Copy, Default)]
pub(crate) struct Loaders<'a> {
    /// Cross-file function resolution callback (optional).
    pub function_loader: FunctionLoaderFn<'a>,
    /// Cross-file constant value resolution callback (optional).
    ///
    /// Given a global constant name (e.g. `"PHP_EOL"`), returns the
    /// constant's value string so that the type can be inferred from
    /// the literal value.
    pub constant_loader: ConstantLoaderFn<'a>,
}

impl<'a> Loaders<'a> {
    /// Create a `Loaders` with only a function loader.
    pub fn with_function(fl: FunctionLoaderFn<'a>) -> Self {
        Self {
            function_loader: fl,
            constant_loader: None,
        }
    }
}

/// Bundles the context needed by [`resolve_target_classes`] and
/// the functions it delegates to.
///
/// Introduced to replace the 8-parameter signature of
/// `resolve_target_classes` with a cleaner `(subject, access_kind, ctx)`
/// triple.  Also used directly by `resolve_call_return_types_expr` and
/// `resolve_arg_text_to_type` (formerly `CallResolutionCtx`).
pub(crate) struct ResolutionCtx<'a> {
    /// The class the cursor is inside, if any.
    pub current_class: Option<&'a ClassInfo>,
    /// All classes known in the current file.
    pub all_classes: &'a [Arc<ClassInfo>],
    /// The full source text of the current file.
    pub content: &'a str,
    /// Byte offset of the cursor in `content`.
    pub cursor_offset: u32,
    /// Cross-file class resolution callback.
    pub class_loader: &'a dyn Fn(&str) -> Option<Arc<ClassInfo>>,
    /// Shared cache of fully-resolved classes, keyed by FQN.
    ///
    /// When `Some`, [`resolve_class_fully_cached`](crate::virtual_members::resolve_class_fully_cached)
    /// is used instead of the uncached variant, eliminating redundant
    /// full-resolution work within a single request cycle.  `None` in
    /// contexts where no `Backend` (and therefore no cache) is available
    /// (e.g. standalone free-function callers, some test helpers).
    pub resolved_class_cache: Option<&'a crate::virtual_members::ResolvedClassCache>,
    /// Cross-file function resolution callback (optional).
    pub function_loader: FunctionLoaderFn<'a>,
}

/// Bundles the common parameters threaded through variable-type resolution.
///
/// Introducing this struct avoids passing 7–10 individual arguments to
/// every helper in the resolution chain, which keeps clippy happy and
/// makes call-sites much easier to read.
pub(super) struct VarResolutionCtx<'a> {
    pub var_name: &'a str,
    pub current_class: &'a ClassInfo,
    pub all_classes: &'a [Arc<ClassInfo>],
    pub content: &'a str,
    pub cursor_offset: u32,
    pub class_loader: &'a dyn Fn(&str) -> Option<Arc<ClassInfo>>,
    /// Cross-file loader callbacks (function loader, constant loader).
    pub loaders: Loaders<'a>,
    /// Shared cache of fully-resolved classes, keyed by FQN.
    ///
    /// See [`ResolutionCtx::resolved_class_cache`] for details.
    pub resolved_class_cache: Option<&'a crate::virtual_members::ResolvedClassCache>,
    /// The `@return` type annotation of the enclosing function/method,
    /// if known.  Used inside generator bodies to reverse-infer variable
    /// types from `Generator<TKey, TValue, TSend, TReturn>`.
    pub enclosing_return_type: Option<PhpType>,
    /// When `true`, if/else/elseif walking only considers the branch
    /// that contains the cursor instead of unioning all branches.
    /// This produces the single type visible at the cursor position,
    /// which is what hover needs (e.g. only `Lamp` inside an if-branch,
    /// not `Lamp|Faucet`).  Completion leaves this `false` so that all
    /// possible types are offered.
    pub branch_aware: bool,
}

impl<'a> VarResolutionCtx<'a> {
    /// Create a [`ResolutionCtx`] from this variable resolution context.
    ///
    /// The non-optional `current_class` is wrapped in `Some(…)`.
    pub(crate) fn as_resolution_ctx(&self) -> ResolutionCtx<'a> {
        ResolutionCtx {
            current_class: Some(self.current_class),
            all_classes: self.all_classes,
            content: self.content,
            cursor_offset: self.cursor_offset,
            class_loader: self.class_loader,
            function_loader: self.loaders.function_loader,
            resolved_class_cache: self.resolved_class_cache,
        }
    }

    /// Convenience accessor for the function loader.
    pub fn function_loader(&self) -> FunctionLoaderFn<'a> {
        self.loaders.function_loader
    }

    /// Convenience accessor for the constant loader.
    pub fn constant_loader(&self) -> ConstantLoaderFn<'a> {
        self.loaders.constant_loader
    }

    /// Clone this context with a different `enclosing_return_type`.
    ///
    /// All other fields are copied by reference.  This is useful when
    /// descending into a nested function/method body whose `@return`
    /// annotation differs from the outer scope.
    pub(super) fn with_enclosing_return_type(
        &self,
        enclosing_return_type: Option<PhpType>,
    ) -> VarResolutionCtx<'a> {
        VarResolutionCtx {
            var_name: self.var_name,
            current_class: self.current_class,
            all_classes: self.all_classes,
            content: self.content,
            cursor_offset: self.cursor_offset,
            class_loader: self.class_loader,
            loaders: self.loaders,
            resolved_class_cache: self.resolved_class_cache,
            enclosing_return_type,
            branch_aware: self.branch_aware,
        }
    }

    /// Clone this context with a different `cursor_offset`.
    ///
    /// All other fields (including `enclosing_return_type`) are preserved.
    /// This is useful when resolving a right-hand-side expression at a
    /// position earlier than the original cursor to avoid infinite
    /// recursion on self-referential assignments.
    pub(super) fn with_cursor_offset(&self, cursor_offset: u32) -> VarResolutionCtx<'a> {
        VarResolutionCtx {
            var_name: self.var_name,
            current_class: self.current_class,
            all_classes: self.all_classes,
            content: self.content,
            cursor_offset,
            class_loader: self.class_loader,
            loaders: self.loaders,
            resolved_class_cache: self.resolved_class_cache,
            enclosing_return_type: self.enclosing_return_type.clone(),
            branch_aware: self.branch_aware,
        }
    }
}

/// Thread-local cache for `resolve_target_classes` results.
/// Active during a diagnostic pass so that multiple collectors
/// (unknown_member, argument_count) share results instead of
/// re-resolving the same subjects independently.
///
/// The cache key is `(subject_text, access_kind, scope_start,
/// var_def_offset, narrowing_offset, assert_offset)` where
/// `scope_start` is the byte offset of the innermost enclosing
/// function/method/closure body and `var_def_offset` is the
/// `effective_from` of the active variable definition (or `0` for
/// non-variable subjects).
///
/// Bare variable subjects are NOT cached here — they bypass the cache
/// in [`resolve_subject_outcome`] by calling
/// [`resolve_target_classes_expr`] directly.  This ensures that
/// expression-level narrowing (ternary, `&&`) resolves fresh at each
/// cursor position.  The per-access discrimination is handled by
/// `SubjectCacheKey.access_offset` in `unknown_members.rs`.
///
/// Scope boundaries and variable definitions are stored alongside the
/// cache and set by [`set_diagnostic_subject_cache_scopes`].
type DiagSubjectCache =
    HashMap<(String, AccessKind, u32, u32, u32, u32), Vec<crate::types::ResolvedType>>;

/// File-level data stored alongside the diagnostic subject cache so
/// that [`resolve_target_classes`] can compute the enclosing scope and
/// active variable definition from the `cursor_offset` without needing
/// a reference to the [`SymbolMap`].
struct DiagSubjectCacheFileData {
    /// Scope boundaries `(start_offset, end_offset)`.
    scopes: Vec<(u32, u32)>,
    /// Variable definition sites, cloned from the [`SymbolMap`].
    var_defs: Vec<crate::symbol_map::VarDefSite>,
    /// Narrowing block boundaries `(start_offset, end_offset)` for
    /// if-body, elseif-body, else-body, match-arm, and switch-case
    /// blocks.  Used to compute the innermost narrowing context for
    /// a given cursor offset so that accesses in the same block share
    /// a cache entry while accesses in different branches do not.
    narrowing_blocks: Vec<(u32, u32)>,
    /// Sorted offsets of `assert($var instanceof …)` statements.
    /// Used as sequential narrowing boundaries so that accesses
    /// before and after an assert get separate cache entries.
    assert_narrowing_offsets: Vec<u32>,
}

type DiagSubjectCacheState = (DiagSubjectCache, DiagSubjectCacheFileData);

thread_local! {
    static DIAG_SUBJECT_CACHE: RefCell<Option<DiagSubjectCacheState>> = const { RefCell::new(None) };
}

// ── Helpers to convert between ResolvedType and Arc<ClassInfo> ──────
//
// Many internal callers (property chain bases, call resolution, etc.)
// still operate on `Vec<Arc<ClassInfo>>`.  These thin wrappers avoid
// repeating the conversion at every call site inside this module.

/// Convert `Vec<ResolvedType>` to `Vec<Arc<ClassInfo>>`, discarding
/// entries without class info (scalars, shapes, unresolvable types).
fn resolved_to_arcs(resolved: Vec<ResolvedType>) -> Vec<Arc<ClassInfo>> {
    ResolvedType::into_arced_classes(resolved)
}

/// Guard that owns the diagnostic subject cache lifetime.
/// Created by [`with_diagnostic_subject_cache`].
pub(crate) struct DiagSubjectCacheGuard {
    owns_cache: bool,
}

impl Drop for DiagSubjectCacheGuard {
    fn drop(&mut self) {
        if self.owns_cache {
            DIAG_SUBJECT_CACHE.with(|cell| {
                *cell.borrow_mut() = None;
            });
        }
    }
}

/// Activate the diagnostic subject cache for the current thread.
///
/// While the returned guard is alive, `resolve_target_classes` will
/// check and populate the cache.  Nested calls return a no-op guard.
///
/// After calling this, use [`set_diagnostic_subject_cache_scopes`] to
/// provide the scope boundaries for the file being diagnosed so that
/// the cache can distinguish variables in different methods.
pub(crate) fn with_diagnostic_subject_cache() -> DiagSubjectCacheGuard {
    let already_active = DIAG_SUBJECT_CACHE.with(|cell| cell.borrow().is_some());
    if already_active {
        return DiagSubjectCacheGuard { owns_cache: false };
    }
    DIAG_SUBJECT_CACHE.with(|cell| {
        *cell.borrow_mut() = Some((
            HashMap::new(),
            DiagSubjectCacheFileData {
                scopes: Vec::new(),
                var_defs: Vec::new(),
                narrowing_blocks: Vec::new(),
                assert_narrowing_offsets: Vec::new(),
            },
        ));
    });
    DiagSubjectCacheGuard { owns_cache: true }
}

/// Provide scope boundaries and variable definitions for the active
/// diagnostic subject cache.
///
/// Must be called while a [`DiagSubjectCacheGuard`] is alive.  The
/// scopes are `(start_offset, end_offset)` pairs for every
/// function, method, closure, and arrow function body in the file.
/// They are used to compute the enclosing scope for each
/// `cursor_offset`, ensuring that same-named variables in different
/// methods resolve independently.
///
/// The `var_defs` are cloned from the [`SymbolMap`] and used to
/// compute the active variable definition at each cursor offset,
/// ensuring that accesses before and after a variable reassignment
/// within the same method get independent cache entries.
///
/// The `narrowing_blocks` are `(start, end)` pairs for every
/// if-body, elseif-body, else-body, match-arm, and switch-case block
/// in the file.  They determine the innermost narrowing context for
/// each cursor offset so that accesses in the same block share a
/// cache entry while accesses in different instanceof-narrowing
/// branches get independent entries.
pub(crate) fn set_diagnostic_subject_cache_scopes(
    scopes: Vec<(u32, u32)>,
    var_defs: Vec<crate::symbol_map::VarDefSite>,
    narrowing_blocks: Vec<(u32, u32)>,
    assert_narrowing_offsets: Vec<u32>,
) {
    DIAG_SUBJECT_CACHE.with(|cell| {
        let mut borrow = cell.borrow_mut();
        if let Some((_map, file_data)) = borrow.as_mut() {
            file_data.scopes = scopes;
            file_data.var_defs = var_defs;
            file_data.narrowing_blocks = narrowing_blocks;
            file_data.assert_narrowing_offsets = assert_narrowing_offsets;
        }
    });
}

/// Find the enclosing scope start offset for a given cursor position
/// using the scope boundaries stored in the diagnostic subject cache.
///
/// Returns `0` when no scope contains the offset (top-level code) or
/// when the cache is not active.
fn diag_cache_enclosing_scope(cursor_offset: u32) -> u32 {
    DIAG_SUBJECT_CACHE.with(|cell| {
        let borrow = cell.borrow();
        match borrow.as_ref() {
            Some((_map, file_data)) => {
                let mut best: u32 = 0;
                for &(start, end) in &file_data.scopes {
                    if start <= cursor_offset && cursor_offset <= end && start > best {
                        best = start;
                    }
                }
                best
            }
            None => 0,
        }
    })
}

/// Find the innermost narrowing block (if/elseif/else body, match arm,
/// switch case) that contains the cursor offset, using the narrowing
/// block boundaries stored in the diagnostic subject cache.
///
/// Returns the block's start offset, or `0` when the offset is not
/// inside any narrowing block or when the cache is not active.  Two
/// variable accesses that return the same value will have identical
/// instanceof narrowing applied and can safely share a cache entry.
fn diag_cache_narrowing_block(cursor_offset: u32) -> u32 {
    DIAG_SUBJECT_CACHE.with(|cell| {
        let borrow = cell.borrow();
        match borrow.as_ref() {
            Some((_map, file_data)) => {
                let mut best: u32 = 0;
                for &(start, end) in &file_data.narrowing_blocks {
                    if start <= cursor_offset && cursor_offset <= end && start > best {
                        best = start;
                    }
                }
                best
            }
            None => 0,
        }
    })
}

/// Find the offset of the most recent `assert($var instanceof …)`
/// statement preceding `cursor_offset`, or `0` if there is none.
///
/// Used as a cache discriminator so that accesses before and after an
/// assert-instanceof in the same flat statement list get separate
/// cache entries.
fn diag_cache_assert_offset(cursor_offset: u32) -> u32 {
    DIAG_SUBJECT_CACHE.with(|cell| {
        let borrow = cell.borrow();
        match borrow.as_ref() {
            Some((_map, file_data)) => {
                match file_data
                    .assert_narrowing_offsets
                    .partition_point(|&o| o < cursor_offset)
                {
                    0 => 0,
                    i => file_data.assert_narrowing_offsets[i - 1],
                }
            }
            None => 0,
        }
    })
}

/// Compute the `var_def_offset` discriminator for a subject at a given
/// cursor offset.
///
/// For variable-based subjects (starting with `$`, excluding `$this`),
/// returns the `effective_from` offset of the most recent variable
/// definition visible at `cursor_offset`.  For non-variable subjects,
/// returns `0`.
///
/// This ensures that the diagnostic subject cache distinguishes
/// accesses to the same variable before and after a reassignment.
fn diag_cache_var_def_offset(subject: &str, cursor_offset: u32) -> u32 {
    if !subject.starts_with('$') || subject.starts_with("$this") {
        return 0;
    }
    // Extract the bare variable name without '$' (e.g. "file" from
    // "$file" or "$file->foo()").
    let after_dollar = &subject[1..];
    let var_name = after_dollar
        .find("->")
        .map(|i| &after_dollar[..i])
        .unwrap_or(after_dollar);

    DIAG_SUBJECT_CACHE.with(|cell| {
        let borrow = cell.borrow();
        match borrow.as_ref() {
            Some((_map, file_data)) => {
                let scope_start = {
                    let mut best: u32 = 0;
                    for &(start, end) in &file_data.scopes {
                        if start <= cursor_offset && cursor_offset <= end && start > best {
                            best = start;
                        }
                    }
                    best
                };
                file_data
                    .var_defs
                    .iter()
                    .rev()
                    .find(|d| {
                        d.name == var_name
                            && d.scope_start == scope_start
                            && d.effective_from <= cursor_offset
                    })
                    .map(|d| d.effective_from)
                    .unwrap_or(0)
            }
            None => 0,
        }
    })
}

/// Resolve a completion subject to all candidate class types.
///
/// Resolve a completion subject to all candidate types, preserving
/// both class info and type strings.
///
/// This is the primary entry point for subject resolution.  It returns
/// `Vec<ResolvedType>` which carries both the structured type string
/// (e.g. `PhpType::Named("Collection")`) and the optional `ClassInfo`.
/// Callers that only need classes can call
/// `ResolvedType::into_arced_classes()` on the result.
///
/// When a [`DiagSubjectCacheGuard`] is active on the current thread,
/// results are cached by `(subject_text, access_kind, scope_start,
/// var_def_offset, narrowing_offset, assert_offset)` so that multiple
/// diagnostic collectors sharing the same file avoid redundant
/// resolution work while keeping different method scopes independent.
pub(crate) fn resolve_target_classes(
    subject: &str,
    access_kind: AccessKind,
    ctx: &ResolutionCtx<'_>,
) -> Vec<ResolvedType> {
    resolve_target_classes_inner(subject, access_kind, ctx, false)
}

/// Resolve a completion subject, optionally skipping the
/// `DIAG_SUBJECT_CACHE` lookup while still populating it.
///
/// When `skip_cache_lookup` is `true`, the cache is not checked but
/// the result IS stored.  This replicates the old
/// `SKIP_DIAG_CACHE_FOR_VARIABLES` behavior: the top-level diagnostic
/// resolver (`resolve_subject_outcome`) resolves bare variables fresh
/// at each cursor position (essential for ternary narrowing), while
/// the cached result remains available for internal chain resolution
/// calls that reference the same variable as a base expression.
fn resolve_target_classes_inner(
    subject: &str,
    access_kind: AccessKind,
    ctx: &ResolutionCtx<'_>,
    skip_cache_lookup: bool,
) -> Vec<ResolvedType> {
    // ── Fast path: check the thread-local diagnostic cache ──────
    let scope_start = diag_cache_enclosing_scope(ctx.cursor_offset);
    let var_def_offset = diag_cache_var_def_offset(subject, ctx.cursor_offset);
    // For variable subjects (excluding $this), use the innermost
    // narrowing block (if/elseif/else body) as a cache discriminator
    // so that accesses inside different instanceof-narrowing contexts
    // get independent cache entries.  Accesses in the same block
    // share a cache entry because they receive identical narrowing.
    let narrowing_offset = if subject.starts_with('$') && !subject.starts_with("$this") {
        diag_cache_narrowing_block(ctx.cursor_offset)
    } else {
        0
    };
    let assert_offset = if subject.starts_with('$') && !subject.starts_with("$this") {
        diag_cache_assert_offset(ctx.cursor_offset)
    } else {
        0
    };
    let cache_key = (
        subject.to_string(),
        access_kind,
        scope_start,
        var_def_offset,
        narrowing_offset,
        assert_offset,
    );

    if !skip_cache_lookup {
        let cached = DIAG_SUBJECT_CACHE.with(|cell| {
            let borrow = cell.borrow();
            borrow
                .as_ref()
                .and_then(|(map, _)| map.get(&cache_key).cloned())
        });
        if let Some(result) = cached {
            return result;
        }
    }

    let expr = SubjectExpr::parse(subject);
    let result = resolve_target_classes_expr(&expr, access_kind, ctx);

    // ── Populate the cache if active ────────────────────────────
    // Skip caching empty results when the variable resolution depth
    // guard has fired.  A depth-limited empty result does not mean
    // the variable is genuinely unresolvable — it only means the
    // recursion was too deep *this time*.  Caching such an empty
    // vec would poison the cache: a later top-level lookup (at
    // depth 0) would hit the cached empty entry and produce a
    // false "type could not be resolved" diagnostic.
    let skip_cache =
        result.is_empty() && super::variable::resolution::is_var_resolution_depth_limited();
    if !skip_cache {
        DIAG_SUBJECT_CACHE.with(|cell| {
            let mut borrow = cell.borrow_mut();
            if let Some((map, _)) = borrow.as_mut() {
                map.insert(cache_key, result.clone());
            }
        });
    }

    result
}

/// Core dispatch for [`resolve_target_classes`], operating on a
/// pre-parsed [`SubjectExpr`].
pub(crate) fn resolve_target_classes_expr(
    expr: &SubjectExpr,
    access_kind: AccessKind,
    ctx: &ResolutionCtx<'_>,
) -> Vec<ResolvedType> {
    let current_class = ctx.current_class;
    let all_classes = ctx.all_classes;
    let class_loader = ctx.class_loader;

    match expr {
        // ── Keywords that always mean "current class" ────────────
        SubjectExpr::This => {
            // Check for `@param-closure-this` override: when the cursor
            // is inside a closure passed as an argument to a function
            // whose parameter carries `@param-closure-this`, resolve
            // `$this` to the declared type instead of the lexical class.
            if let Some(override_cls) =
                super::variable::closure_resolution::find_closure_this_override(ctx)
            {
                return vec![ResolvedType::from_class(override_cls)];
            }
            current_class
                .map(|cc| ResolvedType::from_class(cc.clone()))
                .into_iter()
                .collect()
        }
        SubjectExpr::SelfKw | SubjectExpr::StaticKw => current_class
            .map(|cc| ResolvedType::from_class(cc.clone()))
            .into_iter()
            .collect(),

        // ── `parent::` — resolve to the current class's parent ──
        SubjectExpr::Parent => {
            if let Some(cc) = current_class
                && let Some(ref parent_name) = cc.parent_class
            {
                if let Some(cls) = find_class_by_name(all_classes, parent_name) {
                    return vec![ResolvedType::from_class(cls.as_ref().clone())];
                }
                return class_loader(parent_name)
                    .map(|arc| ResolvedType::from_class(Arc::unwrap_or_clone(arc)))
                    .into_iter()
                    .collect();
            }
            vec![]
        }

        // ── Inline array literal with index access ──────────────
        SubjectExpr::InlineArray { elements, .. } => {
            let mut element_types = Vec::new();
            for elem_text in elements {
                let elem = elem_text.trim();
                if elem.is_empty() {
                    continue;
                }
                let elem_expr = SubjectExpr::parse(elem);
                let resolved = resolve_target_classes_expr(&elem_expr, AccessKind::Arrow, ctx);
                ResolvedType::extend_unique(&mut element_types, resolved);
            }
            element_types
        }

        // ── Enum case / static member access ────────────────────
        SubjectExpr::StaticAccess { class, member } => {
            // Handle self/static/parent keywords — SubjectExpr::parse
            // produces StaticAccess for "self::MONTH", "static::FOO",
            // etc., but "self"/"static"/"parent" are keywords, not
            // class names, so find_class_by_name / class_loader won't
            // find them.
            let owner_classes: Vec<Arc<ClassInfo>> = if is_self_or_static(class) {
                current_class
                    .map(|cc| Arc::new(cc.clone()))
                    .into_iter()
                    .collect()
            } else if let Some(parent_name) = resolve_class_keyword(class, current_class) {
                // parent — resolve via all_classes first, then class_loader
                if let Some(cls) = find_class_by_name(all_classes, &parent_name) {
                    vec![Arc::clone(cls)]
                } else {
                    class_loader(&parent_name).into_iter().collect()
                }
            } else {
                if let Some(cls) = find_class_by_name(all_classes, class) {
                    vec![Arc::clone(cls)]
                } else {
                    class_loader(class).into_iter().collect()
                }
            };

            // When the member is a static property (starts with `$`),
            // resolve to the property's declared type instead of the
            // owning class.  This makes `self::$instance->method()`
            // resolve `method()` on the property's type, not on the
            // class that declares the static property.
            if let Some(prop_name) = member.strip_prefix('$') {
                let mut results: Vec<ResolvedType> = Vec::new();
                for cls in &owner_classes {
                    let resolved = super::type_resolution::resolve_property_types(
                        prop_name,
                        cls,
                        all_classes,
                        class_loader,
                    );
                    ResolvedType::extend_unique(
                        &mut results,
                        resolved.into_iter().map(ResolvedType::from_class).collect(),
                    );
                }
                if !results.is_empty() {
                    return results;
                }
            }

            owner_classes
                .into_iter()
                .map(|arc| ResolvedType::from_class(Arc::unwrap_or_clone(arc)))
                .collect()
        }

        // ── Bare class name ─────────────────────────────────────
        SubjectExpr::ClassName(name) => {
            if let Some(cls) = find_class_by_name(all_classes, name) {
                return vec![ResolvedType::from_class(cls.as_ref().clone())];
            }
            class_loader(name)
                .map(|arc| ResolvedType::from_class(Arc::unwrap_or_clone(arc)))
                .into_iter()
                .collect()
        }

        // ── `new ClassName` (without trailing call parens) ───────
        SubjectExpr::NewExpr { class_name } => {
            if let Some(cls) = find_class_by_name(all_classes, class_name) {
                return vec![ResolvedType::from_class(cls.as_ref().clone())];
            }
            class_loader(class_name)
                .map(|arc| ResolvedType::from_class(Arc::unwrap_or_clone(arc)))
                .into_iter()
                .collect()
        }

        // ── Call expression ─────────────────────────────────────
        SubjectExpr::CallExpr { callee, args_text } => {
            let classes = Backend::resolve_call_return_types_expr(callee, args_text, ctx);
            classes
                .into_iter()
                .map(|arc| ResolvedType::from_class(Arc::unwrap_or_clone(arc)))
                .collect()
        }

        // ── Property chain ──────────────────────────────────────
        SubjectExpr::PropertyChain { base, property } => {
            let base_arcs = resolved_to_arcs(resolve_target_classes_expr(base, access_kind, ctx));
            let mut arc_results: Vec<Arc<ClassInfo>> = Vec::new();
            for cls in &base_arcs {
                let resolved = super::type_resolution::resolve_property_types(
                    property,
                    cls,
                    all_classes,
                    class_loader,
                );
                ClassInfo::extend_unique_arc(
                    &mut arc_results,
                    resolved.into_iter().map(Arc::new).collect(),
                );
            }

            // ── Property-level narrowing ────────────────────────
            // When the property chain resolves to a union (or a
            // broad interface type), an enclosing `instanceof`
            // check like `if ($this->prop instanceof Foo)` should
            // narrow the result set, just as it does for plain
            // variables.  Build the full access path (e.g.
            // `$this->timeline`) and run the narrowing walk.
            //
            // This also handles untyped properties: when the
            // property has no type hint, `results` is empty but
            // an `instanceof` check or `assert()` can still
            // provide a type via `apply_instanceof_inclusion`.
            //
            // Use a dummy class when outside a class body so that
            // property narrowing works in standalone functions and
            // top-level code (e.g. `$arg->value instanceof Foo`
            // inside a foreach).
            {
                let dummy_class;
                let effective_class = match current_class {
                    Some(cc) => cc,
                    None => {
                        dummy_class = ClassInfo::default();
                        &dummy_class
                    }
                };
                let full_path = format!("{}->{}", base.to_subject_text(), property);
                apply_property_narrowing(&full_path, effective_class, ctx, &mut arc_results);
            }

            arc_results
                .into_iter()
                .map(|arc| ResolvedType::from_class(Arc::unwrap_or_clone(arc)))
                .collect()
        }

        // ── Array access on variable or call expression ─────────
        SubjectExpr::ArrayAccess { base, segments } => {
            // When the base is a call expression (e.g. `$c->items()[0]`),
            // resolve the call's raw return type and use it as a candidate
            // for array-segment walking.  This mirrors the variable path
            // but sources the raw type from the method/function signature
            // instead of from docblock annotations or assignments.
            if let SubjectExpr::CallExpr { callee, args_text } = base.as_ref() {
                let call_raw = resolve_call_raw_return_type(callee, args_text, ctx);
                if let Some(raw) = call_raw {
                    let candidates = std::iter::once(raw);
                    if let Some(resolved) =
                        super::source::helpers::try_chained_array_access_with_candidates(
                            candidates,
                            segments,
                            current_class,
                            all_classes,
                            class_loader,
                        )
                    {
                        return resolved.into_iter().map(ResolvedType::from_class).collect();
                    }
                }
                // If raw-type approach didn't work, fall back to resolving
                // the call normally (handles cases like `getItems()[0]`
                // where the return type is already a class with ArrayAccess).
                return vec![];
            }

            let base_var = base.to_subject_text();

            // Build candidate raw types from multiple strategies.
            // Each is tried as a complete pipeline (raw type →
            // segment walk → ClassInfo); the first that succeeds
            // through all segments wins.

            // ── Property chain raw type ─────────────────────────
            // When the base is a property chain (e.g. `$this->cache`,
            // `$obj->items`), resolve the owning class and extract
            // the property's raw type hint.  This preserves generic
            // parameters like `array<string, IntCollection>` or
            // `Collection<int, Translation>` that would be lost if
            // we resolved through `type_hint_to_classes_typed` first.
            let property_raw_type: Option<PhpType> = if let SubjectExpr::PropertyChain {
                base: prop_base,
                property,
            } = base.as_ref()
            {
                let owner_arcs =
                    resolved_to_arcs(resolve_target_classes_expr(prop_base, access_kind, ctx));
                owner_arcs.iter().find_map(|cls| {
                    crate::inheritance::resolve_property_type_hint(cls, property, class_loader)
                })
            } else {
                None
            };

            let docblock_type: Option<PhpType> = docblock::find_iterable_raw_type_in_source(
                ctx.content,
                ctx.cursor_offset as usize,
                &base_var,
            );
            let ast_type: Option<PhpType> = {
                let dummy_class;
                let effective_class = match current_class {
                    Some(cc) => cc,
                    None => {
                        dummy_class = ClassInfo::default();
                        &dummy_class
                    }
                };
                let resolved = crate::completion::variable::resolution::resolve_variable_types(
                    &base_var,
                    effective_class,
                    all_classes,
                    ctx.content,
                    ctx.cursor_offset,
                    class_loader,
                    Loaders::with_function(ctx.function_loader),
                );
                if resolved.is_empty() {
                    None
                } else {
                    Some(ResolvedType::types_joined(&resolved))
                }
            };

            let candidates = property_raw_type
                .into_iter()
                .chain(docblock_type)
                .chain(ast_type);

            if let Some(resolved) = super::source::helpers::try_chained_array_access_with_candidates(
                candidates,
                segments,
                current_class,
                all_classes,
                class_loader,
            ) {
                return resolved.into_iter().map(ResolvedType::from_class).collect();
            }
            // Segment walk failed — the base type does not have
            // array-shape, generic, or iterable annotations that
            // cover bracket access.  Return empty: `$var['key']` is
            // never the same type as `$var`.
            vec![]
        }

        // ── Bare variable ───────────────────────────────────────
        SubjectExpr::Variable(var_name) => resolve_variable_fallback(var_name, access_kind, ctx),

        // ── Callee-only variants (MethodCall, StaticMethodCall,
        //    FunctionCall) should not appear as top-level subjects;
        //    they are wrapped in CallExpr.  If they do appear
        //    (e.g. from a partial parse), treat as class name. ────
        SubjectExpr::MethodCall { .. }
        | SubjectExpr::StaticMethodCall { .. }
        | SubjectExpr::FunctionCall(_) => {
            let text = expr.to_subject_text();
            if let Some(cls) = find_class_by_name(all_classes, &text) {
                return vec![ResolvedType::from_class(cls.as_ref().clone())];
            }
            class_loader(&text)
                .map(|arc| ResolvedType::from_class(Arc::unwrap_or_clone(arc)))
                .into_iter()
                .collect()
        }
    }
}

/// Extract the raw return type string from a call expression's callee.
///
/// Given a `CallExpr`'s callee and arguments, resolves the owning class
/// (for method/static-method calls) or the function info (for standalone
/// functions), finds the matching method/function, and returns its raw
/// return type string (e.g. `"Item[]"`).  This is used by the
/// `ArrayAccess` handler to strip array dimensions and resolve the
/// element type when the base of `[0]` is a call expression.
fn resolve_call_raw_return_type(
    callee: &SubjectExpr,
    _args_text: &str,
    ctx: &ResolutionCtx<'_>,
) -> Option<PhpType> {
    match callee {
        SubjectExpr::MethodCall { base, method } => {
            let base_classes =
                resolved_to_arcs(resolve_target_classes_expr(base, AccessKind::Arrow, ctx));
            for cls in &base_classes {
                // Use a fully-resolved class so that inherited docblock
                // return types (e.g. `list<Pen>` from an interface or
                // parent) are visible instead of the bare native hint.
                let merged = crate::virtual_members::resolve_class_fully_maybe_cached(
                    cls,
                    ctx.class_loader,
                    ctx.resolved_class_cache,
                );
                let found = merged
                    .methods
                    .iter()
                    .find(|m| m.name.eq_ignore_ascii_case(method));
                if let Some(m) = found {
                    if let Some(ref ret) = m.return_type {
                        return Some(ret.clone());
                    }
                    // Method exists but has no return type.
                    // Only fall through to __call for virtual methods
                    // (from @method tags or @mixin). Real methods are
                    // invoked directly at runtime, not through __call.
                    if !m.is_virtual {
                        continue;
                    }
                }
                // __call fallback: method not found, or virtual method
                // without a return type.  Use __call's return type so
                // that chains through dynamic calls (e.g. Builder
                // where{Column}) preserve the type.
                if let Some(m) = merged
                    .methods
                    .iter()
                    .find(|m| m.name.eq_ignore_ascii_case("__call"))
                    && let Some(ref ret) = m.return_type
                {
                    return Some(ret.clone());
                }
            }
            None
        }
        SubjectExpr::StaticMethodCall { class, method } => {
            let owner = resolve_static_owner_class(class, ctx);
            if let Some(ref cls) = owner {
                let merged = crate::virtual_members::resolve_class_fully_maybe_cached(
                    cls,
                    ctx.class_loader,
                    ctx.resolved_class_cache,
                );
                let found = merged
                    .methods
                    .iter()
                    .find(|m| m.name.eq_ignore_ascii_case(method));
                if let Some(m) = found {
                    if let Some(ref ret) = m.return_type {
                        return Some(ret.clone());
                    }
                    // Method exists but has no return type.
                    // Only fall through to __callStatic for virtual methods.
                    if !m.is_virtual {
                        return None;
                    }
                }
                // __callStatic fallback: method not found, or virtual
                // method without a return type.
                if let Some(m) = merged
                    .methods
                    .iter()
                    .find(|m| m.name.eq_ignore_ascii_case("__callStatic"))
                    && let Some(ref ret) = m.return_type
                {
                    return Some(ret.clone());
                }
            }
            None
        }
        SubjectExpr::FunctionCall(fn_name) => {
            if let Some(fl) = ctx.function_loader
                && let Some(func_info) = fl(fn_name)
            {
                return func_info.return_type.clone();
            }
            None
        }
        _ => None,
    }
}

// ─── Enriched subject resolution for diagnostics ────────────────────────────

/// The outcome of resolving a subject for diagnostic purposes.
///
/// [`resolve_target_classes`] only returns `Vec<Arc<ClassInfo>>` and
/// silently drops scalar types and type-string-only entries.
/// Diagnostics need to know *why* resolution returned empty — was the
/// subject a scalar type (runtime crash), an unresolvable class name
/// (likely typo / missing import), or truly untyped?  This enum
/// carries that distinction so the diagnostic collector can emit the
/// right message and severity.
///
/// ## Architectural invariant
///
/// Every `SubjectOutcome` **must** be derived from the same resolution
/// pass that completion and hover use.  Re-resolving a variable
/// through a secondary helper (e.g. `resolve_variable_type`)
/// bypasses narrowing (instanceof, assert, ternary, `&&`) and
/// produces false positives.  See [`resolve_subject_outcome`] for
/// how this is enforced for each subject variant.
#[derive(Clone, Debug)]
pub(crate) enum SubjectOutcome {
    /// Subject resolved to one or more classes.
    Resolved(Vec<Arc<ClassInfo>>),
    /// Subject resolved to a scalar type — member access is always a
    /// runtime crash.  The `PhpType` is the resolved scalar type
    /// (e.g. `int`, `string`, `bool|int`) with null stripped.
    Scalar(PhpType),
    /// Subject resolved to a class name that couldn't be loaded.
    UnresolvableClass(String),
    /// Subject type could not be resolved — no class information
    /// available.
    Untyped,
}

/// Resolve a subject to a [`SubjectOutcome`] in a single pass.
///
/// This is the unified entry point for diagnostic subject resolution.
/// It resolves the subject to `Vec<ResolvedType>` (the same pipeline
/// used by completion and hover) and classifies the result:
///
///   - If any entry has `class_info`, return `Resolved`.
///   - If all entries are primitive scalars, return `Scalar`.
///   - If a type string refers to an unloadable class, return
///     `UnresolvableClass`.
///   - If the result is empty, return `Untyped`.
///
/// For bare variable subjects, the `DIAG_SUBJECT_CACHE` lookup is
/// skipped (but the result is still stored) so that
/// `resolve_variable_types` runs fresh at `ctx.cursor_offset`.
/// This is essential for expression-level narrowing: inside a
/// ternary like `$x instanceof Foo ? $x->bar() : …`, the same
/// variable `$x` must resolve differently at the `bar()` cursor
/// position (narrowed) vs a prior access outside the ternary
/// (un-narrowed).  The `DIAG_SUBJECT_CACHE` key doesn't
/// distinguish these positions (and shouldn't — internal chain
/// resolution calls reuse the outer cursor offset, and must share
/// cache entries).  The per-access discrimination is handled by
/// `SubjectCacheKey.access_offset` in `unknown_members.rs`, which
/// ensures each member-access span gets its own `SubjectOutcome`.
///
/// The result is still cached so that subsequent internal calls
/// (e.g. chain resolution that references the same variable as a
/// base expression) benefit from the cache.
pub(crate) fn resolve_subject_outcome(
    subject: &str,
    access_kind: AccessKind,
    ctx: &ResolutionCtx<'_>,
) -> SubjectOutcome {
    let expr = SubjectExpr::parse(subject);

    // For bare variable subjects, skip the DIAG_SUBJECT_CACHE lookup
    // so that resolve_variable_types runs fresh at ctx.cursor_offset.
    // The result is still stored in the cache so that internal chain
    // resolution calls (resolve_call_return_types_expr etc.) that
    // reference the same variable as a base expression benefit from
    // the cache.
    let skip_cache = matches!(expr, SubjectExpr::Variable(_));
    let resolved = resolve_target_classes_inner(subject, access_kind, ctx, skip_cache);

    if !resolved.is_empty() {
        // ── Check for class-bearing entries ──────────────────────
        let arced: Vec<Arc<ClassInfo>> = ResolvedType::into_arced_classes(resolved.clone());
        if !arced.is_empty() {
            return SubjectOutcome::Resolved(arced);
        }

        // ── All entries are type-string-only (no class info) ────
        let joined = ResolvedType::types_joined(&resolved);

        // Pure scalar — member access is a runtime crash.
        if joined.all_members_primitive_scalar() {
            let scalar = joined.non_null_type().unwrap_or(joined);
            return SubjectOutcome::Scalar(scalar);
        }

        // stdClass / object — synthetic resolution.
        if resolved
            .iter()
            .any(|rt| rt.type_string.is_named_ci("stdclass") || rt.type_string.is_object())
        {
            let synthetic = Arc::new(ClassInfo {
                name: "stdClass".to_string(),
                ..ClassInfo::default()
            });
            return SubjectOutcome::Resolved(vec![synthetic]);
        }

        // Non-scalar, non-class type — check for unresolvable class.
        if let Some(unresolved) = check_unresolvable_class_name(&joined, ctx.class_loader) {
            return SubjectOutcome::UnresolvableClass(unresolved);
        }
        return SubjectOutcome::Untyped;
    }

    // ── Result is empty — classify why ──────────────────────────
    // `expr` was already parsed above for the bare-variable check.

    // For call expressions, check the raw return type hint.
    if let SubjectExpr::CallExpr {
        callee,
        args_text: _,
    } = &expr
    {
        if let Some(scalar) = resolve_call_scalar_return(callee, access_kind, ctx) {
            return SubjectOutcome::Scalar(scalar);
        }
        // Try unresolvable class detection for function calls.
        if let SubjectExpr::FunctionCall(fn_name) = callee.as_ref()
            && let Some(fl) = ctx.function_loader
            && let Some(func_info) = fl(fn_name.as_str())
            && let Some(ref raw_type) = func_info.return_type
            && let Some(unresolved) = check_unresolvable_class_name(raw_type, ctx.class_loader)
        {
            return SubjectOutcome::UnresolvableClass(unresolved);
        }
    }

    // For property chains, check the property's type hint.
    if let SubjectExpr::PropertyChain { base, property } = &expr {
        let base_arcs = resolved_to_arcs(resolve_target_classes_expr(base, access_kind, ctx));
        for cls in &base_arcs {
            let merged =
                resolve_class_fully_maybe_cached(cls, ctx.class_loader, ctx.resolved_class_cache);
            if let Some(parsed) = resolve_property_type_hint(&merged, property, ctx.class_loader) {
                if parsed.all_members_primitive_scalar() {
                    let scalar = parsed.non_null_type().unwrap_or(parsed);
                    return SubjectOutcome::Scalar(scalar);
                }
                return SubjectOutcome::Untyped;
            }
        }
    }

    // For bare variables, try the hover fallback for UnresolvableClass
    // detection only.
    if let SubjectExpr::Variable(var_name) = &expr
        && let Some(resolved_type) = crate::hover::variable_type::resolve_variable_type(
            var_name,
            ctx.content,
            ctx.cursor_offset,
            ctx.current_class,
            ctx.all_classes,
            ctx.class_loader,
            Loaders::with_function(ctx.function_loader),
        )
        && let Some(unresolved) = check_unresolvable_class_name(&resolved_type, ctx.class_loader)
    {
        return SubjectOutcome::UnresolvableClass(unresolved);
    }

    SubjectOutcome::Untyped
}

/// Check whether a call expression's return type is a scalar.
///
/// Inspects the raw return type hint on the method or function without
/// going through the full class resolution pipeline.
fn resolve_call_scalar_return(
    callee: &SubjectExpr,
    access_kind: AccessKind,
    ctx: &ResolutionCtx<'_>,
) -> Option<PhpType> {
    match callee {
        // Instance method call: $obj->getAge()
        SubjectExpr::MethodCall { base, method } => {
            let base_arcs = resolved_to_arcs(resolve_target_classes_expr(base, access_kind, ctx));
            for cls in &base_arcs {
                let resolved = resolve_class_fully_maybe_cached(
                    cls,
                    ctx.class_loader,
                    ctx.resolved_class_cache,
                );
                if let Some(m) = resolved
                    .methods
                    .iter()
                    .find(|m| m.name.eq_ignore_ascii_case(method))
                    && let Some(ref hint) = m.return_type
                    && hint.all_members_primitive_scalar()
                {
                    let scalar = hint.non_null_type().unwrap_or_else(|| hint.clone());
                    return Some(scalar);
                }
            }
            None
        }
        // Standalone function call: getInt()
        SubjectExpr::FunctionCall(fn_name) => {
            if let Some(fl) = ctx.function_loader
                && let Some(func_info) = fl(fn_name)
                && let Some(ref hint) = func_info.return_type
                && hint.all_members_primitive_scalar()
            {
                let scalar = hint.non_null_type().unwrap_or_else(|| hint.clone());
                return Some(scalar);
            }
            None
        }
        // Static method call: Foo::getInt()
        SubjectExpr::StaticMethodCall { class, method } => {
            let cls = (ctx.class_loader)(class);
            if let Some(cls) = cls {
                let resolved = resolve_class_fully_maybe_cached(
                    &cls,
                    ctx.class_loader,
                    ctx.resolved_class_cache,
                );
                if let Some(m) = resolved
                    .methods
                    .iter()
                    .find(|m| m.name.eq_ignore_ascii_case(method))
                    && let Some(ref hint) = m.return_type
                    && hint.all_members_primitive_scalar()
                {
                    let scalar = hint.non_null_type().unwrap_or_else(|| hint.clone());
                    return Some(scalar);
                }
            }
            None
        }
        _ => None,
    }
}

/// Check whether a raw type string refers to a class that cannot be
/// loaded.
///
/// Returns `Some(class_name)` when the type looks like a class name
/// (not scalar, not a PHPDoc pseudo-type) but the class loader cannot
/// find it.  Returns `None` for scalars, unions, shapes, and types
/// that resolve successfully.
fn check_unresolvable_class_name(
    raw_type: &PhpType,
    class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> Option<String> {
    if raw_type.all_members_scalar() {
        return None;
    }

    let effective = raw_type.non_null_type().unwrap_or_else(|| raw_type.clone());
    let base = effective.base_name()?;

    if class_loader(base).is_none() {
        Some(base.to_string())
    } else {
        None
    }
}

/// Shared variable-resolution logic extracted from the former
/// bare-`$var` branch of `resolve_target_classes`.
///
/// Resolves a variable to its classes by running the full variable
/// resolution pipeline (including narrowing from instanceof, assert,
/// ternary, and `&&` chains) and converting the result to
/// `Vec<Arc<ClassInfo>>` (dropping type-string-only entries).
fn resolve_variable_fallback(
    var_name: &str,
    access_kind: AccessKind,
    ctx: &ResolutionCtx<'_>,
) -> Vec<ResolvedType> {
    let current_class = ctx.current_class;
    let all_classes = ctx.all_classes;
    let class_loader = ctx.class_loader;
    let function_loader = ctx.function_loader;

    let dummy_class;
    let effective_class = match current_class {
        Some(cc) => cc,
        None => {
            dummy_class = ClassInfo::default();
            &dummy_class
        }
    };

    // ── `$var::` where `$var` holds a class-string ──
    if access_kind == AccessKind::DoubleColon {
        let class_string_targets =
            crate::completion::variable::class_string_resolution::resolve_class_string_targets(
                var_name,
                effective_class,
                all_classes,
                ctx.content,
                ctx.cursor_offset,
                class_loader,
            );
        if !class_string_targets.is_empty() {
            return class_string_targets
                .into_iter()
                .map(ResolvedType::from_class)
                .collect();
        }
    }

    let resolved_types = super::variable::resolution::resolve_variable_types(
        var_name,
        effective_class,
        all_classes,
        ctx.content,
        ctx.cursor_offset,
        class_loader,
        Loaders::with_function(function_loader),
    );

    // ── `class-string<T>` unwrapping for `$var::` access ────────
    // When the variable's type is `class-string<T>` (e.g. from a
    // `@param class-string<BackedEnum> $class` annotation) and the
    // access kind is `::`, unwrap the inner type `T` and resolve it
    // to classes so that static members are offered against `T`.
    if access_kind == AccessKind::DoubleColon {
        let mut class_string_results: Vec<ResolvedType> = Vec::new();
        for rt in &resolved_types {
            let inner = match &rt.type_string {
                PhpType::ClassString(Some(inner)) => Some(inner.as_ref()),
                // Handle `?class-string<T>` — unwrap nullable first.
                PhpType::Nullable(inner) => match inner.as_ref() {
                    PhpType::ClassString(Some(cs_inner)) => Some(cs_inner.as_ref()),
                    _ => None,
                },
                // Handle union types containing class-string<T>.
                PhpType::Union(members) => {
                    for member in members {
                        let cs_inner = match member {
                            PhpType::ClassString(Some(inner)) => Some(inner.as_ref()),
                            PhpType::Nullable(inner) => match inner.as_ref() {
                                PhpType::ClassString(Some(cs_inner)) => Some(cs_inner.as_ref()),
                                _ => None,
                            },
                            _ => None,
                        };
                        if let Some(inner_ty) = cs_inner {
                            let resolved = super::type_resolution::type_hint_to_classes_typed(
                                inner_ty,
                                &effective_class.name,
                                all_classes,
                                class_loader,
                            );
                            for cls in resolved {
                                ResolvedType::push_unique(
                                    &mut class_string_results,
                                    ResolvedType::from_class(cls),
                                );
                            }
                        }
                    }
                    None // already handled inline
                }
                _ => None,
            };
            if let Some(inner_ty) = inner {
                let resolved = super::type_resolution::type_hint_to_classes_typed(
                    inner_ty,
                    &effective_class.name,
                    all_classes,
                    class_loader,
                );
                for cls in resolved {
                    ResolvedType::push_unique(
                        &mut class_string_results,
                        ResolvedType::from_class(cls),
                    );
                }
            }
        }
        if !class_string_results.is_empty() {
            return class_string_results;
        }
    }

    resolved_types
}

// ── Static owner class resolution ───────────────────────────────────

/// Resolve a static class reference (`self`, `static`, `parent`, or a
/// class name) to its `ClassInfo`.
///
/// Handles the `self`/`static`/`parent` keywords and falls back to
/// `class_loader` then `resolve_target_classes` for named classes.
pub(in crate::completion) fn resolve_static_owner_class(
    class: &str,
    rctx: &ResolutionCtx<'_>,
) -> Option<Arc<ClassInfo>> {
    if is_self_or_static(class) {
        rctx.current_class.map(|cc| Arc::new(cc.clone()))
    } else if let Some(resolved_name) = resolve_class_keyword(class, rctx.current_class) {
        // parent — load via class_loader so we get the full parent ClassInfo
        (rctx.class_loader)(&resolved_name)
    } else {
        find_class_by_name(rctx.all_classes, class)
            .map(Arc::clone)
            .or_else(|| (rctx.class_loader)(class))
            .or_else(|| {
                resolved_to_arcs(resolve_target_classes(
                    class,
                    crate::AccessKind::DoubleColon,
                    rctx,
                ))
                .into_iter()
                .next()
            })
    }
}

/// Apply instanceof / assert narrowing for a property-access path.
///
/// This is the property-level analog of the narrowing that
/// [`super::variable::resolution::walk_statements_for_assignments`]
/// performs for plain variables.  It re-parses the source, locates
/// the enclosing method body, and walks its statements with a
/// [`VarResolutionCtx`] whose `var_name` is the full property path
/// (e.g. `$this->timeline`).  The existing narrowing functions in
/// [`super::types::narrowing`] already support property paths via
/// [`super::types::narrowing::expr_to_subject_key`], so no changes
/// to those functions are required.
fn apply_property_narrowing(
    property_path: &str,
    current_class: &ClassInfo,
    rctx: &ResolutionCtx<'_>,
    results: &mut Vec<Arc<ClassInfo>>, // still operates on Arc<ClassInfo> — called from property chain
) {
    use crate::parser::with_parsed_program;

    // The narrowing walk functions operate on Vec<ClassInfo>, so unwrap
    // the Arcs, run narrowing, then re-wrap.
    let mut plain: Vec<ClassInfo> = results.drain(..).map(Arc::unwrap_or_clone).collect();

    with_parsed_program(
        rctx.content,
        "apply_property_narrowing",
        |program, _content| {
            let ctx = VarResolutionCtx {
                var_name: property_path,
                current_class,
                all_classes: rctx.all_classes,
                content: rctx.content,
                cursor_offset: rctx.cursor_offset,
                class_loader: rctx.class_loader,
                loaders: Loaders::with_function(rctx.function_loader),
                resolved_class_cache: None,
                enclosing_return_type: None,
                branch_aware: false,
            };
            walk_property_narrowing_in_statements(program.statements.iter(), &ctx, &mut plain);
        },
    );

    *results = plain.into_iter().map(Arc::new).collect();
}

/// Walk top-level statements to find the class + method containing the
/// cursor, then apply narrowing to `results` for the given property path.
fn walk_property_narrowing_in_statements<'b>(
    statements: impl Iterator<Item = &'b mago_syntax::ast::Statement<'b>>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ClassInfo>,
) {
    use mago_span::HasSpan;
    use mago_syntax::ast::*;

    for stmt in statements {
        match stmt {
            Statement::Class(class) => {
                let start = class.left_brace.start.offset;
                let end = class.right_brace.end.offset;
                if ctx.cursor_offset >= start && ctx.cursor_offset <= end {
                    walk_property_narrowing_in_members(class.members.iter(), ctx, results);
                    return;
                }
            }
            Statement::Trait(trait_def) => {
                let start = trait_def.left_brace.start.offset;
                let end = trait_def.right_brace.end.offset;
                if ctx.cursor_offset >= start && ctx.cursor_offset <= end {
                    walk_property_narrowing_in_members(trait_def.members.iter(), ctx, results);
                    return;
                }
            }
            Statement::Namespace(ns) => {
                let ns_span = ns.span();
                if ctx.cursor_offset >= ns_span.start.offset
                    && ctx.cursor_offset <= ns_span.end.offset
                {
                    walk_property_narrowing_in_statements(ns.statements().iter(), ctx, results);
                    return;
                }
            }
            Statement::Function(func) => {
                let body_start = func.body.left_brace.start.offset;
                let body_end = func.body.right_brace.end.offset;
                if ctx.cursor_offset >= body_start && ctx.cursor_offset <= body_end {
                    walk_property_narrowing_stmts(func.body.statements.iter(), ctx, results);
                    return;
                }
            }
            // ── Functions inside if-guards / blocks ──
            // The common PHP pattern `if (! function_exists('foo'))
            // { function foo(…) { … } }` nests the function
            // declaration inside an if body.  Recurse into blocks
            // and if-bodies so property narrowing still works.
            Statement::If(if_stmt) => {
                let if_span = stmt.span();
                if ctx.cursor_offset >= if_span.start.offset
                    && ctx.cursor_offset <= if_span.end.offset
                {
                    for inner in if_stmt.body.statements().iter() {
                        walk_property_narrowing_in_statements(std::iter::once(inner), ctx, results);
                    }
                }
            }
            Statement::Block(block) => {
                let blk_span = stmt.span();
                if ctx.cursor_offset >= blk_span.start.offset
                    && ctx.cursor_offset <= blk_span.end.offset
                {
                    walk_property_narrowing_in_statements(block.statements.iter(), ctx, results);
                }
            }
            _ => {}
        }
    }
}

/// Walk class members to find the method containing the cursor, then
/// apply instanceof / guard-clause narrowing for the property path.
fn walk_property_narrowing_in_members<'b>(
    members: impl Iterator<Item = &'b mago_syntax::ast::class_like::member::ClassLikeMember<'b>>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ClassInfo>,
) {
    use mago_syntax::ast::class_like::member::ClassLikeMember;
    use mago_syntax::ast::class_like::method::MethodBody;

    for member in members {
        if let ClassLikeMember::Method(method) = member {
            let body = match &method.body {
                MethodBody::Concrete(block) => block,
                _ => continue,
            };
            let body_start = body.left_brace.start.offset;
            let body_end = body.right_brace.end.offset;
            if ctx.cursor_offset >= body_start && ctx.cursor_offset <= body_end {
                walk_property_narrowing_stmts(body.statements.iter(), ctx, results);
                return;
            }
        }
    }
}

/// Walk statements applying only narrowing (no assignment scanning)
/// for a property path like `$this->prop`.
fn walk_property_narrowing_stmts<'b>(
    statements: impl Iterator<Item = &'b mago_syntax::ast::Statement<'b>>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ClassInfo>,
) {
    use mago_span::HasSpan;
    use mago_syntax::ast::*;

    use super::types::narrowing;

    for stmt in statements {
        let stmt_span = stmt.span();
        // Only consider statements whose start is before the cursor.
        if stmt_span.start.offset >= ctx.cursor_offset {
            continue;
        }

        match stmt {
            Statement::If(if_stmt) => {
                walk_property_narrowing_if(if_stmt, stmt, ctx, results);
            }
            Statement::Block(block) => {
                walk_property_narrowing_stmts(block.statements.iter(), ctx, results);
            }
            Statement::Expression(expr_stmt) => {
                // assert($this->prop instanceof Foo) — unconditional
                narrowing::try_apply_assert_instanceof_narrowing(
                    expr_stmt.expression,
                    ctx,
                    results,
                );
            }
            Statement::Foreach(foreach) => match &foreach.body {
                ForeachBody::Statement(inner) => {
                    walk_property_narrowing_stmt(inner, ctx, results);
                }
                ForeachBody::ColonDelimited(body) => {
                    walk_property_narrowing_stmts(body.statements.iter(), ctx, results);
                }
            },
            Statement::While(while_stmt) => match &while_stmt.body {
                WhileBody::Statement(inner) => {
                    walk_property_narrowing_stmt(inner, ctx, results);
                }
                WhileBody::ColonDelimited(body) => {
                    walk_property_narrowing_stmts(body.statements.iter(), ctx, results);
                }
            },
            Statement::For(for_stmt) => match &for_stmt.body {
                ForBody::Statement(inner) => {
                    walk_property_narrowing_stmt(inner, ctx, results);
                }
                ForBody::ColonDelimited(body) => {
                    walk_property_narrowing_stmts(body.statements.iter(), ctx, results);
                }
            },
            Statement::DoWhile(dw) => {
                walk_property_narrowing_stmt(dw.statement, ctx, results);
            }
            Statement::Try(try_stmt) => {
                walk_property_narrowing_stmts(try_stmt.block.statements.iter(), ctx, results);
                for catch in try_stmt.catch_clauses.iter() {
                    walk_property_narrowing_stmts(catch.block.statements.iter(), ctx, results);
                }
                if let Some(finally) = &try_stmt.finally_clause {
                    walk_property_narrowing_stmts(finally.block.statements.iter(), ctx, results);
                }
            }
            Statement::Switch(switch) => {
                for case in switch.body.cases().iter() {
                    walk_property_narrowing_stmts(case.statements().iter(), ctx, results);
                }
            }
            _ => {}
        }
    }
}

/// Apply property-level narrowing inside an if / elseif / else chain.
fn walk_property_narrowing_if<'b>(
    if_stmt: &'b mago_syntax::ast::If<'b>,
    enclosing_stmt: &'b mago_syntax::ast::Statement<'b>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ClassInfo>,
) {
    use mago_span::HasSpan;
    use mago_syntax::ast::*;

    use super::types::narrowing;

    match &if_stmt.body {
        IfBody::Statement(body) => {
            // ── then-body narrowing ──
            narrowing::try_apply_instanceof_narrowing(
                if_stmt.condition,
                body.statement.span(),
                ctx,
                results,
            );
            walk_property_narrowing_stmt(body.statement, ctx, results);

            // ── elseif narrowing ──
            for else_if in body.else_if_clauses.iter() {
                narrowing::try_apply_instanceof_narrowing(
                    else_if.condition,
                    else_if.statement.span(),
                    ctx,
                    results,
                );
                walk_property_narrowing_stmt(else_if.statement, ctx, results);
            }

            // ── else-body inverse narrowing ──
            if let Some(else_clause) = &body.else_clause {
                let else_span = else_clause.statement.span();
                narrowing::try_apply_instanceof_narrowing_inverse(
                    if_stmt.condition,
                    else_span,
                    ctx,
                    results,
                );
                for else_if in body.else_if_clauses.iter() {
                    narrowing::try_apply_instanceof_narrowing_inverse(
                        else_if.condition,
                        else_span,
                        ctx,
                        results,
                    );
                }
                walk_property_narrowing_stmt(else_clause.statement, ctx, results);
            }
        }
        IfBody::ColonDelimited(body) => {
            let then_end = if !body.else_if_clauses.is_empty() {
                body.else_if_clauses
                    .first()
                    .unwrap()
                    .elseif
                    .span()
                    .start
                    .offset
            } else if let Some(ref ec) = body.else_clause {
                ec.r#else.span().start.offset
            } else {
                body.endif.span().start.offset
            };
            let then_span = mago_span::Span::new(
                body.colon.file_id,
                body.colon.start,
                mago_span::Position::new(then_end),
            );
            narrowing::try_apply_instanceof_narrowing(if_stmt.condition, then_span, ctx, results);
            walk_property_narrowing_stmts(body.statements.iter(), ctx, results);

            for else_if in body.else_if_clauses.iter() {
                let ei_span = mago_span::Span::new(
                    else_if.colon.file_id,
                    else_if.colon.start,
                    mago_span::Position::new(
                        else_if
                            .statements
                            .span(else_if.colon.file_id, else_if.colon.end)
                            .end
                            .offset,
                    ),
                );
                narrowing::try_apply_instanceof_narrowing(else_if.condition, ei_span, ctx, results);
                walk_property_narrowing_stmts(else_if.statements.iter(), ctx, results);
            }

            if let Some(else_clause) = &body.else_clause {
                let else_span = mago_span::Span::new(
                    else_clause.colon.file_id,
                    else_clause.colon.start,
                    mago_span::Position::new(
                        else_clause
                            .statements
                            .span(else_clause.colon.file_id, else_clause.colon.end)
                            .end
                            .offset,
                    ),
                );
                narrowing::try_apply_instanceof_narrowing_inverse(
                    if_stmt.condition,
                    else_span,
                    ctx,
                    results,
                );
                for else_if in body.else_if_clauses.iter() {
                    narrowing::try_apply_instanceof_narrowing_inverse(
                        else_if.condition,
                        else_span,
                        ctx,
                        results,
                    );
                }
                walk_property_narrowing_stmts(else_clause.statements.iter(), ctx, results);
            }
        }
    }

    // ── Guard clause narrowing ──
    // When the then-body unconditionally exits and there are no
    // elseif / else branches, apply inverse narrowing after the if.
    if enclosing_stmt.span().end.offset < ctx.cursor_offset {
        narrowing::apply_guard_clause_narrowing(if_stmt, ctx, results);
    }
}

/// Dispatch a single statement to `walk_property_narrowing_stmts`.
fn walk_property_narrowing_stmt<'b>(
    stmt: &'b mago_syntax::ast::Statement<'b>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ClassInfo>,
) {
    walk_property_narrowing_stmts(std::iter::once(stmt), ctx, results);
}