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
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
use super::helpers::extract_string_from_expr;
use super::{root_receiver_var, ExpressionAnalyzer};
use crate::flow_state::FlowState;
use crate::symbol::ReferenceKind;
use mir_issues::{IssueKind, Severity};
use mir_types::{Atomic, Name, Type};
use php_ast::owned::{Expr, ExprKind, NewExpr, PropertyAccessExpr, StaticAccessExpr};
use std::sync::Arc;
/// Widen scalar literal atomics to their base type when forming a `new`
/// receiver's generic `type_params`. Carrying a literal type param into the
/// receiver (e.g. `Box<5>` from `new Box(5)`) is over-narrow and risks false
/// positives downstream (e.g. `$box->set(6)` where `set(T)` and `T=5` would
/// wrongly reject `6`). Mirrors `stmt::widen_for_check`, plus `true`/`false`
/// → `bool`.
fn widen_type_param(ty: &Type) -> Type {
let mut out = Type::empty();
out.from_docblock = ty.from_docblock;
out.possibly_undefined = ty.possibly_undefined;
for atomic in &ty.types {
let widened = match atomic {
Atomic::TLiteralInt(_) | Atomic::TIntRange { .. } => Atomic::TInt,
Atomic::TLiteralString(_) => Atomic::TString,
Atomic::TLiteralFloat(_, _) => Atomic::TFloat,
Atomic::TTrue | Atomic::TFalse => Atomic::TBool,
other => other.clone(),
};
out.add_type(widened);
}
out
}
/// Rebind a top-level `self`/`static`/`parent` atom in a property's declared
/// type to the concrete class that atom refers to — these atoms carry no
/// `type_params` of their own (there's nowhere on `TSelf`/`TStaticObject`/
/// `TParent` to put them), so a bare `@var self|null` on a generic class
/// read off a concrete receiver (`Box<int>`) would otherwise stay an
/// unbound `self()` instead of resolving to `Box<int>`. `self`/`static` are
/// treated identically (both resolve to `owner_fqcn`), matching this
/// codebase's existing self/static conflation elsewhere (e.g.
/// `call::args::substitute_static_atom`).
pub(super) fn rebind_self_static_parent(
ty: Type,
owner_fqcn: &str,
owner_type_params: &[Type],
) -> Type {
let mut out = Type::empty();
out.from_docblock = ty.from_docblock;
out.possibly_undefined = ty.possibly_undefined;
for atomic in ty.types {
let rebound = match atomic {
Atomic::TSelf { .. } | Atomic::TStaticObject { .. } | Atomic::TParent { .. } => {
Atomic::TNamedObject {
fqcn: Name::from(owner_fqcn),
type_params: mir_types::union::vec_to_type_params(owner_type_params.to_vec()),
}
}
other => other,
};
out.add_type(rebound);
}
out
}
/// Rebind every top-level `self`/`static`/`parent` atom to a `TNamedObject`
/// using that atom's OWN carried `fqcn` (already resolved to a concrete
/// class by the collector) — for a property-write receiver typed as
/// self/static/parent (e.g. a `self $x` parameter), not a nested reference
/// inside a property's own declared type (see [`rebind_self_static_parent`]
/// for that case, which needs an externally-supplied owner/type-params
/// instead). No template substitution: these atoms carry no type params of
/// their own and there's no additional context here to resolve them from,
/// matching this file's existing `TSelf`/`TStaticObject`/`TParent` read arm.
pub(super) fn rebind_self_static_parent_atom_only(ty: Type) -> Type {
let mut out = Type::empty();
out.from_docblock = ty.from_docblock;
out.possibly_undefined = ty.possibly_undefined;
for atomic in ty.types {
let rebound = match atomic {
Atomic::TSelf { fqcn } | Atomic::TStaticObject { fqcn } | Atomic::TParent { fqcn } => {
Atomic::TNamedObject {
fqcn,
type_params: Default::default(),
}
}
other => other,
};
out.add_type(rebound);
}
out
}
fn is_valid_class_name_type(ty: &Type) -> bool {
// Class names must be strings or class-string types. Mixed is allowed
// since it's already imprecise (matches the static-call path — a `mixed`
// receiver is a Mixed* concern, not InvalidStringClass). Template params
// are allowed because their bound may be a class-string.
ty.contains(|t| {
matches!(
t,
Atomic::TString
| Atomic::TClassString(_)
| Atomic::TLiteralString(_)
| Atomic::TMixed
| Atomic::TTemplateParam { .. }
)
})
}
/// Owned equivalent of `expr_can_be_passed_by_reference` for owned `Expr`.
fn expr_can_be_passed_by_reference_owned(expr: &Expr) -> bool {
matches!(
expr.kind,
ExprKind::Variable(_)
| ExprKind::ArrayAccess(_)
| ExprKind::PropertyAccess(_)
| ExprKind::NullsafePropertyAccess(_)
| ExprKind::StaticPropertyAccess(_)
| ExprKind::StaticPropertyAccessDynamic { .. }
)
}
/// Get the name string from an owned `Expr` for Variable/Identifier nodes.
fn expr_name_str(expr: &Expr) -> Option<&str> {
match &expr.kind {
ExprKind::Variable(s) | ExprKind::Identifier(s) => Some(s.as_ref()),
_ => None,
}
}
impl<'a> ExpressionAnalyzer<'a> {
/// Infer the class-level generic type params for `new Class(...)` from the
/// constructor argument types.
///
/// Given `@template T` on the class and a constructor parameter typed `T`,
/// `new Box(5)` binds `T → int` and returns `[int]` (in the class's declared
/// template-param order) so the result is `Box<int>`. Returns the cached
/// empty params when the class is non-generic or nothing could be inferred,
/// preserving the previous behaviour for ordinary instantiations.
fn infer_new_type_params(
&mut self,
fqcn: &Arc<str>,
ctor_params: Option<&[mir_codebase::definitions::DeclaredParam]>,
arg_types: &[Type],
arg_names: &[Option<String>],
call_span: php_ast::Span,
) -> Arc<[Type]> {
let empty = mir_types::union::empty_type_params();
// A plain subclass that doesn't redeclare `@template` (`class IntBox
// extends Box {}`) is still implicitly parameterized the same way
// `Box` is — walk up to the nearest ancestor that actually declares
// templates instead of bailing out just because `fqcn` itself has none.
let class_tps = match crate::db::class_template_params(self.db, fqcn) {
Some(tps) if !tps.is_empty() => tps,
_ => return empty,
};
let Some(ctor_params) = ctor_params else {
return empty;
};
// Bind class templates ONLY from constructor ARGUMENTS (no bound/mixed
// fallback). A template the constructor never binds is absent from the
// map, so it stays `mixed` (bare) in the emitted `type_params` — it must
// NOT be fabricated to its declared bound, or a later `T`-typed method
// call would falsely substitute the param to the bound and reject valid
// args (e.g. `@template T of Base`, `__construct(int $id)` → `new Repo(5)`
// must be bare `Repo`, never `Repo<Base>`).
let (mut bindings, unchecked) = crate::generic::infer_arg_template_bindings(
self.db,
&class_tps,
ctor_params,
arg_types,
arg_names,
);
// A subclass that fixes a generic ancestor via `@extends Box<int>`
// already determines T=int for every instance of this class,
// regardless of what this particular constructor call's arguments
// would otherwise infer — an inherited fixed binding takes priority
// so a mismatched constructor argument shows up as an arg-type
// mismatch (check_constructor_args, substituted the same way) rather
// than silently rebinding T to the bad argument's type and
// corrupting every later `@return T` on this receiver. This applies
// even when `fqcn` ALSO declares its own, separate `@template`
// (`class Mid<U> extends Base<int>` — U is still freshly inferred
// below, T is independently fixed) — only skipped per-entry when the
// inherited binding's value is itself self-referential, pointing
// back at one of `fqcn`'s OWN template params (e.g. `class
// TypedList { @template T; @implements Collection<T> }`, where T is
// exactly what THIS constructor call is inferring — merging it here
// would corrupt it into a self-referential `TypedList<T>`-shaped
// type before inference even runs).
let own_template_names: std::collections::HashSet<mir_types::Name> = class_tps
.iter()
.map(|tp| mir_types::Name::from(tp.name.as_ref()))
.collect();
for (name, ty) in crate::db::inherited_template_bindings(self.db, fqcn, &Default::default())
{
let self_referential = ty.contains(
|a| matches!(a, Atomic::TTemplateParam { name, .. } if own_template_names.contains(name)),
);
if !self_referential {
bindings.insert(name, ty);
}
}
// A class-level `@template T of Bound` was previously enforced only at
// method-call sites (against a method's OWN template params), never
// here — the dominant real-world path (constructor-arg inference on
// `new`) bypassed bound checking entirely. Check it the same way
// method/function calls do.
//
// Restricted to classes declared outside the bundled stubs: a stub
// constructor with multiple declared PHP overloads (e.g. DatePeriod's
// DateTimeInterface-pair vs. ISO-8601-string forms) is collapsed by
// `merge_method_overloads` into a single permissive signature that
// keeps only the longest overload's param *types* — the other
// overload's own param types are discarded entirely, not unioned in.
// Binding a template from an argument that actually satisfies a
// *different, now-invisible* overload would be a false positive that
// this approximation can't distinguish from a real violation.
let violations = crate::generic::check_template_bounds_with_inheritance(
self.db,
&bindings,
&class_tps,
&unchecked,
Some(fqcn.as_ref()),
);
let is_stub_class = !violations.is_empty()
&& crate::db::class_like_decl_file(self.db, crate::db::Fqcn::from_str(self.db, fqcn))
.is_some_and(|f| crate::stubs::StubVfs::new().is_stub_file(f.as_ref()));
for (name, inferred, bound) in violations {
if is_stub_class {
continue;
}
self.emit(
IssueKind::InvalidTemplateParam {
name: name.to_string(),
expected_bound: format!("{bound}"),
actual: format!("{inferred}"),
},
Severity::Error,
call_span,
);
}
// Emit the inferred bindings in the class's declared template-param order
// so `build_class_bindings` zips them back correctly at the call site.
// A template bound from an argument → its (widened) inferred type;
// otherwise → `mixed`. Only consider the receiver "concrete" when at
// least one template was bound from an argument — otherwise keep the
// bare (un-parameterised) type, preserving prior behaviour for ordinary
// / non-generic / uninferable instantiations.
let mut params: Vec<Type> = Vec::with_capacity(class_tps.len());
let mut any_concrete = false;
for tp in class_tps.iter() {
match bindings.get(&mir_types::Name::from(tp.name.as_ref())) {
Some(ty) if !ty.is_mixed_not_template() => {
// Widen scalar literals to their base type so the receiver
// does not carry an over-narrow type param (e.g. `new Box(5)`
// → `Box<int>`, not `Box<5>`, so a later `$box->set(6)` for
// `set(T)` is not wrongly rejected).
any_concrete = true;
params.push(widen_type_param(ty));
}
_ => params.push(Type::mixed()),
}
}
if any_concrete {
mir_types::union::vec_to_type_params(params)
} else {
empty
}
}
pub(super) fn analyze_new(
&mut self,
n: &NewExpr,
call_span: php_ast::Span,
ctx: &mut FlowState,
) -> Type {
let mut arg_types = crate::call::ARG_TYPES_BUF
.with(|b| b.borrow_mut().take())
.unwrap_or_default();
arg_types.clear();
let mut sole_spread_ty: Option<Type> = None;
for a in n.args.iter() {
let ty = self.analyze(&a.value, ctx);
crate::call::consume_arg_assignment(&a.value, ctx);
if a.unpack {
if n.args.len() == 1 {
sole_spread_ty = Some(ty.clone());
}
arg_types.push(crate::call::spread_element_type(self.db, &ty));
} else {
arg_types.push(ty);
}
}
let mut arg_spans: Vec<php_ast::Span> = n.args.iter().map(|a| a.span).collect();
let mut arg_names: Vec<Option<String>> = n
.args
.iter()
.map(|a| a.name.as_ref().map(crate::parser::name_to_string_owned))
.collect();
let mut arg_can_be_byref: Vec<bool> = n
.args
.iter()
.map(|a| expr_can_be_passed_by_reference_owned(&a.value))
.collect();
let mut ctor_has_spread = n.args.iter().any(|a| a.unpack);
let mut ctor_arity_unknown = ctor_has_spread;
// A sole spread arg over a literal, sequentially-keyed shape can be
// expanded into one binding per element so each constructor
// parameter is checked individually instead of only the first (see
// expand_sole_spread_arg). `ctor_arity_unknown` stays true even
// after expansion — PHP allows extra/spread positional args, so a
// concretely-known count still shouldn't trigger
// TooFew/TooManyArguments.
if let Some(expanded) = sole_spread_ty.and_then(|t| crate::call::expand_sole_spread_arg(&t))
{
arg_spans = crate::call::distinct_spans_for_expansion(arg_spans[0], expanded.len());
arg_names = vec![None; expanded.len()];
arg_can_be_byref = vec![false; expanded.len()];
arg_types = expanded;
ctor_has_spread = false;
ctor_arity_unknown = true;
}
// Generic type params inferred from constructor arguments, attached to
// the resulting `TNamedObject` so member-access substitution works.
let mut inferred_type_params: Arc<[Type]> = mir_types::union::empty_type_params();
let class_ty = match &n.class.kind {
ExprKind::Identifier(name) => {
let resolved = crate::db::resolve_name(self.db, &self.file, name.as_ref());
let fqcn: Arc<str> = match resolved.as_str() {
"self" | "static" => ctx
.self_fqcn
.clone()
.or_else(|| ctx.static_fqcn.clone())
.unwrap_or_else(|| Arc::from(resolved.as_str())),
"parent" => ctx
.parent_fqcn
.clone()
.unwrap_or_else(|| Arc::from(resolved.as_str())),
_ => Arc::from(resolved.as_str()),
};
let type_exists = crate::db::class_exists(self.db, fqcn.as_ref());
if !matches!(resolved.as_str(), "self" | "static" | "parent")
&& !type_exists
&& !ctx.is_class_guarded(fqcn.as_ref())
{
self.emit(
IssueKind::UndefinedClass {
name: resolved.clone(),
},
Severity::Error,
n.class.span,
);
} else if type_exists {
let here = crate::db::Fqcn::from_str(self.db, fqcn.as_ref());
if let Some(class) = crate::db::find_class_like(self.db, here) {
// `new static()` is valid even in an abstract class:
// late static binding resolves `static` to the concrete
// subclass at runtime, never the abstract class itself.
// `new self()` / `new AbstractName()` remain errors.
if class.is_class() && class.is_abstract() && resolved.as_str() != "static"
{
self.emit(
IssueKind::AbstractInstantiation {
class: fqcn.to_string(),
},
Severity::Error,
n.class.span,
);
}
if class.is_interface() {
self.emit(
IssueKind::InterfaceInstantiation {
class: fqcn.to_string(),
},
Severity::Error,
n.class.span,
);
}
if let Some(msg) = class.deprecated() {
self.emit(
IssueKind::DeprecatedClass {
name: fqcn.to_string(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
n.class.span,
);
}
// Check for case mismatch between written name and canonical
if let Some((used, canonical_str)) =
crate::fqcn_case_mismatch(fqcn.as_ref(), class.fqcn().as_ref())
{
self.emit(
IssueKind::WrongCaseClass {
used,
canonical: canonical_str,
},
Severity::Info,
n.class.span,
);
}
}
let ctor_params_and_templates = crate::db::find_method_in_chain(
self.db,
crate::db::Fqcn::from_str(self.db, fqcn.as_ref()),
"__construct",
)
.map(|(_, s)| {
(
s.params.to_vec(),
s.template_params.clone(),
s.no_named_arguments,
s.taint_sink_params.clone(),
s.is_pure,
s.is_mutation_free,
)
});
// `new static`/`new self`/`new parent` inside a trait binds
// to the using class's constructor (late static binding),
// not the trait's — which has none. Skip constructor-arg
// validation so passing args isn't flagged against the
// trait's (absent) zero-arg implicit constructor.
let trait_relative_new =
matches!(resolved.as_str(), "self" | "static" | "parent")
&& crate::flow_state::self_is_trait(self.db, ctx);
if let Some((
ctor_params,
ctor_templates,
ctor_no_named_args,
ctor_taint_sink_params,
ctor_is_pure,
ctor_is_mutation_free,
)) = &ctor_params_and_templates
{
// Taint sink check: `new Sink($tainted)` reaching a
// @taint-sink annotated constructor parameter never
// ran this at all — call/function.rs and
// call/method.rs both check it for their own call
// shapes, but analyze_new had no equivalent.
if !ctor_taint_sink_params.is_empty() {
for (param_name, sink_kind) in ctor_taint_sink_params {
let param_idx = ctor_params
.iter()
.position(|p| p.name.as_ref() == param_name.as_ref());
let is_variadic = param_idx
.and_then(|idx| ctor_params.get(idx))
.is_some_and(|p| p.is_variadic);
let args: Vec<&php_ast::owned::Arg> = if is_variadic {
let idx = param_idx.unwrap();
n.args
.iter()
.filter(|a| a.name.is_none())
.skip(idx)
.collect()
} else {
let positional = param_idx.and_then(|idx| n.args.get(idx));
let named = n.args.iter().find(|a| {
a.name
.as_ref()
.map(|nm| {
crate::parser::name_to_string_owned(nm)
== param_name.as_ref()
})
.unwrap_or(false)
});
positional.or(named).into_iter().collect()
};
for arg in args {
if crate::taint::is_expr_tainted(
&arg.value, ctx, self.db, &self.file,
) {
self.emit(
crate::taint::taint_sink_issue(sink_kind),
Severity::Error,
call_span,
);
}
}
}
}
// Purity check: `new X(...)` inside a @pure function
// runs X's constructor exactly like any other call —
// call/function.rs and call/method.rs both check the
// callee's own is_pure for their own call shapes, but
// analyze_new had no equivalent at all. A @mutation-free
// constructor is exempt (not just @pure): initializing
// $this's own properties during construction is not an
// external mutation, the same exemption
// mutation_free_constructor_ok already proves for a
// plain assignment inside the constructor body.
if ctx.is_in_pure_fn && !ctor_is_pure && !ctor_is_mutation_free {
self.emit(
IssueKind::ImpureFunctionCall {
fn_name: format!("{fqcn}::__construct"),
},
Severity::Warning,
call_span,
);
}
// Same check for @psalm-immutable/@psalm-external-
// mutation-free, scoped to when a constructor
// argument is both OBJECT-typed and reachable from
// `$this`/a parameter — passing `$this`'s own state
// (or a parameter's) into an impure constructor lets
// it store/mutate that object just as much as
// calling an impure METHOD on it would
// (call/method.rs's own external-mutation-free check
// has the identical receiver scoping). The
// object-typed requirement matters: passing a plain
// VALUE read off `$this` (`new self($this->intProp)`,
// the standard immutable "wither" idiom) is not a
// mutation risk at all — only an object reference the
// constructor could hold onto and later mutate is.
if (ctx.is_in_immutable_method || ctx.is_in_external_mutation_free_method)
&& !ctor_is_pure
&& !ctor_is_mutation_free
{
for arg in n.args.iter() {
let Some(recv_name) = root_receiver_var(&arg.value) else {
continue;
};
let recv_stripped = recv_name.trim_start_matches('$');
let reachable = (ctx.is_in_immutable_method
&& recv_stripped == "this")
|| (ctx.is_in_external_mutation_free_method
&& recv_stripped != "this"
&& ctx.param_names.contains(&Name::from(recv_stripped)));
if !reachable {
continue;
}
let arg_is_object =
crate::expr::assignment::resolve_chained_receiver_type(
&arg.value, ctx, self.db, &self.file,
)
.is_some_and(|ty| {
ty.types.iter().any(|a| {
matches!(
a,
Atomic::TNamedObject { .. }
| Atomic::TSelf { .. }
| Atomic::TStaticObject { .. }
| Atomic::TParent { .. }
)
})
});
if arg_is_object {
self.emit(
IssueKind::ImpureFunctionCall {
fn_name: format!("{fqcn}::__construct"),
},
Severity::Warning,
call_span,
);
break;
}
}
}
if !trait_relative_new {
// A bare subclass of a generic ancestor fixed via
// `@extends Box<int>` already determines T=int for
// this exact `new` — substitute it into the
// constructor's own param types before arg-checking,
// mirroring how every other template-consuming call
// site (method/static calls, property read/write,
// array-access, foreach) substitutes
// `inherited_template_bindings` before using a
// class's template params. A constructor-level
// `@template T` shadowing the class-level one keeps
// its own occurrences unbound so arg inference still
// runs for it.
let class_tps = crate::db::class_template_params(self.db, &fqcn)
.map(|tps| tps.to_vec())
.unwrap_or_default();
let mut bindings: rustc_hash::FxHashMap<mir_types::Name, Type> =
Default::default();
// Merged even when `fqcn` ALSO declares its own,
// separate `@template` (`class Mid<U> extends
// Base<int>` — U is still freshly inferred below,
// T is independently fixed) — only skipped
// per-entry when the inherited binding's value is
// itself self-referential, pointing back at one of
// `fqcn`'s OWN template params (e.g. a class
// implementing a covariant interface with its own
// template forwarded to it, `@implements
// Collection<T>`) — there, T is exactly what THIS
// constructor-arg inference is meant to bind, and
// merging it here would corrupt it into a
// self-referential type before inference runs.
let own_template_names: std::collections::HashSet<mir_types::Name> =
class_tps
.iter()
.map(|tp| mir_types::Name::from(tp.name.as_ref()))
.collect();
for (k, v) in crate::db::inherited_template_bindings(
self.db,
&fqcn,
&Default::default(),
) {
let self_referential = v.contains(|a| {
matches!(a, Atomic::TTemplateParam { name, .. } if own_template_names.contains(name))
});
if !self_referential {
bindings.insert(k, v);
}
}
for tp in ctor_templates.iter() {
bindings.remove(&mir_types::Name::from(tp.name.as_ref()));
}
let substituted_ctor_params: Vec<
mir_codebase::definitions::DeclaredParam,
>;
let effective_ctor_params: &[mir_codebase::definitions::DeclaredParam] =
if bindings.is_empty() || class_tps.is_empty() {
ctor_params
} else {
substituted_ctor_params = ctor_params
.iter()
.map(|p| mir_codebase::definitions::DeclaredParam {
ty: mir_codebase::wrap_param_type(
p.ty.as_ref()
.map(|t| t.substitute_templates(&bindings)),
),
out_ty: mir_codebase::wrap_param_type(
p.out_ty
.as_ref()
.map(|t| t.substitute_templates(&bindings)),
),
..p.clone()
})
.collect();
&substituted_ctor_params
};
crate::call::check_constructor_args(
self,
&fqcn,
crate::call::CheckArgsParams {
fn_name: "__construct",
params: effective_ctor_params,
arg_types: &arg_types,
arg_spans: &arg_spans,
arg_names: &arg_names,
arg_can_be_byref: &arg_can_be_byref,
call_span,
has_spread: ctor_has_spread,
arity_unknown: ctor_arity_unknown,
too_many_arity_unknown: false,
template_params: ctor_templates,
no_named_arguments: *ctor_no_named_args,
},
);
}
} else if !arg_types.is_empty()
&& !n.args.iter().any(|a| a.unpack)
&& !trait_relative_new
// `new static(args)` may construct a subclass that
// declares a constructor, even when the current class
// has none — don't flag it against the implicit 0-arg
// constructor (`new self` / a named class still are).
&& resolved.as_str() != "static"
&& crate::db::class_exists(self.db, fqcn.as_ref())
{
// Class has no constructor but arguments were passed —
// PHP's implicit constructor accepts zero arguments.
self.emit(
mir_issues::IssueKind::TooManyArguments {
fn_name: format!("{fqcn}::__construct"),
expected: 0,
actual: arg_types.len(),
},
mir_issues::Severity::Error,
call_span,
);
}
// Infer class-level generic type params from the constructor
// arguments (e.g. `new Box(5)` → `Box<int>` for `@template T`
// with `__construct(T $value)`). This lets later member access
// (`$b->get()`) substitute the receiver's bindings into return
// types, including UNANNOTATED inferred returns.
inferred_type_params = self.infer_new_type_params(
&fqcn,
ctor_params_and_templates
.as_ref()
.map(|(p, _, _, _, _, _)| p.as_slice()),
&arg_types,
&arg_names,
call_span,
);
}
crate::call::ARG_TYPES_BUF.with(|b| {
let mut g = b.borrow_mut();
if g.as_ref().map_or(0, |v| v.capacity()) < arg_types.capacity() {
*g = Some(arg_types);
}
});
let ty = Type::single(Atomic::TNamedObject {
fqcn: mir_types::Name::from(fqcn.as_ref()),
type_params: std::mem::replace(
&mut inferred_type_params,
mir_types::union::empty_type_params(),
),
});
self.record_symbol(
n.class.span,
ReferenceKind::ClassReference(fqcn.clone()),
ty.clone(),
);
self.record_ref(Arc::from(format!("cls:{fqcn}")), n.class.span);
// A `new X(...)` site is also a constructor call: record it
// under the method key so find-references on `__construct`
// resolves instantiation sites without an AST re-walk.
self.record_ref(Arc::from(format!("meth:{fqcn}::__construct")), n.class.span);
ty
}
_ => {
let ty = self.analyze(&n.class, ctx);
// Check if the expression could evaluate to a valid class name
// (but skip anonymous class definitions, which are valid)
if !matches!(n.class.kind, ExprKind::AnonymousClass(_))
&& !is_valid_class_name_type(&ty)
{
self.emit(
IssueKind::InvalidStringClass {
actual: ty.to_string(),
},
Severity::Warning,
n.class.span,
);
}
// Note: TClassString<AbstractClass> is valid for `new $var` because the
// class-string constraint means the held class-name IS-A AbstractClass, not
// that it IS AbstractClass itself. The concrete runtime class may be any
// non-abstract subclass, so no AbstractInstantiation check here.
// `new $class()` where `$class` holds a known class-string
// (`$class = Foo::class;`) is a real reference to `Foo` — record it,
// or a class instantiated only this way is falsely flagged unused
// with no go-to-definition from this call site.
for atomic in &ty.types {
if let Atomic::TClassString(Some(fqcn)) = atomic {
self.record_ref(Arc::from(format!("cls:{fqcn}")), n.class.span);
self.record_symbol(
n.class.span,
ReferenceKind::ClassReference(Arc::from(fqcn.as_ref())),
Type::single(Atomic::TClassString(None)),
);
}
}
Type::single(Atomic::TObject)
}
};
class_ty
}
/// `EnumName::CaseName->value` / `->name`: look the case up directly from
/// the object EXPRESSION's own syntax rather than its (widened, generic
/// enum) inferred type — see the call sites for why. Returns `None` for
/// anything else (a variable, a method call, `self::Case`, an unresolved
/// class, an unknown case name, …), which falls through to the ordinary
/// property-resolution path unchanged.
fn enum_case_literal_property(&self, object: &Expr, prop_name: &str) -> Option<Type> {
let ExprKind::ClassConstAccess(cca) = &object.kind else {
return None;
};
let ExprKind::Identifier(class_id) = &cca.class.kind else {
return None;
};
let ExprKind::Identifier(case_name) = &cca.member.kind else {
return None;
};
if case_name.as_ref() == "class" {
return None;
}
let resolved = crate::db::resolve_name(self.db, &self.file, class_id.as_ref());
let here = crate::db::Fqcn::from_str(self.db, &resolved);
let crate::db::ClassLike::Enum(e) = crate::db::find_class_like(self.db, here)? else {
return None;
};
let case = e.cases.get(case_name.as_ref())?;
match prop_name {
// A non-backed enum has no `->value` at all — `case.value` is
// always `Some` regardless (a plain `mixed` fallback when the
// case has no explicit value, same as an unbacked case), so this
// must be gated on the ENUM's own backing type, not just an
// `Option` check, or accessing `->value` on a non-backed case
// would silently resolve instead of the `UndefinedProperty` the
// ordinary property-resolution path below correctly emits.
"value" if e.scalar_type.is_some() => case.value.clone(),
"name" => Some(Type::single(Atomic::TLiteralString(Arc::from(
case_name.as_ref(),
)))),
_ => None,
}
}
pub(super) fn analyze_property_access(
&mut self,
pa: &PropertyAccessExpr,
expr_span: php_ast::Span,
ctx: &mut FlowState,
) -> Type {
let obj_ty = self.analyze(&pa.object, ctx);
self.record_receiver_type(pa.object.span, pa.property.span, obj_ty.clone());
let prop_name =
extract_string_from_expr(&pa.property).unwrap_or_else(|| "<dynamic>".to_string());
if obj_ty.is_mixed() {
let is_only_template_params = obj_ty
.types
.iter()
.all(|t| matches!(t, Atomic::TTemplateParam { .. }));
if !is_only_template_params {
self.emit(
IssueKind::MixedPropertyFetch {
property: prop_name.clone(),
},
Severity::Info,
expr_span,
);
}
// Unknowable receiver — record a name-only fallback so
// find-references on any `X::$name` can surface this access.
if prop_name != "<dynamic>" {
self.record_ref(Arc::from(format!("propname:{prop_name}")), pa.property.span);
}
return Type::mixed();
}
// InvalidPropertyFetch: all types are scalar/non-object
if !obj_ty.is_mixed()
&& !obj_ty.types.is_empty()
&& obj_ty.types.iter().all(|a| {
matches!(
a,
Atomic::TInt
| Atomic::TLiteralInt(_)
| Atomic::TIntRange { .. }
| Atomic::TPositiveInt
| Atomic::TFloat
| Atomic::TIntegralFloat
| Atomic::TLiteralFloat(_, _)
| Atomic::TString
| Atomic::TNonEmptyString
| Atomic::TNumericString
| Atomic::TLiteralString(_)
| Atomic::TBool
| Atomic::TTrue
| Atomic::TFalse
| Atomic::TArray { .. }
| Atomic::TNonEmptyArray { .. }
| Atomic::TList { .. }
| Atomic::TNonEmptyList { .. }
| Atomic::TKeyedArray { .. }
)
})
{
self.emit(
IssueKind::InvalidPropertyFetch {
ty: obj_ty.to_string(),
},
Severity::Error,
expr_span,
);
return Type::mixed();
}
if obj_ty.contains(|t| matches!(t, Atomic::TNull)) && obj_ty.is_single() {
self.emit(
IssueKind::NullPropertyFetch {
property: prop_name.clone(),
},
Severity::Error,
expr_span,
);
return Type::mixed();
}
if obj_ty.is_nullable() {
self.emit(
IssueKind::PossiblyNullPropertyFetch {
property: prop_name.clone(),
},
Severity::Info,
expr_span,
);
}
if prop_name == "<dynamic>" {
self.analyze(&pa.property, ctx);
self.record_dynamic_member_access(&obj_ty, pa.property.span);
return Type::mixed();
}
// `Kind::Foo->value`/`->name` on a LITERAL case reference: the
// receiver's inferred type (`obj_ty`) is only ever the generic enum
// object type (`Kind::Foo` is typed as bare `Kind`, not a
// case-specific atom — a separate, wider gap than this one property-
// access site), so `resolve_property_type` below can only ever widen
// to the enum's whole backing scalar type. Recovering the specific
// case directly from the object EXPRESSION's own syntax (rather than
// its already-widened type) is what lets match arms written as
// `Kind::Foo->value => ...` keep their literal value, which
// exhaustiveness checking needs to prove a match over `->value` is
// complete.
if prop_name == "value" || prop_name == "name" {
if let Some(ty) = self.enum_case_literal_property(&pa.object, &prop_name) {
return ty;
}
}
let non_null_ty = obj_ty.remove_null();
let mut declaring = None;
let resolved = self.resolve_property_type(
&non_null_ty,
&prop_name,
pa.property.span,
&mut declaring,
ctx,
);
// If we have a narrowed type for this property access ($var->prop,
// or the one-more-hop $var->a->prop), return it instead of the
// declared type.
let mut resolved =
if let Some(obj_key) = crate::narrowing::chained_prop_receiver_key(&pa.object) {
ctx.get_prop_refined(&obj_key, &prop_name)
.cloned()
.unwrap_or(resolved)
} else {
resolved
};
// PHP 8 reads a plain `->` access on a null receiver as a warning
// (not fatal), still evaluating to null — same observable value as
// `?->`'s short-circuit (see analyze_nullsafe_property_access, which
// this mirrors). So the expression's type must include null too
// whenever the receiver itself could be null. Guarded on `obj_ty`
// (not `non_null_ty`) so a receiver already narrowed non-null (e.g.
// inside `if ($obj->prop !== null)`, which also narrows `$obj`)
// doesn't get re-widened.
if obj_ty.is_nullable() {
resolved.add_type(Atomic::TNull);
}
for atomic in &non_null_ty.types {
if let Atomic::TNamedObject { fqcn, .. } = atomic {
let declaring_class = declaring.take().unwrap_or_else(|| Arc::from(fqcn.as_ref()));
self.record_symbol(
pa.property.span,
ReferenceKind::PropertyAccess {
class: declaring_class,
property: Arc::from(prop_name.as_str()),
},
resolved.clone(),
);
break;
}
}
resolved
}
pub(super) fn analyze_nullsafe_property_access(
&mut self,
pa: &PropertyAccessExpr,
ctx: &mut FlowState,
) -> Type {
let obj_ty = self.analyze(&pa.object, ctx);
self.record_receiver_type(pa.object.span, pa.property.span, obj_ty.clone());
let prop_name =
extract_string_from_expr(&pa.property).unwrap_or_else(|| "<dynamic>".to_string());
if prop_name == "<dynamic>" {
self.analyze(&pa.property, ctx);
self.record_dynamic_member_access(&obj_ty, pa.property.span);
return Type::mixed();
}
// See the identical special case in `analyze_property_access` above —
// a literal `Kind::Foo?->value`/`->name` access recovers the specific
// case from the receiver's own syntax. `Kind::Foo` is never itself
// null, so no `TNull` needs adding here the way the general path below
// does for a genuinely nullable receiver.
if prop_name == "value" || prop_name == "name" {
if let Some(ty) = self.enum_case_literal_property(&pa.object, &prop_name) {
return ty;
}
}
let non_null_ty = obj_ty.remove_null();
let mut declaring = None;
let resolved = self.resolve_property_type(
&non_null_ty,
&prop_name,
pa.property.span,
&mut declaring,
ctx,
);
// If we have a narrowed type for this property access ($var?->prop,
// or the one-more-hop $var->a?->prop), return it instead of the
// declared type — matching the plain `->` path in
// analyze_property_access above.
let mut prop_ty =
if let Some(obj_key) = crate::narrowing::chained_prop_receiver_key(&pa.object) {
ctx.get_prop_refined(&obj_key, &prop_name)
.cloned()
.unwrap_or(resolved)
} else {
resolved
};
// Only the receiver's own nullability can make `$obj?->prop` evaluate to
// null — if `$obj` can never be null, this is exactly `$obj->prop`'s type,
// narrowed-or-not. Adding TNull unconditionally clobbered a narrowed
// non-null property type back into a nullable one.
if obj_ty.is_nullable() {
prop_ty.add_type(Atomic::TNull);
}
for atomic in &non_null_ty.types {
if let Atomic::TNamedObject { fqcn, .. } = atomic {
let declaring_class = declaring.take().unwrap_or_else(|| Arc::from(fqcn.as_ref()));
self.record_symbol(
pa.property.span,
ReferenceKind::PropertyAccess {
class: declaring_class,
property: Arc::from(prop_name.as_str()),
},
prop_ty.clone(),
);
break;
}
}
prop_ty
}
pub(super) fn analyze_static_property_access(
&mut self,
spa: &StaticAccessExpr,
ctx: &FlowState,
) -> Type {
let mut result_ty = Type::mixed();
if let ExprKind::Identifier(id) = &spa.class.kind {
let resolved = crate::db::resolve_name(self.db, &self.file, id.as_ref());
if matches!(resolved.as_str(), "self" | "static" | "parent") {
// Resolve the relative keyword through the FlowState and record
// the property read so a `self::$prop` access counts as a use
// (otherwise a private static property is wrongly reported
// UnusedProperty).
let fqcn_opt = match resolved.as_str() {
"self" | "static" => ctx.self_fqcn.clone().or_else(|| ctx.static_fqcn.clone()),
"parent" => ctx.parent_fqcn.clone(),
_ => None,
};
if let Some(fqcn) = fqcn_opt {
self.record_symbol(
spa.class.span,
ReferenceKind::ClassReference(fqcn.clone()),
Type::single(Atomic::TClassString(None)),
);
if let Some(prop_name) = expr_name_str(&spa.member) {
let prop_name = prop_name.trim_start_matches('$');
// Key by the declaring owner, not `self`/`static`'s own
// class — a `self::$prop` access inside a subclass for a
// `$prop` declared on the parent must record
// `prop:Parent::prop`, matching `record_static_prop_access`.
let mut owner = fqcn.clone();
if let Some(refined) = ctx.get_prop_refined(fqcn.as_ref(), prop_name) {
result_ty = refined.clone();
} else {
let here = crate::db::Fqcn::from_str(self.db, fqcn.as_ref());
if let Some((prop_owner, p)) =
crate::db::find_property_in_chain(self.db, here, prop_name)
{
owner = prop_owner;
if !self.in_existence_check
&& self.property_inaccessible(p.visibility, owner.as_ref(), ctx)
{
self.emit(
IssueKind::InaccessibleProperty {
class: owner.to_string(),
property: prop_name.to_string(),
},
Severity::Error,
spa.member.span,
);
}
let ty = p.ty.as_deref().cloned().unwrap_or_else(Type::mixed);
// A static access has no receiver instance to carry
// type args, but an `@extends Box<int>` clause on the
// accessed class itself still statically binds the
// declaring class's template param — resolve that,
// mirroring the write-side substitution in
// assignment.rs (otherwise a generic static property
// stays an unresolved bare template / mixed).
let bindings = crate::db::inherited_template_bindings(
self.db,
fqcn.as_ref(),
&rustc_hash::FxHashMap::default(),
);
result_ty = if bindings.is_empty() {
ty
} else {
ty.substitute_templates(&bindings)
};
}
}
self.record_ref(
Arc::from(format!("prop:{}::{}", owner, prop_name)),
spa.member.span,
);
// Same read-side purity check as the explicit-class-name
// path (record_static_prop_access) — reading shared
// external state is non-deterministic across calls,
// same as a superglobal read.
if ctx.is_in_pure_fn {
self.emit(
IssueKind::ImpureStaticPropertyAccess {
class: owner.to_string(),
property: prop_name.to_string(),
},
Severity::Warning,
spa.member.span,
);
}
self.record_symbol(
spa.member.span,
ReferenceKind::PropertyAccess {
class: owner,
property: Arc::from(prop_name),
},
result_ty.clone(),
);
self.record_receiver_type(
spa.class.span,
spa.member.span,
Type::single(Atomic::TClassString(Some(mir_types::Name::from(
fqcn.as_ref(),
)))),
);
}
}
} else if !crate::db::class_exists(self.db, &resolved)
&& !ctx.is_class_guarded(resolved.as_str())
{
self.emit(
IssueKind::UndefinedClass { name: resolved },
Severity::Error,
spa.class.span,
);
} else {
result_ty = self.record_static_prop_access(
Arc::from(resolved.as_str()),
&spa.class,
&spa.member,
ctx,
);
}
} else if let ExprKind::Variable(var_name) = &spa.class.kind {
// `$cls::$prop` — derive the FQCN(s) from the variable's inferred
// type, mirroring the `$obj::CONST` handling in
// `analyze_class_const_access`. Covers both an object instance
// (`$obj::$prop`) and a class-string (`$cls = self::class;`).
// Without this, a property read only through a variable holding
// the class was never checked (existence/visibility/deprecation)
// and never recorded as a usage — falsely flagging the property
// (and, if otherwise unreferenced, the class) as unused.
let var_ty = ctx.get_var(var_name.as_ref());
let mut result = Type::empty();
let mut any = false;
for atomic in &var_ty.types {
let fqcn = atomic.named_object_fqcn().or_else(|| match atomic {
Atomic::TClassString(Some(fqcn)) => Some(fqcn.as_ref()),
_ => None,
});
if let Some(fqcn) = fqcn {
any = true;
let ty = self.record_static_prop_access(
Arc::from(fqcn),
&spa.class,
&spa.member,
ctx,
);
result.merge_with(&ty);
}
}
if any {
result_ty = result;
}
}
result_ty
}
/// Record and resolve a static property access (`Class::$prop`) once the
/// concrete class FQCN is known — shared by the plain-identifier class
/// name path and the object-instance/class-string variable path.
fn record_static_prop_access(
&mut self,
resolved: Arc<str>,
class_expr: &Expr,
member_expr: &Expr,
ctx: &FlowState,
) -> Type {
let mut result_ty = Type::mixed();
self.record_ref(Arc::from(format!("cls:{resolved}")), class_expr.span);
self.record_symbol(
class_expr.span,
ReferenceKind::ClassReference(resolved.clone()),
Type::single(Atomic::TClassString(None)),
);
self.record_receiver_type(
class_expr.span,
member_expr.span,
Type::single(Atomic::TClassString(Some(mir_types::Name::from(
resolved.as_ref(),
)))),
);
if let Some(prop_name) = expr_name_str(member_expr) {
// Key the reference/symbol by the property's declaring owner, not
// the accessed-through class — `Child::$prop` for a `$prop`
// declared on `Parent` must record `prop:Parent::prop`, or
// find-references from the declaring property never sees usages
// reached only through a subclass name (the same fix already
// applied to constant/instance-property access above).
let mut owner = resolved.clone();
if let Some(refined) = ctx.get_prop_refined(resolved.as_ref(), prop_name) {
result_ty = refined.clone();
} else {
let here = crate::db::Fqcn::from_str(self.db, resolved.as_ref());
if let Some(p) = crate::db::find_property_in_chain(self.db, here, prop_name) {
owner = p.0.clone();
if let Some(msg) = &p.1.deprecated {
self.emit(
IssueKind::DeprecatedProperty {
class: resolved.to_string(),
property: prop_name.to_string(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
member_expr.span,
);
}
if !self.in_existence_check
&& self.property_inaccessible(p.1.visibility, owner.as_ref(), ctx)
{
self.emit(
IssueKind::InaccessibleProperty {
class: owner.to_string(),
property: prop_name.to_string(),
},
Severity::Error,
member_expr.span,
);
}
let ty = p.1.ty.as_deref().cloned().unwrap_or_else(Type::mixed);
// Static-property counterpart of the same substitution
// `analyze_static_property_access`'s self/static/parent
// branch and the write-side (assignment.rs) both apply —
// a static access has no receiver instance to carry type
// args, but an `@extends Box<int>` clause on `resolved`
// itself still statically binds the declaring class's
// template param.
let bindings = crate::db::inherited_template_bindings(
self.db,
resolved.as_ref(),
&rustc_hash::FxHashMap::default(),
);
result_ty = if bindings.is_empty() {
ty
} else {
ty.substitute_templates(&bindings)
};
}
}
// Reading a static property is just as non-deterministic across
// calls as reading a superglobal (already checked in
// variables.rs/arrays.rs) — but unlike the write side
// (ImpureStaticPropertyAssignment), the read side had no check
// at all.
if ctx.is_in_pure_fn {
self.emit(
IssueKind::ImpureStaticPropertyAccess {
class: owner.to_string(),
property: prop_name.to_string(),
},
Severity::Warning,
member_expr.span,
);
}
self.record_ref(
Arc::from(format!("prop:{}::{}", owner, prop_name)),
member_expr.span,
);
self.record_symbol(
member_expr.span,
ReferenceKind::PropertyAccess {
class: owner,
property: Arc::from(prop_name),
},
result_ty.clone(),
);
}
result_ty
}
pub(super) fn analyze_class_const_access(
&mut self,
cca: &StaticAccessExpr,
expr_span: php_ast::Span,
ctx: &FlowState,
) -> Type {
if expr_name_str(&cca.member) == Some("class") {
if let ExprKind::Identifier(id) = &cca.class.kind {
let resolved = crate::db::resolve_name(self.db, &self.file, id.as_ref());
if resolved.as_str() == "parent"
&& ctx.parent_fqcn.is_none()
&& ctx.self_fqcn.is_some()
{
self.emit(IssueKind::ParentNotFound, Severity::Error, cca.class.span);
}
if !matches!(resolved.as_str(), "self" | "static" | "parent") {
// `Foo::class` is a PHP compile-time string constant — the class
// need not be loaded or even defined. Never emit UndefinedClass
// for `::class` expressions.
if crate::db::class_exists(self.db, &resolved) {
// Check if the class is deprecated
let here = crate::db::Fqcn::from_str(self.db, resolved.as_str());
if let Some(class) = crate::db::find_class_like(self.db, here) {
if let Some(msg) = class.deprecated() {
self.emit(
IssueKind::DeprecatedClass {
name: resolved.clone(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
cca.class.span,
);
}
}
}
self.record_ref(Arc::from(format!("cls:{resolved}")), cca.class.span);
// Without this, go-to-definition/hover on the class name inside
// `Foo::class` resolved nothing, unlike every other class-name
// position (`new Foo`, `instanceof Foo`, `Foo::method()`, …).
self.record_symbol(
cca.class.span,
ReferenceKind::ClassReference(Arc::from(resolved.as_str())),
Type::single(Atomic::TClassString(None)),
);
}
// `self`/`static`/`parent::class` must carry the actual enclosing
// class, not the literal pseudo-name — otherwise a variable holding
// `self::class` types as the unresolvable `class-string<self>`
// instead of e.g. `class-string<Foo>`, breaking every downstream
// consumer of that variable (including `$var::CONST`/`$var::$prop`).
let concrete = match resolved.as_str() {
"self" | "static" => ctx
.self_fqcn
.clone()
.or_else(|| ctx.static_fqcn.clone())
.unwrap_or_else(|| Arc::from(resolved.as_str())),
"parent" => ctx
.parent_fqcn
.clone()
.unwrap_or_else(|| Arc::from(resolved.as_str())),
_ => Arc::from(resolved.as_str()),
};
return Type::single(Atomic::TClassString(Some(mir_types::Name::from(
concrete.as_ref(),
))));
}
// For $obj::class, derive class-string<T> from the object's declared type.
if let ExprKind::Variable(var_name) = &cca.class.kind {
let obj_ty = ctx.get_var(var_name.as_ref());
let mut result = Type::empty();
for atomic in &obj_ty.types {
match atomic {
Atomic::TNamedObject { fqcn, .. }
| Atomic::TSelf { fqcn }
| Atomic::TStaticObject { fqcn } => {
result.add_type(Atomic::TClassString(Some(*fqcn)));
}
_ => {}
}
}
if !result.types.is_empty() {
return result;
}
}
return Type::single(Atomic::TClassString(None));
}
let const_name = match expr_name_str(&cca.member) {
Some(n) => n.to_string(),
None => return Type::mixed(),
};
let fqcn = match &cca.class.kind {
ExprKind::Identifier(id) => {
let resolved = crate::db::resolve_name(self.db, &self.file, id.as_ref());
match resolved.as_str() {
"self" | "static" => {
let Some(self_fqcn) = &ctx.self_fqcn else {
return Type::mixed();
};
let here = crate::db::Fqcn::from_str(self.db, self_fqcn);
let found =
crate::db::find_class_constant_in_chain(self.db, here, &const_name);
// Inside a trait, `self::`/`static::CONST` may be
// defined on the using class via late static binding,
// not the trait itself — skip the undefined check.
if found.is_none()
&& !crate::db::has_unknown_ancestor(self.db, self_fqcn)
&& !crate::flow_state::self_is_trait(self.db, ctx)
{
self.emit(
IssueKind::UndefinedConstant {
name: format!("{self_fqcn}::{const_name}"),
},
Severity::Error,
expr_span,
);
}
if let Some((_, ref c)) = found {
if let Some(msg) = &c.deprecated {
self.emit(
IssueKind::DeprecatedConstant {
class: self_fqcn.to_string(),
constant: const_name.clone(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
cca.member.span,
);
}
}
let const_ty = found
.as_ref()
.map(|(_, c)| c.ty.clone())
.unwrap_or_else(Type::mixed);
// Key against the resolved *declaring* class (may be a
// trait providing the constant), not self_fqcn — see
// record_object_const_access for why.
let owner: Arc<str> = found
.as_ref()
.map(|(owner_fqcn, _)| owner_fqcn.clone())
.unwrap_or_else(|| self_fqcn.clone());
self.record_ref(
Arc::from(format!("cnst:{owner}::{const_name}")),
cca.member.span,
);
self.record_symbol(
cca.member.span,
ReferenceKind::ConstantAccess {
class: owner,
constant: Arc::from(const_name.as_str()),
},
const_ty.clone(),
);
return const_ty;
}
"parent" => {
let Some(parent_fqcn) = &ctx.parent_fqcn else {
if ctx.self_fqcn.is_some() {
self.emit(
IssueKind::ParentNotFound,
Severity::Error,
cca.class.span,
);
}
return Type::mixed();
};
let here = crate::db::Fqcn::from_str(self.db, parent_fqcn);
let found =
crate::db::find_class_constant_in_chain(self.db, here, &const_name);
if found.is_none() && !crate::db::has_unknown_ancestor(self.db, parent_fqcn)
{
self.emit(
IssueKind::UndefinedConstant {
name: format!("{parent_fqcn}::{const_name}"),
},
Severity::Error,
expr_span,
);
}
if let Some((_, ref c)) = found {
if let Some(msg) = &c.deprecated {
self.emit(
IssueKind::DeprecatedConstant {
class: parent_fqcn.to_string(),
constant: const_name.clone(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
cca.member.span,
);
}
}
let const_ty = found
.as_ref()
.map(|(_, c)| c.ty.clone())
.unwrap_or_else(Type::mixed);
// Key against the resolved *declaring* class (may be a
// trait providing the constant), not parent_fqcn — see
// record_object_const_access for why.
let owner: Arc<str> = found
.as_ref()
.map(|(owner_fqcn, _)| owner_fqcn.clone())
.unwrap_or_else(|| parent_fqcn.clone());
self.record_ref(
Arc::from(format!("cnst:{owner}::{const_name}")),
cca.member.span,
);
self.record_symbol(
cca.member.span,
ReferenceKind::ConstantAccess {
class: owner,
constant: Arc::from(const_name.as_str()),
},
const_ty.clone(),
);
return const_ty;
}
_ => resolved,
}
}
// `$obj::CONST` — derive the FQCN(s) from the object's inferred
// type, mirroring the `$obj::class` handling a few lines above.
// Without this, a constant read only through an object-instance
// variable was never checked (existence/visibility/deprecation)
// and never recorded as a usage. Also handles `$cls::CONST` where
// `$cls` holds a class-string (e.g. `$cls = self::class;`) — the
// same access form, just via a string rather than an instance.
ExprKind::Variable(var_name) => {
let obj_ty = ctx.get_var(var_name.as_ref());
let mut result = Type::empty();
let mut any = false;
for atomic in &obj_ty.types {
let fqcn = atomic.named_object_fqcn().or_else(|| match atomic {
Atomic::TClassString(Some(fqcn)) => Some(fqcn.as_ref()),
_ => None,
});
if let Some(fqcn) = fqcn {
any = true;
let const_ty = self.record_object_const_access(
fqcn,
&const_name,
cca.class.span,
cca.member.span,
expr_span,
ctx,
);
result.merge_with(&const_ty);
}
}
return if any { result } else { Type::mixed() };
}
_ => return Type::mixed(),
};
if !crate::db::class_exists(self.db, &fqcn) && !ctx.is_class_guarded(fqcn.as_str()) {
self.emit(
IssueKind::UndefinedClass { name: fqcn },
Severity::Error,
cca.class.span,
);
return Type::mixed();
}
// A trait can declare constants for the classes that `use` it (PHP
// 8.2+), but the trait itself is never a valid constant-access
// target — `HasFoo::FOO` is a hard fatal regardless of whether FOO
// exists, so this must short-circuit before the existence lookup
// below, which would otherwise treat the trait like any other class.
if crate::db::class_kind(self.db, &fqcn).is_some_and(|k| k.is_trait) {
self.emit(
IssueKind::TraitConstantAccessedDirectly {
trait_name: fqcn,
constant: const_name,
},
Severity::Error,
expr_span,
);
return Type::mixed();
}
self.record_ref(Arc::from(format!("cls:{fqcn}")), cca.class.span);
let here = crate::db::Fqcn::from_str(self.db, &fqcn);
// Check if the class is deprecated
if let Some(class) = crate::db::find_class_like(self.db, here) {
if let Some(msg) = class.deprecated() {
self.emit(
IssueKind::DeprecatedClass {
name: fqcn.clone(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
cca.class.span,
);
}
}
let here = crate::db::Fqcn::from_str(self.db, &fqcn);
let found = crate::db::find_class_constant_in_chain(self.db, here, &const_name);
// Key the `cnst:` reference against the resolved *declaring* class, not
// the literal receiver — see record_object_const_access for why.
let owner: Arc<str> = found
.as_ref()
.map(|(owner_fqcn, _)| owner_fqcn.clone())
.unwrap_or_else(|| Arc::from(fqcn.as_str()));
self.record_ref(
Arc::from(format!("cnst:{owner}::{const_name}")),
cca.member.span,
);
// Check if the constant is deprecated
if let Some((ref owner_fqcn, ref c)) = found {
if let Some(msg) = &c.deprecated {
self.emit(
IssueKind::DeprecatedConstant {
class: fqcn.clone(),
constant: const_name.clone(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
cca.member.span,
);
}
// Visibility check: private constants are only accessible from the
// declaring class; protected constants only from the declaring class
// or its subclasses.
use mir_codebase::definitions::Visibility;
let inaccessible = match c.visibility {
Some(Visibility::Private) => {
// Accessible only from the exact declaring class
ctx.self_fqcn
.as_deref()
.map(|s| !s.eq_ignore_ascii_case(owner_fqcn))
.unwrap_or(true)
}
Some(Visibility::Protected) => {
// Accessible from the declaring class or a subclass
let caller = ctx.self_fqcn.as_deref().unwrap_or("");
if caller.is_empty() {
true
} else {
!crate::db::extends_or_implements(self.db, caller, owner_fqcn)
&& !caller.eq_ignore_ascii_case(owner_fqcn)
}
}
_ => false,
};
if inaccessible {
self.emit(
IssueKind::InaccessibleClassConstant {
class: fqcn.clone(),
constant: const_name.clone(),
},
Severity::Error,
cca.member.span,
);
}
}
let const_ty = found
.as_ref()
.map(|(_, c)| c.ty.clone())
.unwrap_or_else(Type::mixed);
self.record_symbol(
cca.member.span,
ReferenceKind::ConstantAccess {
class: owner,
constant: Arc::from(const_name.as_str()),
},
const_ty.clone(),
);
if found.is_none() && !crate::db::has_unknown_ancestor(self.db, &fqcn) {
self.emit(
IssueKind::UndefinedConstant {
name: format!("{fqcn}::{const_name}"),
},
Severity::Error,
expr_span,
);
}
const_ty
}
/// Constant access through an object-typed receiver (`$obj::CONST`).
/// `fqcn` comes from the receiver's already-resolved type, so unlike the
/// class-name-token path in `analyze_class_const_access` there's no
/// separate `UndefinedClass` check here.
fn record_object_const_access(
&mut self,
fqcn: &str,
const_name: &str,
class_span: php_ast::Span,
member_span: php_ast::Span,
expr_span: php_ast::Span,
ctx: &FlowState,
) -> Type {
if crate::db::class_kind(self.db, fqcn).is_some_and(|k| k.is_trait) {
self.emit(
IssueKind::TraitConstantAccessedDirectly {
trait_name: fqcn.to_string(),
constant: const_name.to_string(),
},
Severity::Error,
expr_span,
);
return Type::mixed();
}
self.record_ref(Arc::from(format!("cls:{fqcn}")), class_span);
let here = crate::db::Fqcn::from_str(self.db, fqcn);
let found = crate::db::find_class_constant_in_chain(self.db, here, const_name);
// Key the `cnst:` reference against the resolved *declaring* class, not
// the literal receiver — a `Trait::CONST` access is never legal PHP, so
// a constant provided by a used trait is only ever read through the
// consuming class. Without this, find-references from the trait's own
// constant declaration never sees any of its external usages.
let owner: Arc<str> = found
.as_ref()
.map(|(owner_fqcn, _)| owner_fqcn.clone())
.unwrap_or_else(|| Arc::from(fqcn));
self.record_ref(
Arc::from(format!("cnst:{owner}::{const_name}")),
member_span,
);
if let Some((ref owner_fqcn, ref c)) = found {
if let Some(msg) = &c.deprecated {
self.emit(
IssueKind::DeprecatedConstant {
class: fqcn.to_string(),
constant: const_name.to_string(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
member_span,
);
}
use mir_codebase::definitions::Visibility;
let inaccessible = match c.visibility {
Some(Visibility::Private) => ctx
.self_fqcn
.as_deref()
.map(|s| !s.eq_ignore_ascii_case(owner_fqcn))
.unwrap_or(true),
Some(Visibility::Protected) => {
let caller = ctx.self_fqcn.as_deref().unwrap_or("");
if caller.is_empty() {
true
} else {
!crate::db::extends_or_implements(self.db, caller, owner_fqcn)
&& !caller.eq_ignore_ascii_case(owner_fqcn)
}
}
_ => false,
};
if inaccessible {
self.emit(
IssueKind::InaccessibleClassConstant {
class: fqcn.to_string(),
constant: const_name.to_string(),
},
Severity::Error,
member_span,
);
}
}
let const_ty = found
.as_ref()
.map(|(_, c)| c.ty.clone())
.unwrap_or_else(Type::mixed);
self.record_symbol(
member_span,
ReferenceKind::ConstantAccess {
class: owner,
constant: Arc::from(const_name),
},
const_ty.clone(),
);
if found.is_none() && !crate::db::has_unknown_ancestor(self.db, fqcn) {
self.emit(
IssueKind::UndefinedConstant {
name: format!("{fqcn}::{const_name}"),
},
Severity::Error,
expr_span,
);
}
const_ty
}
/// `p.ty`, falling back to a type inferred from what the declaring
/// constructor directly assigned this property, when it has no native
/// type hint and no `@var` docblock at all (`p.ty` is `None` only in
/// that case — see `PropertyDef::ty`). `owner` must be the property's
/// DECLARING class (`find_property_in_chain`'s owner), matching how
/// `record_property_inference` keyed it.
fn effective_property_ty(
&self,
owner: &Arc<str>,
prop_name: &str,
p: &mir_codebase::definitions::PropertyDef,
) -> Type {
p.ty.as_deref().cloned().unwrap_or_else(|| {
crate::db::inferred_property_type_demand(self.db, owner.as_ref(), prop_name)
.map(|t| (*t).clone())
.unwrap_or_else(Type::mixed)
})
}
/// Whether `ctx`'s scope is disallowed from reading a private/protected
/// property declared on `owner_fqcn` — same private/protected rules as
/// the class-constant checks in `analyze_class_const_access` /
/// `record_object_const_access` above.
fn property_inaccessible(
&self,
visibility: mir_codebase::definitions::Visibility,
owner_fqcn: &str,
ctx: &FlowState,
) -> bool {
use mir_codebase::definitions::Visibility;
match visibility {
Visibility::Private => ctx
.self_fqcn
.as_deref()
.map(|s| !s.eq_ignore_ascii_case(owner_fqcn))
.unwrap_or(true),
Visibility::Protected => {
let caller = ctx.self_fqcn.as_deref().unwrap_or("");
if caller.is_empty() {
true
} else {
!crate::db::extends_or_implements(self.db, caller, owner_fqcn)
&& !caller.eq_ignore_ascii_case(owner_fqcn)
}
}
Visibility::Public => false,
}
}
/// `declaring_class` is set to the FQCN of the class that declares the
/// property when the inheritance-chain lookup resolves it — reused by the
/// callers for symbol recording so the chain is only walked once.
pub(super) fn resolve_property_type(
&mut self,
obj_ty: &Type,
prop_name: &str,
span: php_ast::Span,
declaring_class: &mut Option<Arc<str>>,
ctx: &FlowState,
) -> Type {
for atomic in &obj_ty.types {
match atomic {
Atomic::TNamedObject { fqcn, type_params }
if crate::db::class_kind(self.db, fqcn.as_ref())
.is_some_and(|k| !k.is_interface && !k.is_trait && !k.is_enum) =>
{
let prop_result = crate::db::find_property_in_chain(
self.db,
crate::db::Fqcn::new(self.db, *fqcn),
prop_name,
);
if let Some((owner, p)) = prop_result {
if let Some(msg) = &p.deprecated {
self.emit(
IssueKind::DeprecatedProperty {
class: fqcn.to_string(),
property: prop_name.to_string(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
span,
);
}
if !self.in_existence_check
&& self.property_inaccessible(p.visibility, owner.as_ref(), ctx)
{
self.emit(
IssueKind::InaccessibleProperty {
class: owner.to_string(),
property: prop_name.to_string(),
},
Severity::Error,
span,
);
}
let ty = self.effective_property_ty(&owner, prop_name, &p);
// Substitute the receiver's own concrete type params (e.g.
// `Box<int>`'s `T → int`) into a property declared with a
// bare `@var T` — plus, when the property is inherited from
// an ancestor with its own separate template, resolve THAT
// ancestor's params through the same `@extends`/`@implements`
// chain walk used everywhere else for inherited bindings.
// Run this even when the receiver itself has no own type
// params (a bare subclass) — `inherited_template_bindings`
// still needs to resolve a `@extends Box<int>`-fixed
// ancestor template with no receiver-supplied args at all.
let class_tps = crate::db::class_template_params(self.db, fqcn.as_ref())
.unwrap_or_default();
let own_bindings =
crate::generic::build_class_bindings(&class_tps, type_params);
let inherited = crate::db::inherited_template_bindings(
self.db,
fqcn.as_ref(),
&own_bindings,
);
let mut substitution = own_bindings.clone();
if owner.as_ref() == fqcn.as_ref() {
// `prop_name` is declared directly on the receiver's own
// class — a bare template name in its docblock is the
// receiver's OWN template, so it must win over a
// same-named but unrelated ancestor template (only fill
// in names own_bindings doesn't have).
for (k, v) in inherited {
substitution.entry(k).or_insert(v);
}
} else {
// `prop_name` is inherited from `owner` — a bare template
// name in ITS docblock is scoped to `owner`'s own
// declaration, which the ancestor-chain walk resolves; it
// must win over a same-named receiver-own template.
substitution.extend(inherited);
}
// A bare `self`/`static`/`parent` in the property's OWN
// declared type (e.g. `@var self|null`) refers to `owner`
// itself, not a template placeholder — substitute_templates
// never touches it, so resolve it separately first using
// owner's own concrete type args (the receiver's, when the
// property is declared directly on the receiver's class).
let owner_type_params: Vec<Type> = if owner.as_ref() == fqcn.as_ref() {
type_params.to_vec()
} else {
crate::db::class_template_params(self.db, owner.as_ref())
.unwrap_or_default()
.iter()
.map(|tp| {
substitution
.get(&tp.name)
.cloned()
.unwrap_or_else(Type::mixed)
})
.collect()
};
let ty = rebind_self_static_parent(ty, owner.as_ref(), &owner_type_params);
let ty = ty.substitute_templates(&substitution);
self.record_ref(Arc::from(format!("prop:{}::{}", owner, prop_name)), span);
*declaring_class = Some(owner);
return ty;
}
let get_method = crate::db::find_method_in_chain(
self.db,
crate::db::Fqcn::from_str(self.db, fqcn.as_ref()),
"__get",
);
// `stdClass` permits arbitrary dynamic properties at
// runtime (json_decode results, DB rows, casts), so any
// `->prop` access is valid — never an UndefinedProperty.
let allows_dynamic = fqcn.as_ref().eq_ignore_ascii_case("stdClass");
if get_method.is_none()
&& !allows_dynamic
&& !crate::db::has_unknown_ancestor(self.db, fqcn.as_ref())
{
// Give a plugin (e.g. Eloquent `$casts`) a chance to
// supply the type before flagging the property undefined.
if let Some(ty) = self.class_property_from_plugin(fqcn.as_ref(), prop_name)
{
self.record_ref(
Arc::from(format!("prop:{}::{}", fqcn, prop_name)),
span,
);
*declaring_class = Some((*fqcn).into());
return ty;
}
if !self.in_existence_check {
self.emit(
IssueKind::UndefinedProperty {
class: fqcn.to_string(),
property: prop_name.to_string(),
},
Severity::Warning,
span,
);
}
}
return get_method
.and_then(|(_, m)| m.effective_return_type().cloned())
.unwrap_or_else(Type::mixed);
}
Atomic::TNamedObject { fqcn, .. }
if crate::db::class_kind(self.db, fqcn.as_ref())
.is_some_and(|k| k.is_trait) =>
{
// Inside a trait body $this is typed as the trait itself.
// Properties can be declared on the trait or inherited from
// trait ancestors. If not found, return mixed silently —
// the using class might supply the property.
let prop_result = crate::db::find_property_in_chain(
self.db,
crate::db::Fqcn::new(self.db, *fqcn),
prop_name,
);
if let Some((owner, p)) = prop_result {
let ty = self.effective_property_ty(&owner, prop_name, &p);
self.record_ref(Arc::from(format!("prop:{}::{}", owner, prop_name)), span);
*declaring_class = Some(owner);
return ty;
}
// The property may be supplied by whichever class ends up
// consuming this trait — record a per-trait marker so
// DeadCodeAnalyzer can credit any composing class's own
// private property of this name as used.
self.record_ref(Arc::from(format!("traituse:{fqcn}::{prop_name}")), span);
return Type::mixed();
}
Atomic::TNamedObject { fqcn, type_params }
if crate::db::class_kind(self.db, fqcn.as_ref())
.is_some_and(|k| k.is_interface) =>
{
if let Some(crate::db::ClassLike::Interface(iface)) = crate::db::find_class_like(
self.db,
crate::db::Fqcn::from_str(self.db, fqcn.as_ref()),
) {
// Real PHP semantics: interfaces (pre-8.4 property hooks)
// can't declare properties at all, so any access through a
// plain interface type is suspect regardless of whether the
// interface opted into @seal-properties — @property* tags
// are the only thing that legitimizes an access.
if !self.in_existence_check && !iface.own_properties.contains_key(prop_name)
{
self.emit(
IssueKind::NoInterfaceProperties {
property: prop_name.to_string(),
},
Severity::Info,
span,
);
}
if let Some(p) = iface.own_properties.get(prop_name) {
// Unlike the class/trait branches above, this never ran
// record_ref/set declaring_class — a `$x->prop` access
// through an interface-typed `$x` was invisible to
// find-references/hover and any dead-code exemption
// that keys off the property reference.
self.record_ref(
Arc::from(format!("prop:{}::{}", fqcn, prop_name)),
span,
);
*declaring_class = Some((*fqcn).into());
let ty = p.ty.as_deref().cloned().unwrap_or_else(Type::mixed);
// Substitute the receiver's own concrete type params
// into a `@property T $x` the same way the class
// branch above does — `own_properties` only ever
// returns THIS interface's own declaration, so there's
// no ancestor-vs-own distinction to make here.
let class_tps =
crate::db::class_template_params(self.db, fqcn.as_ref())
.unwrap_or_default();
let own_bindings =
crate::generic::build_class_bindings(&class_tps, type_params);
return ty.substitute_templates(&own_bindings);
}
}
return Type::mixed();
}
Atomic::TNamedObject { fqcn, .. }
if crate::db::class_kind(self.db, fqcn.as_ref()).is_some_and(|k| k.is_enum) =>
{
match prop_name {
"name" => return Type::single(Atomic::TNonEmptyString),
"value" => {
let here = crate::db::Fqcn::new(self.db, *fqcn);
if let Some(scalar_ty) = crate::db::find_class_like(self.db, here)
.and_then(|c| c.enum_scalar_type().cloned())
{
return scalar_ty;
}
if !self.in_existence_check {
self.emit(
IssueKind::UndefinedProperty {
class: fqcn.to_string(),
property: prop_name.to_string(),
},
Severity::Warning,
span,
);
}
return Type::mixed();
}
_ => {
let here = crate::db::Fqcn::new(self.db, *fqcn);
if let Some(crate::db::ClassLike::Enum(e)) =
crate::db::find_class_like(self.db, here)
{
if let Some(p) = e.own_properties.get(prop_name) {
self.record_ref(
Arc::from(format!("prop:{}::{}", fqcn, prop_name)),
span,
);
*declaring_class = Some((*fqcn).into());
return p.ty.as_deref().cloned().unwrap_or_else(Type::mixed);
}
}
if !self.in_existence_check {
self.emit(
IssueKind::UndefinedProperty {
class: fqcn.to_string(),
property: prop_name.to_string(),
},
Severity::Warning,
span,
);
}
return Type::mixed();
}
}
}
Atomic::TSelf { fqcn }
| Atomic::TStaticObject { fqcn }
| Atomic::TParent { fqcn } => {
// A variable/param holding a self/static/parent-typed value
// (not just `$this`, which is injected as a plain
// TNamedObject) — resolve the property the same way, minus
// template substitution (these atoms carry no type params
// of their own). Falls through to the loop's final
// `Type::mixed()` on a miss, matching prior silent behavior.
let prop_result = crate::db::find_property_in_chain(
self.db,
crate::db::Fqcn::new(self.db, *fqcn),
prop_name,
);
if let Some((owner, p)) = prop_result {
if let Some(msg) = &p.deprecated {
self.emit(
IssueKind::DeprecatedProperty {
class: fqcn.to_string(),
property: prop_name.to_string(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
span,
);
}
if !self.in_existence_check
&& self.property_inaccessible(p.visibility, owner.as_ref(), ctx)
{
self.emit(
IssueKind::InaccessibleProperty {
class: owner.to_string(),
property: prop_name.to_string(),
},
Severity::Error,
span,
);
}
let ty = self.effective_property_ty(&owner, prop_name, &p);
self.record_ref(Arc::from(format!("prop:{}::{}", owner, prop_name)), span);
*declaring_class = Some(owner);
return ty;
}
}
Atomic::TIntersection { parts } => {
for part in parts.iter() {
for inner_atomic in &part.types {
if let Atomic::TNamedObject { fqcn, .. } = inner_atomic {
let prop_result = crate::db::find_property_in_chain(
self.db,
crate::db::Fqcn::new(self.db, *fqcn),
prop_name,
);
if let Some((owner, p)) = prop_result {
self.record_ref(
Arc::from(format!("prop:{}::{}", owner, prop_name)),
span,
);
let ty = self.effective_property_ty(&owner, prop_name, &p);
*declaring_class = Some(owner);
return ty;
}
}
}
}
if !self.in_existence_check {
self.emit(
IssueKind::UndefinedProperty {
class: atomic.to_string(),
property: prop_name.to_string(),
},
Severity::Warning,
span,
);
}
return Type::mixed();
}
Atomic::TMixed => return Type::mixed(),
_ => {}
}
}
Type::mixed()
}
}