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
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
//! Class declarations: signature binding, inheritance validation, and the
//! method/constructor body pass. Mirrors the interface binder
//! ([`super::Inferer::bind_interface`]) for signatures and the function-body
//! pass ([`super::generic::Inferer::infer_functions`]) for bodies. Codegen is a
//! later slice (SUB-480+); this pass only typechecks.
use crate::compiler_error::CompilerFailure;
use std::collections::{BTreeMap, BTreeSet};
use std::ops::ControlFlow;
use crate::{
AccessorKind, AccessorSig, ClassMember, FieldSig, Ident, MangledName, MethodSig, Param, Span,
StmtKind, Type, TypeAnnotation, TypeKind, TypeSymbol, TypedClassAccessor,
TypedClassConstructor, TypedClassDecl, TypedClassField, TypedClassMethod, TypedParam,
Visibility,
};
use super::{Inferer, type_limit_at, type_limit_unlocated};
use crate::type_size::{TypeLimits, TypeTooLarge};
use super::assignable::ImplementsFailure;
use super::generic::{
erase_generic_params, erase_generic_params_in_expr, erase_generic_params_in_stmt,
substitute_typevars,
};
#[derive(Clone, Copy, PartialEq, Eq)]
enum RuntimeTestMode {
General,
AllowAliasRefs,
}
/// A static member found by [`Inferer::class_static_in_chain`].
pub(super) enum StaticResolution {
Method(MethodSig, Visibility),
Field(FieldSig),
}
/// One class's `implements` clause, held until every class signature is bound.
pub(in crate::typechecker) struct PendingImplements {
class_name: String,
mangled: MangledName,
generic_names: Vec<String>,
/// Each target's annotation span and resolved type. Non-interface targets
/// are already diagnosed and ride along as `Type::Error`.
targets: Vec<(Span, Type)>,
}
/// What a class's `extends` clause resolved to.
enum ExtendsTarget {
Absent,
/// A usable parent. Its member surface is known even when a diagnosed
/// type-argument error left the args erased.
Class(crate::ClassExtends),
/// The clause named something unusable — already diagnosed. Nothing is
/// known about what the class inherits (see
/// [`Inferer::unresolved_parents`]).
Unresolved,
}
/// An *instance* member of a class that has a parent, and so *might* redeclare
/// an inherited name — a method, a field (plain or parameter property), or an
/// accessor. Whether an ancestor actually declares the name, and at which kind,
/// is resolved by the checks themselves.
struct RedeclarationCandidate {
name: String,
span: Span,
child_class: MangledName,
kind: MemberKind,
/// For an accessor property, where each half is declared. `get x` and `set
/// x` are one property and one candidate, but they are checked against the
/// inherited accessor separately, and each mismatch has to point its caret
/// at the half that is wrong. Empty for every other kind.
accessor_spans: BTreeMap<AccessorKind, Span>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum MemberKind {
Method,
Field,
Accessor,
}
impl MemberKind {
/// How the kind is named in a diagnostic.
fn noun(self) -> &'static str {
match self {
MemberKind::Method => "method",
MemberKind::Field => "field",
MemberKind::Accessor => "accessor",
}
}
/// The indefinite article [`noun`](Self::noun) takes.
fn article(self) -> &'static str {
match self {
MemberKind::Accessor => "an",
MemberKind::Method | MemberKind::Field => "a",
}
}
}
/// The read and write types of a field-write target. They coincide for data
/// fields and diverge only for an accessor whose getter return type and setter
/// parameter type differ.
pub(super) struct FieldRw {
pub(super) read: Type,
pub(super) write: Type,
}
impl FieldRw {
pub(super) fn uniform(ty: Type) -> Self {
FieldRw {
read: ty.clone(),
write: ty,
}
}
}
impl<'a> Inferer<'a> {
pub(super) fn bind_class(
&mut self,
name: Ident,
generics: Vec<Ident>,
extends: Option<TypeAnnotation>,
implements: Vec<TypeAnnotation>,
members: Vec<ClassMember>,
doc: Option<crate::DocComment>,
) -> Result<(), CompilerFailure> {
let generic_names: Vec<String> = generics.iter().map(|g| g.name.clone()).collect();
// Push class-level generics so member annotations can name them. Generic
// classes are not otherwise resolved in v1 (rejected as type args in
// `resolve_type`), but a `class Box<T> { value: T }` still binds cleanly.
self.push_signature_generics(generic_names.clone());
let mangled = self.mangle_top_symbol(&name.name)?;
let extends_clause = match self.resolve_extends_target(extends.as_ref())? {
ExtendsTarget::Class(e) => {
if let Some(annot) = &extends
&& self.reject_private_constructor(
&e.parent,
super::expr::ConstructorUse::Extend,
annot.span,
)
{
self.hidden_parent_constructors.insert(mangled.clone());
}
Some(e)
}
ExtendsTarget::Absent => None,
ExtendsTarget::Unresolved => {
self.unresolved_parents.insert(mangled.clone());
None
}
};
let implements_types = self.resolve_implements_targets(&implements)?;
let implements_mangled: Vec<MangledName> = implements_types
.iter()
.filter_map(|t| match t.peel() {
Type::InterfaceRef { mangled, .. } => Some(mangled.clone()),
_ => None,
})
.collect();
let mut fields: BTreeMap<String, FieldSig> = BTreeMap::new();
let mut methods: BTreeMap<String, MethodSig> = BTreeMap::new();
let mut method_visibility: BTreeMap<String, Visibility> = BTreeMap::new();
let mut statics: BTreeMap<String, MethodSig> = BTreeMap::new();
let mut static_visibility: BTreeMap<String, Visibility> = BTreeMap::new();
let mut static_fields: BTreeMap<String, FieldSig> = BTreeMap::new();
let mut constructor: Vec<Param> = Vec::new();
let mut constructor_visibility = Visibility::Public;
let mut seen_constructor = false;
// Each `get`/`set` is its own declaration. `(property, is_setter)` guards
// duplicates; the property's `FieldSig` is updated incrementally below.
let mut accessor_sigs: Vec<AccessorSig> = Vec::new();
let mut seen_accessor: std::collections::BTreeSet<(String, bool)> =
std::collections::BTreeSet::new();
for member in &members {
match member {
ClassMember::Field {
name: f_name,
modifiers,
ty,
initializer,
doc: f_doc,
..
} if modifiers.static_span.is_some() => {
if self.reject_bad_static_name(&statics, &static_fields, f_name, &name) {
continue;
}
if initializer.is_none() {
self.error_with_help(
f_name.span,
"a static field must be initialized".to_string(),
vec![format!(
"add `= <value>` — there is no constructor moment to assign \
`{}.{}`",
name.name, f_name.name
)],
);
continue;
}
let resolved = self.resolve_type(ty)?;
if self.reject_class_generic_in_static(
f_name,
&generic_names,
&[],
std::iter::once(&resolved),
) {
continue;
}
static_fields.insert(
f_name.name.clone(),
FieldSig {
ty: resolved,
visibility: modifiers.visibility,
readonly: modifiers.readonly.is_some(),
optional: false,
doc: f_doc.clone(),
},
);
}
ClassMember::Method {
name: m_name,
modifiers,
optional,
generics: m_generics,
params,
return_type,
doc: m_doc,
..
} if modifiers.static_span.is_some() => {
if self.reject_bad_static_name(&statics, &static_fields, m_name, &name) {
continue;
}
let m_generic_names: Vec<String> =
m_generics.iter().map(|g| g.name.clone()).collect();
self.push_signature_generics(m_generic_names.clone());
let resolved_params: Vec<Param> = self.resolve_params(params)?;
let resolved_ret = self.resolve_type(return_type)?;
self.pop_signature_generics();
if self.reject_class_generic_in_static(
m_name,
&generic_names,
&m_generic_names,
resolved_params.iter().map(|p| &p.ty).chain([&resolved_ret]),
) {
continue;
}
statics.insert(
m_name.name.clone(),
MethodSig {
optional: *optional,
generics: m_generic_names,
params: resolved_params,
ret: resolved_ret,
predicate: None,
doc: m_doc.clone(),
},
);
static_visibility.insert(m_name.name.clone(), modifiers.visibility);
}
ClassMember::Field {
name: f_name,
modifiers,
optional,
ty,
doc: f_doc,
..
} => {
if self.reject_duplicate_member(&fields, &methods, f_name, &name) {
continue;
}
let resolved = self.resolve_type(ty)?;
fields.insert(
f_name.name.clone(),
FieldSig {
ty: resolved,
visibility: modifiers.visibility,
readonly: modifiers.readonly.is_some(),
optional: *optional,
doc: f_doc.clone(),
},
);
}
ClassMember::Method {
name: m_name,
modifiers,
optional,
generics: m_generics,
params,
return_type,
doc: m_doc,
..
} => {
if self.reject_duplicate_member(&fields, &methods, m_name, &name) {
continue;
}
let m_generic_names: Vec<String> =
m_generics.iter().map(|g| g.name.clone()).collect();
// Method-level generics on class methods have no codegen
// (the vtable slot would get a stub body that traps) —
// reject at bind time instead of at runtime. Class-level
// generics (`class Box<T>`) are fine.
if let Some(g) = m_generics.first() {
self.error_with_help(
g.span,
format!(
"type parameters on class instance methods are not \
supported yet (`{}<{}>`)",
m_name.name, g.name
),
vec![format!(
"move it to a top-level generic function \
(`function {}<{}>(self: {}, …)`), or make it \
`static {}<{}>(…)` — statics may declare their own \
type parameters",
m_name.name,
g.name,
if generic_names.is_empty() {
name.name.clone()
} else {
format!("{}<{}>", name.name, generic_names.join(", "))
},
m_name.name,
g.name
)],
);
}
self.push_signature_generics(m_generic_names.clone());
let resolved_params: Vec<Param> = self.resolve_params(params)?;
let resolved_ret = self.resolve_type(return_type)?;
self.pop_signature_generics();
self.check_conversion_method(
"class",
m_name,
&resolved_params,
&m_generic_names,
&resolved_ret,
);
methods.insert(
m_name.name.clone(),
MethodSig {
optional: *optional,
generics: m_generic_names,
params: resolved_params,
ret: resolved_ret,
predicate: None,
doc: m_doc.clone(),
},
);
method_visibility.insert(m_name.name.clone(), modifiers.visibility);
}
ClassMember::Constructor {
visibility,
params,
span,
..
} => {
if seen_constructor {
self.error(
*span,
format!("class `{}` declares more than one constructor", name.name),
);
continue;
}
seen_constructor = true;
constructor_visibility = *visibility;
constructor = self.resolve_parameter_types(params)?;
// Parameter properties declare a field with the param's type.
for (decl, resolved) in params.iter().zip(constructor.iter()) {
let Some(modifiers) = &decl.modifiers else {
continue;
};
if self.reject_duplicate_member(&fields, &methods, &decl.name, &name) {
continue;
}
let field_ty = match &decl.ty {
Some(annotation) => crate::ObjectField::widen_optional(
decl.optional,
self.resolve_type(annotation)?,
),
None if decl.default.is_some() => self
.typed_ast
.authored_parameter_types
.get(&(
decl.name.span.file.0,
decl.name.span.start,
decl.name.span.end,
))
.cloned()
.ok_or_else(|| {
super::inference_failure(
"missing inferred parameter-property source type",
)
.with_span(decl.name.span)
})?,
None => resolved.ty.clone(),
};
fields.insert(
decl.name.name.clone(),
FieldSig {
ty: field_ty,
visibility: modifiers.visibility,
readonly: modifiers.readonly.is_some(),
optional: false,
doc: None,
},
);
}
}
ClassMember::Accessor {
name: a_name,
modifiers,
kind,
param,
return_type,
span,
..
} => {
let is_setter = *kind == AccessorKind::Set;
// The first accessor for a property guards against a clash with a
// field or method of the same name.
let first = !seen_accessor.contains(&(a_name.name.clone(), false))
&& !seen_accessor.contains(&(a_name.name.clone(), true));
if !seen_accessor.insert((a_name.name.clone(), is_setter)) {
self.error(
*span,
format!(
"duplicate `{}` accessor `{}`",
if is_setter { "set" } else { "get" },
a_name.name
),
);
continue;
}
if first && self.reject_duplicate_member(&fields, &methods, a_name, &name) {
continue;
}
// A getter contributes the read type; a setter makes the property
// writable (its independent write type lives on the `AccessorSig`).
// The getter/setter read/write types are independent (TS 4.3+).
let visibility = modifiers.visibility;
match kind {
AccessorKind::Get => {
let ret_ty = return_type
.as_ref()
.map(|t| self.resolve_type(t))
.transpose()?
.unwrap_or(Type::Error);
fields
.entry(a_name.name.clone())
.and_modify(|f| f.ty = ret_ty.clone())
.or_insert_with(|| FieldSig {
ty: ret_ty.clone(),
visibility,
readonly: true,
optional: false,
doc: None,
});
accessor_sigs.push(AccessorSig::Getter {
name: a_name.name.clone(),
ret_ty,
});
}
AccessorKind::Set => {
let write_ty = param
.as_ref()
.and_then(|p| p.ty.as_ref())
.map(|t| self.resolve_type(t))
.transpose()?
.unwrap_or(Type::Error);
let param_name = param
.as_ref()
.map_or_else(|| "value".to_string(), |p| p.name.name.clone());
fields
.entry(a_name.name.clone())
.and_modify(|f| f.readonly = false)
.or_insert_with(|| FieldSig {
ty: write_ty.clone(),
visibility,
readonly: false,
optional: false,
doc: None,
});
accessor_sigs.push(AccessorSig::Setter {
name: a_name.name.clone(),
param: crate::Param {
name: param_name,
ty: write_ty,
optional: false,
default: None,
rest: false,
},
});
}
}
}
}
}
self.pop_signature_generics();
self.local_class_mangles.insert(mangled.clone());
let symbol = TypeSymbol {
name: name.name.clone(),
mangled_name: mangled.clone(),
declaration_span: name.span,
kind: TypeKind::Class {
generics: generic_names.clone(),
fields,
narrowing_checks: BTreeMap::new(),
methods,
method_visibility,
accessors: accessor_sigs,
constructor,
constructor_visibility,
statics,
static_visibility,
static_fields,
extends: extends_clause,
implements: implements_mangled,
doc,
},
};
self.types
.insert(name.name.clone(), self.package_name.to_string(), symbol);
// `implements` conformance needs every class signature bound — an
// inherited member may come from a parent declared further down the
// file — so the check itself is deferred to
// `check_pending_implements`.
self.pending_implements.push(PendingImplements {
class_name: name.name.clone(),
mangled,
generic_names,
targets: implements
.iter()
.map(|a| a.span)
.zip(implements_types)
.collect(),
});
Ok(())
}
/// Check that every class satisfies each interface it declares. Runs once
/// all class signatures are bound, so a member inherited from a
/// later-declared parent counts.
pub(super) fn check_pending_implements(&mut self) -> Result<(), CompilerFailure> {
for pending in std::mem::take(&mut self.pending_implements) {
// An unresolvable parent could have supplied any of the interface's
// members, so conformance is unknowable rather than broken.
if !self.inherits_unresolved_parent(&pending.mangled) {
self.check_class_implements(&pending)?;
}
let first_target = pending.targets.first().map(|(span, _)| *span);
self.type_size_checkpoint(first_target)?;
}
Ok(())
}
fn check_class_implements(
&mut self,
pending: &PendingImplements,
) -> Result<(), CompilerFailure> {
// A generic class is checked at fresh opaque parameters, applied to
// both sides, so `Box<T> implements Container<T>` still matches member
// for member while `Box<T> implements Container<string>` is caught —
// instantiating with bare `TypeVar`s would make both pass.
let class_args: Vec<Type> = pending
.generic_names
.iter()
.map(|name| self.fresh_generic_param(name))
.collect::<Result<_, _>>()?;
let opaque: BTreeMap<String, Type> = pending
.generic_names
.iter()
.cloned()
.zip(class_args.iter().cloned())
.collect();
for (span, iface_ty) in &pending.targets {
// Peeled to agree with `resolve_implements_targets`, which admits an
// aliased interface. An unpeeled match reads `type N = Named` as a
// non-interface and skips conformance with no diagnostic at all.
let Type::InterfaceRef {
mangled: iface_mangled,
name: iface_name,
args: iface_args,
..
} = iface_ty.peel()
else {
continue;
};
let iface_args: Vec<Type> = iface_args
.iter()
.map(|a| substitute_typevars(a, &opaque, &self.type_limits))
.collect::<Result<_, _>>()
.map_err(type_limit_at(*span))?;
let failures = self.resolver().implements_failures(
&pending.mangled,
&class_args,
iface_mangled,
iface_name,
&iface_args,
);
if !failures.is_empty() {
self.report_implements_failures(*span, &pending.class_name, iface_ty, &failures);
}
}
Ok(())
}
/// Render a class→interface conformance failure as an LLM-native diagnostic:
/// the message names the offending members, and the `help` block lifts the
/// interface's expected shape plus the class's actual signature for every
/// member whose type is incompatible.
fn report_implements_failures(
&mut self,
span: Span,
class_name: &str,
iface_ty: &Type,
failures: &[ImplementsFailure],
) {
let mut clauses: Vec<String> = Vec::new();
let mut help = vec![self.format_definition(iface_ty)];
for failure in failures {
match failure {
ImplementsFailure::Missing(member) => {
clauses.push(format!("missing member `{member}`"));
}
ImplementsFailure::Incompatible {
member,
expected,
actual,
} => {
clauses.push(format!("member `{member}` has an incompatible signature"));
help.push(format!(
"`{class_name}.{member}` is `{actual}`, but `{iface_ty}` declares it as `{expected}`"
));
}
ImplementsFailure::NotReadable { member, ty } => {
clauses.push(format!("member `{member}` is write-only (no getter)"));
help.push(format!(
"`{iface_ty}` requires a readable `{member}: {ty}`; add a \
`get {member}(): {ty}` accessor to `{class_name}`"
));
}
ImplementsFailure::NotWritable { member, ty } => {
clauses.push(format!("member `{member}` is not writable"));
// The interface-side fix leads because it is the one that always
// applies: the class member may be a method or a get-only
// accessor, neither of which takes a setter the way a field does.
help.push(format!(
"`{iface_ty}` declares `{member}: {ty}` as settable, but \
`{class_name}.{member}` only reads — declare the interface \
property `readonly {member}: {ty}`, or make the class member \
writable (a non-`readonly` field, or a \
`set {member}(value: {ty})` accessor)"
));
}
ImplementsFailure::OptionalityMismatch { member, ty } => {
clauses.push(format!("member `{member}` is optional"));
help.push(format!(
"`{iface_ty}` requires `{member}: {ty}`, but \
`{class_name}.{member}` is declared `{member}?: {ty}` — \
drop the `?` on the class, or mark the interface \
property `{member}?: {ty}`"
));
}
}
}
self.error_with_help(
span,
format!(
"class `{class_name}` does not implement `{iface_ty}`: {}",
clauses.join(", ")
),
help,
);
}
fn reject_duplicate_member(
&mut self,
fields: &BTreeMap<String, FieldSig>,
methods: &BTreeMap<String, MethodSig>,
member: &Ident,
class: &Ident,
) -> bool {
if fields.contains_key(&member.name) || methods.contains_key(&member.name) {
self.error(
member.span,
format!(
"duplicate member `{}` on class `{}`",
member.name, class.name
),
);
return true;
}
false
}
/// Duplicate-or-reserved check for the statics namespace. Statics and instance
/// members live in disjoint namespaces, so a static may share a name with an
/// instance member (TS-compatible) — only other statics collide.
fn reject_bad_static_name(
&mut self,
statics: &BTreeMap<String, MethodSig>,
static_fields: &BTreeMap<String, FieldSig>,
member: &Ident,
class: &Ident,
) -> bool {
if statics.contains_key(&member.name) || static_fields.contains_key(&member.name) {
self.error(
member.span,
format!(
"duplicate static member `{}` on class `{}`",
member.name, class.name
),
);
return true;
}
if matches!(member.name.as_str(), "prototype" | "name" | "length") {
self.error_with_help(
member.span,
format!(
"static member `{}` conflicts with a built-in class property",
member.name
),
vec![
"TypeScript reserves `prototype`, `name`, and `length` on class objects; \
pick another name"
.to_string(),
],
);
return true;
}
false
}
/// A static runs without an instance, so the class's type parameters have no
/// binding there (TS rule). Method-level generics shadow class generics and
/// stay allowed.
fn reject_class_generic_in_static<'t>(
&mut self,
member: &Ident,
class_generics: &[String],
method_generics: &[String],
signature_types: impl Iterator<Item = &'t Type> + Clone,
) -> bool {
let mentioned = class_generics
.iter()
.filter(|g| !method_generics.contains(g))
.find(|g| {
signature_types
.clone()
.any(|ty| signature_mentions_typevar(ty, g))
});
let Some(g) = mentioned else {
return false;
};
self.error_with_help(
member.span,
format!(
"static member `{}` cannot reference class type parameter `{g}`",
member.name
),
vec![format!(
"a static runs without an instance, so the class's `{g}` has no binding; \
declare the parameter on the method itself: `static {}<{g}>(…)`",
member.name
)],
);
true
}
/// Recover the parent of an `extends` clause whose type arguments failed to
/// resolve, instantiated at erased args so member lookup still works.
/// `None` when the clause named no class at all — the caller then treats the
/// whole inherited surface as unknown.
fn errored_extends_parent(&self, annot: &TypeAnnotation) -> Option<crate::ClassExtends> {
let name = match &annot.kind {
crate::TypeAnnotationKind::Name { name, .. } => name.name.clone(),
crate::TypeAnnotationKind::Qualified { path, .. } => path
.iter()
.map(|s| s.name.as_str())
.collect::<Vec<&str>>()
.join("."),
_ => return None,
};
self.lookup_named_type(&name).and_then(|s| match &s.kind {
TypeKind::Class { generics, .. } => Some(crate::ClassExtends {
parent: s.mangled_name.clone(),
// `Error`, not `unknown`: inherited members come back poisoned
// so operations on them stay silent, instead of drawing a
// second diagnostic that advises narrowing an `unknown`.
args: vec![Type::Error; generics.len()],
}),
_ => None,
})
}
fn resolve_extends_target(
&mut self,
extends: Option<&TypeAnnotation>,
) -> Result<ExtendsTarget, CompilerFailure> {
let Some(annot) = extends else {
return Ok(ExtendsTarget::Absent);
};
// Runs inside the class's signature-generics scope, so a generic
// parent's args may name the child's own type params
// (`class Tagged<T> extends Box<T>` → args `[TypeVar(T)]`).
// Arity/void violations surface in `resolve_class_reference` and come
// back as `Type::Error`.
let ty = self.resolve_type(annot)?;
Ok(match ty.peel() {
Type::ClassRef { mangled, args, .. } => ExtendsTarget::Class(crate::ClassExtends {
parent: mangled.clone(),
args: args.clone(),
}),
// The clause named a real class but got its type arguments wrong.
// That error is already reported; keep the parent link (at erased
// args) so `super(...)` and inherited members still resolve —
// dropping it would bury the real diagnostic under a pile of
// "requires a parent class" / "field does not exist" follow-ons.
Type::Error => match self.errored_extends_parent(annot) {
Some(parent) => ExtendsTarget::Class(parent),
None => ExtendsTarget::Unresolved,
},
other => {
let other = other.clone();
self.error_with_help(
annot.span,
format!(
"a class can only `extends` another class, but `{other}` is not a class"
),
vec![
"to share a shape without inheritance, use `implements` with an interface"
.to_string(),
],
);
ExtendsTarget::Unresolved
}
})
}
/// Resolve each `implements` target to its `Type`. Non-interface targets are
/// diagnosed and resolved to `Type::Error` so positions line up with the
/// annotation list (the caller derives mangled names and conformance from these).
fn resolve_implements_targets(
&mut self,
implements: &[TypeAnnotation],
) -> Result<Vec<Type>, CompilerFailure> {
let mut out = Vec::new();
for annot in implements {
let ty = self.resolve_type(annot)?;
match ty.peel() {
Type::InterfaceRef { .. } | Type::Error => out.push(ty),
other => {
let other = other.clone();
self.error_with_help(
annot.span,
format!("a class can only `implements` an interface, but `{other}` is not an interface"),
vec!["`extends` a class for inheritance; `implements` lists interfaces".to_string()],
);
out.push(Type::Error);
}
}
}
Ok(out)
}
/// Reject `extends` cycles and signature-incompatible overrides. Runs after
/// every class signature is bound so parent chains are fully resolvable.
pub(super) fn check_class_inheritance(
&mut self,
top_level: &[crate::StmtId],
) -> Result<(), CompilerFailure> {
// (class name, `extends` annotation span) for every class with a parent.
let extending: Vec<(String, Span)> = top_level
.iter()
.map(|id| {
Ok::<_, CompilerFailure>(
match &self.ast.try_stmt(*id).map_err(super::arena_failure)?.kind {
StmtKind::ClassDecl {
name,
extends: Some(ext),
..
} => Some((name.name.clone(), ext.span)),
_ => None,
},
)
})
.filter_map(Result::transpose)
.collect::<Result<_, _>>()?;
for (class_name, ext_span) in &extending {
let Some(start) = self.class_mangled(class_name) else {
continue;
};
let mut chain = vec![start.clone()];
let mut parent = self.class_parent(&start);
let mut cyclic = false;
while let Some(p) = parent {
if chain.contains(&p) {
cyclic = true;
break;
}
if chain.len() >= crate::compiler_limits::MAX_CLASS_CHAIN_LEN {
return Err(CompilerFailure::Limit {
stage: crate::compiler_error::CompilerStage::Infer,
span: Some(*ext_span),
message: format!(
"class `{class_name}` has more than {} classes in its inheritance \
chain, counting itself and every ancestor",
crate::compiler_limits::MAX_CLASS_CHAIN_LEN
),
help: vec![
"flatten the hierarchy, or compose behavior instead of extending"
.into(),
],
});
}
chain.push(p.clone());
parent = self.class_parent(&p);
}
self.type_size_checkpoint(Some(*ext_span))?;
if cyclic {
self.invalid_class_hierarchies.insert(start);
self.error_with_help(
*ext_span,
format!(
"circular inheritance: class `{class_name}` is part of an `extends` cycle"
),
vec![
"classes form a single-inheritance tree; break the cycle so no class is its own ancestor"
.to_string(),
],
);
}
}
self.resolve_implicit_constructors(top_level)?;
self.check_member_redeclarations(top_level)?;
Ok(())
}
/// A subclass with no `constructor` member inherits the nearest ancestor's
/// constructor signature, so `new Sub(...)` and `super(...)` check against it
/// (codegen forwards the same params to the parent init). Runs after every
/// class signature is bound, so the parent chain is fully resolvable.
fn resolve_implicit_constructors(
&mut self,
top_level: &[crate::StmtId],
) -> Result<(), CompilerFailure> {
let has_explicit = |members: &[ClassMember]| {
members
.iter()
.any(|m| matches!(m, ClassMember::Constructor { .. }))
};
let explicit_ctor: std::collections::BTreeSet<MangledName> = top_level
.iter()
.map(|id| {
Ok::<_, CompilerFailure>(
match &self.ast.try_stmt(*id).map_err(super::arena_failure)?.kind {
StmtKind::ClassDecl { name, members, .. } if has_explicit(members) => {
self.class_mangled(&name.name)
}
_ => None,
},
)
})
.filter_map(Result::transpose)
.collect::<Result<_, _>>()?;
let implicit: Vec<(String, MangledName)> = top_level
.iter()
.map(|id| {
Ok::<_, CompilerFailure>(
match &self.ast.try_stmt(*id).map_err(super::arena_failure)?.kind {
StmtKind::ClassDecl {
name,
members,
extends: Some(_),
..
} if !has_explicit(members) => self
.class_mangled(&name.name)
.map(|m| (name.name.clone(), m)),
_ => None,
},
)
})
.filter_map(Result::transpose)
.collect::<Result<_, _>>()?;
for (child_name, child) in implicit {
// An unresolvable parent, or one whose constructor is private to
// another module, takes its constructor signature with it: stand in a
// variadic one so `new Sub(…)` accepts whatever the program passes
// rather than reporting an arity the class never had.
let inherited = if self.hidden_parent_constructors.contains(&child) {
Some(erased_constructor())
} else {
self.nearest_explicit_ctor(&child, &explicit_ctor)
.or_else(|| {
self.inherits_unresolved_parent(&child)
.then(erased_constructor)
})
};
if let Some((params, visibility)) = inherited
&& let Some(sym) = self.types.lookup_mut(&child_name)
&& let TypeKind::Class {
constructor,
constructor_visibility,
..
} = &mut sym.kind
{
*constructor = params;
*constructor_visibility = visibility;
}
}
Ok(())
}
/// Constructor signature and visibility of the nearest ancestor of `child`
/// that declares an explicit constructor (cycle-guarded), the signature
/// substituted at the bindings the intervening extends clauses instantiate —
/// an implicit subclass of a generic parent stores concrete ctor params. The
/// implicit constructor is the inherited one, so a `private` one stays
/// private, as in TypeScript. An implicit local ancestor whose own parent's
/// constructor is hidden from it yields the erased stand-in instead. `None`
/// when no ancestor declares one.
fn nearest_explicit_ctor(
&self,
child: &MangledName,
explicit_ctor: &std::collections::BTreeSet<MangledName>,
) -> Option<(Vec<Param>, Visibility)> {
use super::generic::substitute_typevars;
self.walk_ancestors(child, |sym, bindings| {
let p = &sym.mangled_name;
// An imported ancestor's `constructor` field already holds its
// effective (possibly inherited) params, resolved in its own package —
// so any imported ancestor is a valid stopping point, the same way a
// local ancestor with an explicit constructor is.
let imported = !self.local_class_mangles.contains(p);
if !imported && !explicit_ctor.contains(p) {
// An implicit local ancestor that may not use its parent's
// constructor stands in for it: walking past would reach the
// private one, and this pass may not have filled its own yet.
return if self.hidden_parent_constructors.contains(p) {
ControlFlow::Break(Some(erased_constructor()))
} else {
ControlFlow::Continue(())
};
}
let TypeKind::Class {
constructor,
constructor_visibility,
..
} = &sym.kind
else {
return ControlFlow::Break(None);
};
let visibility = *constructor_visibility;
let params = constructor
.iter()
.map(|param| {
Ok(Param {
ty: substitute_typevars(¶m.ty, bindings, &self.type_limits)?,
..param.clone()
})
})
.collect();
ControlFlow::Break(
self.type_limits
.ok_or_record(params)
.map(|params| (params, visibility)),
)
})
}
fn check_member_redeclarations(
&mut self,
top_level: &[crate::StmtId],
) -> Result<(), CompilerFailure> {
for member in self.redeclaration_candidates(top_level)? {
// A cross-kind redeclaration has no same-kind check to run — the
// ancestor walk each one does looks for its own kind and would sail
// past the declaration that actually collides.
if self.reported_cross_kind_redeclaration(&member)? {
continue;
}
match member.kind {
MemberKind::Method => self.check_method_override(&member)?,
MemberKind::Field => self.check_field_redeclaration(&member)?,
MemberKind::Accessor => self.check_accessor_redeclaration(&member)?,
}
self.type_size_checkpoint(Some(member.span))?;
}
Ok(())
}
/// Every instance member of every class that has a parent, in source order —
/// except a class's accessor properties, which land last, by property name,
/// since the get/set pair is collected into one candidate after the walk.
/// Materialized rather than checked in place because the walk borrows the
/// AST out of `self`, while the checks need `self` mutably to report.
fn redeclaration_candidates(
&self,
top_level: &[crate::StmtId],
) -> Result<Vec<RedeclarationCandidate>, CompilerFailure> {
let mut found: Vec<RedeclarationCandidate> = Vec::new();
for id in top_level {
let StmtKind::ClassDecl {
name: class_name,
members,
..
} = &self.ast.try_stmt(*id).map_err(super::arena_failure)?.kind
else {
continue;
};
let Some(child_class) = self.class_mangled(&class_name.name) else {
continue;
};
// Only classes with a parent can redeclare.
if self.class_parent(&child_class).is_none() {
continue;
}
let redeclared =
|name: &crate::Ident, span: Span, kind: MemberKind| RedeclarationCandidate {
name: name.name.clone(),
span,
child_class: child_class.clone(),
kind,
accessor_spans: BTreeMap::new(),
};
// `get x` and `set x` are one property under one name, and the
// checks run per property, so the pair contributes one candidate —
// built after the member walk, once both halves' spans are known.
let mut accessor_candidates: BTreeMap<&str, RedeclarationCandidate> = BTreeMap::new();
for member in members {
match member {
ClassMember::Method {
name,
modifiers,
span,
..
} if modifiers.static_span.is_none() => {
found.push(redeclared(name, *span, MemberKind::Method));
}
ClassMember::Field {
name,
modifiers,
span,
..
} if modifiers.static_span.is_none() => {
found.push(redeclared(name, *span, MemberKind::Field));
}
ClassMember::Accessor {
name,
modifiers,
kind,
span,
..
} if modifiers.static_span.is_none() => {
accessor_candidates
.entry(name.name.as_str())
.or_insert_with(|| redeclared(name, *span, MemberKind::Accessor))
.accessor_spans
.insert(*kind, *span);
}
// A parameter property declares a field just as a `Field`
// member does, and codegen lays it out identically — so it
// shadows identically and needs the same check.
ClassMember::Constructor { params, .. } => found.extend(
params
.iter()
.filter(|p| p.modifiers.is_some())
.map(|p| redeclared(&p.name, p.name.span, MemberKind::Field)),
),
// Statics live in their own namespace and share no slot with
// anything inherited.
ClassMember::Method { .. }
| ClassMember::Field { .. }
| ClassMember::Accessor { .. } => {}
}
}
found.extend(accessor_candidates.into_values());
}
Ok(found)
}
/// Reject a member that redeclares an inherited name at a *different* kind.
/// The two never unify: an accessor over an inherited field leaves the field
/// winning every access and the accessor bodies dead, a field over an
/// inherited accessor appends a second, independent property under one name,
/// and a field over an inherited method leaves `c.v` and `p.v()` naming
/// different members.
fn reported_cross_kind_redeclaration(
&mut self,
member: &RedeclarationCandidate,
) -> Result<bool, CompilerFailure> {
let opaque = self.opaque_own_generics(&member.child_class)?;
let Some((inherited_kind, owner)) =
self.ancestor_member_kind(&member.child_class, &member.name, &opaque)
else {
return Ok(false);
};
if inherited_kind == member.kind {
return Ok(false);
}
let owner_name = self.class_name_of(&owner);
let (child, parent) = (member.kind.noun(), inherited_kind.noun());
self.error_with_help(
member.span,
format!(
"`{}` redeclares an inherited {parent} as {} {child}",
member.name,
member.kind.article()
),
vec![
format!("inherited: {parent} `{}` on `{owner_name}`", member.name),
format!(
"a redeclaration shares the inherited member's storage or vtable slot, so it \
has to keep its kind — declare `{}` as {} {parent}, or rename it",
member.name,
inherited_kind.article()
),
],
);
Ok(true)
}
/// An accessor redeclaring an inherited accessor shares its vtable slot, so
/// the slot's recorded signature is the *base* declarer's: a getter whose
/// return doesn't fit it (or a setter that won't accept what the inherited
/// one does) miscompiles rather than dispatching.
fn check_accessor_redeclaration(
&mut self,
member: &RedeclarationCandidate,
) -> Result<(), CompilerFailure> {
let opaque = self.opaque_own_generics(&member.child_class)?;
for own in self.class_own_accessors(&member.child_class, &member.name) {
let Some(inherited) = self.ancestor_accessor(&member.child_class, &own, &opaque) else {
continue;
};
let Some(cmp) =
accessor_comparison(&member.name, &own, &inherited, &opaque, &self.type_limits)
.map_err(type_limit_at(member.span))?
else {
continue;
};
if super::assignable(&cmp.subtype, &cmp.supertype, self.resolver()) {
continue;
}
let span = member
.accessor_spans
.get(&cmp.half)
.copied()
.unwrap_or(member.span);
self.error_with_help(
span,
format!(
"accessor `{}` is not compatible with the inherited accessor",
cmp.accessor
),
vec![
format!("inherited: {}", cmp.inherited),
format!("redeclared: {}", cmp.redeclared),
format!(
"the two share one vtable slot — keep the inherited signature, or rename \
`{}`",
member.name
),
],
);
}
Ok(())
}
/// The class's own getter and setter for `name` (either may be absent).
fn class_own_accessors(&self, mangled: &MangledName, name: &str) -> Vec<AccessorSig> {
let Some(sym) = self.class_by_mangled(mangled) else {
return Vec::new();
};
let TypeKind::Class { accessors, .. } = &sym.kind else {
return Vec::new();
};
accessors
.iter()
.filter(|a| a.name() == name)
.cloned()
.collect()
}
/// Nearest ancestor's accessor matching `own`'s half (getter against getter,
/// setter against setter), substituted at the bindings the child's `extends`
/// clause instantiates.
fn ancestor_accessor(
&self,
child: &MangledName,
own: &AccessorSig,
own_bindings: &BTreeMap<String, Type>,
) -> Option<AccessorSig> {
let name = own.name().to_string();
let want_getter = matches!(own, AccessorSig::Getter { .. });
self.walk_ancestors_at(child, own_bindings, |sym, bindings| {
let TypeKind::Class { accessors, .. } = &sym.kind else {
return ControlFlow::Continue(());
};
let found = accessors.iter().find(|a| {
a.name() == name && matches!(a, AccessorSig::Getter { .. }) == want_getter
});
match found {
Some(sig) => {
ControlFlow::Break(self.type_limits.ok_or_record(substitute_accessor_sig(
sig,
bindings,
&self.type_limits,
)))
}
// A class that redeclares the property's other half but not this
// one still leaves this half inherited from further up.
None => ControlFlow::Continue(()),
}
})
}
/// The kind the nearest ancestor declares `name` at, with the class that
/// declares it.
fn ancestor_member_kind(
&self,
child: &MangledName,
name: &str,
own_bindings: &BTreeMap<String, Type>,
) -> Option<(MemberKind, MangledName)> {
self.walk_ancestors_at(child, own_bindings, |sym, _| {
match declared_member_kind(sym, name) {
Some(kind) => ControlFlow::Break(Some((kind, sym.mangled_name.clone()))),
None => ControlFlow::Continue(()),
}
})
}
fn check_method_override(
&mut self,
member: &RedeclarationCandidate,
) -> Result<(), CompilerFailure> {
let Some(child_sig) = self.class_method_sig(&member.child_class, &member.name) else {
return Ok(());
};
// A generic declared on the method itself is not in this map and keeps
// its existing (lenient) treatment.
let opaque = self.opaque_own_generics(&member.child_class)?;
let Some(parent_sig) = self.ancestor_method_sig(&member.child_class, &member.name, &opaque)
else {
return Ok(());
};
let child_fn = substitute_typevars(&method_fn_type(&child_sig), &opaque, &self.type_limits)
.map_err(type_limit_at(member.span))?;
let parent_fn = method_fn_type(&parent_sig);
// TypeScript lets an override declare fewer parameters, as any function
// may. Here the override fills the inherited method's vtable slot, whose
// Wasm signature is fixed, so it must declare them all.
if child_sig.params.len() < parent_sig.params.len() {
self.error_with_help(
member.span,
format!(
"override of method `{}` must declare the inherited method's {} parameter(s)",
member.name,
parent_sig.params.len()
),
vec![
format!("inherited: {parent_fn}"),
format!("override: {child_fn}"),
"declare the parameters it ignores too".to_string(),
],
);
return Ok(());
}
if !super::assignable(&child_fn, &parent_fn, self.resolver()) {
self.error_with_help(
member.span,
format!(
"override of method `{}` is not compatible with the inherited signature",
member.name
),
vec![
format!("inherited: {parent_fn}"),
format!("override: {child_fn}"),
],
);
}
Ok(())
}
/// A redeclared field shadows the inherited one into a single property
/// sharing one payload slot, so a parent-typed receiver reads the child's
/// value through the *parent's* declared type, and a parent method writes
/// the child's storage. Sound only if the child's type still satisfies the
/// parent's, and only if the redeclaration doesn't reach storage it has no
/// business naming.
fn check_field_redeclaration(
&mut self,
member: &RedeclarationCandidate,
) -> Result<(), crate::compiler_error::CompilerFailure> {
let Some(child_field) = self.class_own_field_sig(&member.child_class, &member.name) else {
return Ok(());
};
let opaque = self.opaque_own_generics(&member.child_class)?;
let Some((parent_field, parent_class)) =
self.ancestor_field_decl(&member.child_class, &member.name, &opaque)
else {
return Ok(());
};
let child_ty =
substitute_typevars(&field_read_ty(&child_field), &opaque, &self.type_limits)
.map_err(type_limit_at(member.span))?;
let parent_ty = field_read_ty(&parent_field);
if !super::assignable(&child_ty, &parent_ty, self.resolver()) {
self.error_with_help(
member.span,
format!(
"field `{}` is not compatible with the inherited declaration",
member.name
),
vec![
format!("inherited: {}: {parent_ty}", member.name),
format!("redeclared: {}: {child_ty}", member.name),
format!(
"give `{}` a type assignable to `{parent_ty}`, or rename it",
member.name
),
],
);
return Ok(());
}
// `private` is module-scoped, so a field private to another module is a
// name this class cannot see — yet the shared slot would hand it write
// access to that module's encapsulated state.
if parent_field.visibility != Visibility::Public
&& !self.local_class_mangles.contains(&parent_class)
{
let owner = self.class_name_of(&parent_class);
self.error_with_help(
member.span,
format!(
"field `{}` redeclares a field that is private to another module",
member.name
),
vec![format!(
"the two would share one storage slot, so this would alias state \
`{owner}` encapsulates — rename the field"
)],
);
return Ok(());
}
if child_field.visibility != parent_field.visibility {
let inherited = visibility_keyword(parent_field.visibility);
self.error_with_help(
member.span,
format!(
"field `{}` redeclares an inherited field at a different visibility",
member.name
),
vec![
format!("inherited: {inherited} {}", member.name),
format!(
"redeclared: {} {}",
visibility_keyword(child_field.visibility),
member.name
),
format!("declare `{}` as `{inherited}`, or rename it", member.name),
],
);
}
self.record_narrowing_check(member, &child_ty, &opaque)?;
Ok(())
}
/// Records the read guard for a redeclaration that *narrows* the inherited
/// type — see [`crate::FieldNarrowingCheck`] for what it buys.
///
/// Mutual assignability means no narrowing and so no guard: the parent
/// cannot write anything the child does not already admit.
fn record_narrowing_check(
&mut self,
member: &RedeclarationCandidate,
child_ty: &Type,
opaque: &BTreeMap<String, Type>,
) -> Result<(), crate::compiler_error::CompilerFailure> {
// Against the *widest* ancestor, not the nearest: the slot is shared with
// every declaration above, so an intermediate class narrowing it first
// must not shrink what this guard defends against.
let Some((widest_field, widest_class)) =
self.widest_ancestor_field_decl(&member.child_class, &member.name, opaque)
else {
return Ok(());
};
let parent_ty = field_read_ty(&widest_field);
if super::assignable(&parent_ty, child_ty, self.resolver()) {
return Ok(());
}
let Some(test) = self.narrowing_test(&parent_ty, child_ty) else {
return Ok(());
};
let child_name = self.class_name_of(&member.child_class);
let parent_name = self.class_name_of(&widest_class);
let field = &member.name;
let check = crate::FieldNarrowingCheck {
declaration: Some(member.child_class.clone()),
minimal_test_target: (self.array_representation_distinguishes(&parent_ty, child_ty)
|| (matches!(test, crate::FieldNarrowingTest::NonNull)
&& !type_mentions_erased_parameter(child_ty)))
.then(|| child_ty.clone()),
test,
message: format!(
"field `{field}` holds a value its declaration does not admit: \
`{child_name}.{field}: {child_ty}` narrows the inherited \
`{parent_name}.{field}: {parent_ty}` and the two share one storage slot, \
so code that only sees the inherited declaration can write it"
),
};
self.field_narrowing_checks
.insert((member.child_class.clone(), field.clone()), check.clone());
let _: () = if let Some(symbol) = self.types.lookup_mut(&child_name)
&& let TypeKind::Class {
narrowing_checks, ..
} = &mut symbol.kind
{
narrowing_checks.insert(field.clone(), check);
};
Ok(())
}
/// Only skip the element walk when every array the ancestor admits also
/// satisfies the child. Unknown, structural, and other erased alternatives
/// require the full validator because they can conceal incompatible arrays.
fn array_representation_distinguishes(&self, parent: &Type, child: &Type) -> bool {
let child_non_null = super::narrowing::strip_null(child);
if !matches!(child_non_null.peel(), Type::Array(_)) {
return false;
}
match parent.peel() {
Type::Union(members) => members
.iter()
.all(|member| self.array_representation_distinguishes(member, child)),
Type::Array(_) | Type::Tuple(_) => super::assignable(parent, child, self.resolver()),
Type::Null
| Type::Undefined
| Type::Number
| Type::NumberLiteral(_)
| Type::Boolean
| Type::BooleanLiteral(_)
| Type::String
| Type::StringLiteral(_)
| Type::BigInt
| Type::BigIntLiteral(_) => true,
_ => false,
}
}
/// What the read has to verify, or `None` when nothing it can lower would.
/// Prefers [`crate::FieldNarrowingTest::NonNull`] when stripping `null` is the
/// whole difference — see the variant for why that is worth a case of its own
/// — and otherwise tests structural conformance to the narrowed type.
/// Interfaces retain a descriptor for both data properties and methods;
/// data-only interfaces simply carry an empty method set.
///
/// `None` is not a safe default, only the status quo: for a leaf whose Wasm
/// lowering the parent's value also satisfies the bare cast *succeeds* and the
/// wrong-typed value escapes to fail somewhere else. Widening the allowlist
/// shrinks that hole.
fn narrowing_test(
&self,
parent_ty: &Type,
child_ty: &Type,
) -> Option<crate::FieldNarrowingTest> {
// A presence check can never reject a value the child's declaration
// admits, so it is sound whenever that declaration rejects `null`. An
// erased type parameter cannot promise that here — `Sub<T>`'s `v: T` is
// `string | null` at `Sub<string | null>` — but it does not have to:
// `emit_narrowed_field_read` re-asks at the read, where the substitution
// is known, and skips the test when the read's own type admits `null`.
let child_rejects_null = !super::expr::type_admits_null(child_ty, self.resolver());
// Reaching here means the parent is not assignable to the child, so if
// every *non-null* parent value is, `null` is the whole difference and
// presence is the complete check.
let parent_non_null = super::narrowing::strip_null(parent_ty);
if child_rejects_null && super::assignable(&parent_non_null, child_ty, self.resolver()) {
return Some(crate::FieldNarrowingTest::NonNull);
}
if crate::typed_ast::field_runtime_type_is_testable(child_ty) {
return Some(crate::FieldNarrowingTest::Shape(child_ty.peel().clone()));
}
if let Some(test) = self.interface_narrowing_test(child_ty) {
return Some(crate::FieldNarrowingTest::Interface(test));
}
if type_mentions_erased_parameter(child_ty) {
return Some(crate::FieldNarrowingTest::Substituted);
}
// Nothing in `runtime_type_is_testable`, no interface metadata, and no
// erased parameter to re-ask at the read. Presence still catches the
// part of the narrowing that removes `null`.
(child_rejects_null && super::expr::type_admits_null(parent_ty, self.resolver()))
.then_some(crate::FieldNarrowingTest::NonNull)
}
pub(super) fn interface_narrowing_test(
&self,
child_ty: &Type,
) -> Option<crate::InterfaceNarrowingTest> {
let (interface_ty, nullable, undefined) = match child_ty.peel() {
Type::InterfaceRef { .. } => (child_ty.peel(), false, false),
Type::Union(members) => {
let nullable = members
.iter()
.any(|member| matches!(member.peel(), Type::Null));
let undefined = members
.iter()
.any(|member| matches!(member.peel(), Type::Undefined));
let mut non_null = members
.iter()
.filter(|member| !matches!(member.peel(), Type::Null | Type::Undefined));
let interface = non_null.next()?;
if non_null.next().is_some() {
return None;
}
(interface.peel(), nullable, undefined)
}
_ => return None,
};
let Type::InterfaceRef {
mangled,
name,
args,
package,
..
} = interface_ty
else {
return None;
};
let members = self.resolver().interface_full_form(mangled, name, args)?;
let crate::TypeKind::Interface {
methods, dispatch, ..
} = &self.resolver().lookup(mangled, name)?.kind
else {
return None;
};
let target = interface_ty.clone();
let non_shape_carriers =
self.non_shape_interface_carriers(&target, package, name, dispatch, &members);
Some(crate::InterfaceNarrowingTest {
index: self.resolver().index_signature(interface_ty),
members,
methods: methods.keys().cloned().collect(),
shape_allowed: *dispatch == crate::Dispatch::VTable
|| non_shape_carriers.contains(&crate::InterfaceCarrier::ObjectShape),
non_shape_carriers,
nullable,
undefined,
})
}
fn non_shape_interface_carriers(
&self,
target: &Type,
package: &crate::Package,
name: &str,
dispatch: &crate::Dispatch,
members: &std::collections::BTreeMap<String, crate::ObjectField>,
) -> std::collections::BTreeSet<crate::InterfaceCarrier> {
let mut carriers = self.primitive_interface_carriers(target);
carriers.extend(self.collection_interface_carriers(target, name, members));
carriers.extend(self.direct_interface_carriers(package, name, dispatch));
carriers
}
fn primitive_interface_carriers(
&self,
target: &Type,
) -> std::collections::BTreeSet<crate::InterfaceCarrier> {
let mut carriers = std::collections::BTreeSet::new();
for (carrier, ty) in [
(crate::InterfaceCarrier::Number, Type::Number),
(crate::InterfaceCarrier::Boolean, Type::Boolean),
(crate::InterfaceCarrier::String, Type::String),
(crate::InterfaceCarrier::BigInt, Type::BigInt),
(crate::InterfaceCarrier::Uint8Array, Type::Uint8Array),
] {
if super::assignable(&ty, target, self.resolver()) {
carriers.insert(carrier);
}
}
carriers
}
fn collection_interface_carriers(
&self,
target: &Type,
name: &str,
members: &std::collections::BTreeMap<String, crate::ObjectField>,
) -> std::collections::BTreeSet<crate::InterfaceCarrier> {
let target_args = match target.peel() {
Type::InterfaceRef { args, .. } => args.as_slice(),
_ => &[],
};
let candidates = runtime_carrier_candidates(members);
let mut carriers =
self.array_and_set_interface_carriers(target, name, target_args, &candidates, members);
carriers.extend(self.map_interface_carriers(
target,
name,
target_args,
&candidates,
members,
));
carriers
}
/// How the instantiations of a collection carrier relate to `target`, where
/// that can be decided without trying each one. A field typed as a union of
/// hundreds of literals makes hundreds of candidate arguments, and `Map`
/// tries every pair of them.
///
/// Member names do not depend on type arguments, so a missing required
/// member, or a weak target sharing no member with the carrier, rules out
/// every instantiation. When none of the carrier members the target names
/// mentions the carrier's type parameters, and the target has no index
/// signature constraining member types, every instantiation compares the
/// same members, so one answers for all.
fn carrier_fit(
&self,
template: &Type,
target: &Type,
target_members: &std::collections::BTreeMap<String, crate::ObjectField>,
) -> CarrierFit {
let Some((mangled, _, name, args)) = template.interface_routing() else {
return CarrierFit::TryEach;
};
let Some(form) = self.resolver().interface_full_form(&mangled, name, &args) else {
return CarrierFit::TryEach;
};
if target_members
.iter()
.any(|(member, field)| !field.optional && !form.contains_key(member))
{
return CarrierFit::None;
}
let weak = !target_members.is_empty() && target_members.values().all(|f| f.optional);
if weak && !form.is_empty() && !target_members.keys().any(|k| form.contains_key(k)) {
return CarrierFit::None;
}
// An index signature of `unknown` admits every member of every
// instantiation: only `void` is not assignable to `unknown`, and no
// candidate is `void`.
let index_constrains_members = self
.resolver()
.index_signature(target)
.is_some_and(|index| !matches!(index.value.peel(), Type::Unknown));
if index_constrains_members
|| self.carrier_members_mention_parameters(&mangled, name, target_members)
{
return CarrierFit::TryEach;
}
if super::assignable(template, target, self.resolver()) {
CarrierFit::Every
} else {
CarrierFit::None
}
}
/// Whether any member of the carrier interface `name` that `target_members`
/// also names mentions one of the carrier's type parameters. True when the
/// declaration cannot be read, which keeps the per-instantiation search.
fn carrier_members_mention_parameters(
&self,
mangled: &MangledName,
name: &str,
target_members: &std::collections::BTreeMap<String, crate::ObjectField>,
) -> bool {
let Some(symbol) = self.resolver().lookup(mangled, name) else {
return true;
};
let TypeKind::Interface {
generics,
methods,
properties,
..
} = &symbol.kind
else {
return true;
};
let mentions = |ty: &Type| {
generics
.iter()
.any(|generic| signature_mentions_typevar(ty, generic))
};
target_members.keys().any(|member| {
methods.get(member).is_some_and(|sig| {
sig.params.iter().any(|param| mentions(¶m.ty)) || mentions(&sig.ret)
}) || properties
.get(member)
.is_some_and(|property| mentions(&property.ty))
})
}
fn array_and_set_interface_carriers(
&self,
target: &Type,
name: &str,
target_args: &[Type],
candidates: &[Type],
members: &std::collections::BTreeMap<String, crate::ObjectField>,
) -> std::collections::BTreeSet<crate::InterfaceCarrier> {
let mut carriers = std::collections::BTreeSet::new();
let exact_element = matches!(name, "Iterable" | "Set")
.then(|| target_args.first())
.flatten();
if let Some(element) = exact_element {
let array = Type::Array(Box::new(element.clone()));
if super::assignable(&array, target, self.resolver()) {
carriers.insert(crate::InterfaceCarrier::Array(array));
}
let candidate = Type::prelude_interface("Set".to_string(), vec![element.clone()]);
if super::assignable(&candidate, target, self.resolver()) {
carriers.insert(crate::InterfaceCarrier::Set(element.clone()));
}
} else {
// Candidate instantiations only answer whether the backing's
// non-generic surface (for example `length`) satisfies the target.
// When every instantiation matches, the target leaves contents
// unconstrained and an `Any` carrier is sound. Otherwise retain
// only the matching instantiations and validate their contents.
let array_fit =
self.carrier_fit(&Type::Array(Box::new(Type::Unknown)), target, members);
let array_matches = array_fit.matching(candidates, |element| {
let array = Type::Array(Box::new(element.clone()));
let tuple = Type::Tuple(vec![element.clone()].into());
super::assignable(&array, target, self.resolver())
|| super::assignable(&tuple, target, self.resolver())
});
if array_matches.len() == candidates.len() {
carriers.insert(crate::InterfaceCarrier::ArrayAny);
} else {
carriers.extend(
array_matches.into_iter().map(|element| {
crate::InterfaceCarrier::Array(Type::Array(Box::new(element)))
}),
);
}
let set_fit = self.carrier_fit(
&Type::prelude_interface("Set".to_string(), vec![Type::Unknown]),
target,
members,
);
let set_matches = set_fit.matching(candidates, |element| {
let set = Type::prelude_interface("Set".to_string(), vec![element.clone()]);
super::assignable(&set, target, self.resolver())
});
if set_matches.len() == candidates.len() {
carriers.insert(crate::InterfaceCarrier::SetAny);
} else {
carriers.extend(set_matches.into_iter().map(crate::InterfaceCarrier::Set));
}
}
carriers
}
fn map_interface_carriers(
&self,
target: &Type,
name: &str,
target_args: &[Type],
candidates: &[Type],
members: &std::collections::BTreeMap<String, crate::ObjectField>,
) -> std::collections::BTreeSet<crate::InterfaceCarrier> {
let mut carriers = std::collections::BTreeSet::new();
let exact_map_pair = if name == "Map" {
target_args.first().zip(target_args.get(1))
} else if name == "Iterable" {
target_args
.first()
.and_then(|element| match element.peel() {
Type::Tuple(items) if items.len() == 2 => items.first().zip(items.get(1)),
_ => None,
})
} else {
None
};
if let Some((key, value)) = exact_map_pair {
let candidate =
Type::prelude_interface("Map".to_string(), vec![key.clone(), value.clone()]);
if super::assignable(&candidate, target, self.resolver()) {
carriers.insert(crate::InterfaceCarrier::Map(key.clone(), value.clone()));
}
} else {
let fit = self.carrier_fit(
&Type::prelude_interface("Map".to_string(), vec![Type::Unknown, Type::Unknown]),
target,
members,
);
match fit {
CarrierFit::None => {}
CarrierFit::Every => {
carriers.insert(crate::InterfaceCarrier::MapAny);
}
CarrierFit::TryEach => {
let map_matches: Vec<(Type, Type)> = candidates
.iter()
.flat_map(|key| {
candidates.iter().filter_map(|value| {
let map = Type::prelude_interface(
"Map".to_string(),
vec![key.clone(), value.clone()],
);
super::assignable(&map, target, self.resolver())
.then(|| (key.clone(), value.clone()))
})
})
.collect();
if map_matches.len() == candidates.len() * candidates.len() {
carriers.insert(crate::InterfaceCarrier::MapAny);
} else {
carriers.extend(
map_matches
.into_iter()
.map(|(key, value)| crate::InterfaceCarrier::Map(key, value)),
);
}
}
}
}
carriers
}
fn direct_interface_carriers(
&self,
package: &crate::Package,
name: &str,
dispatch: &crate::Dispatch,
) -> std::collections::BTreeSet<crate::InterfaceCarrier> {
let mut carriers = std::collections::BTreeSet::new();
if *dispatch != crate::Dispatch::VTable {
match name {
"RegExp" => {
carriers.insert(crate::InterfaceCarrier::RegExp);
}
"RegExpMatch" => {
carriers.insert(crate::InterfaceCarrier::RegExpMatch);
}
"Temporal.Instant" => {
carriers.insert(crate::InterfaceCarrier::TemporalInstant);
}
"Temporal.Duration" => {
carriers.insert(crate::InterfaceCarrier::TemporalDuration);
}
"Temporal.ZonedDateTime" => {
carriers.insert(crate::InterfaceCarrier::TemporalZonedDateTime);
}
"Temporal.PlainDate" => {
carriers.insert(crate::InterfaceCarrier::TemporalPlainDate);
}
"Temporal.PlainTime" => {
carriers.insert(crate::InterfaceCarrier::TemporalPlainTime);
}
"Temporal.PlainDateTime" => {
carriers.insert(crate::InterfaceCarrier::TemporalPlainDateTime);
}
"Temporal.PlainYearMonth" => {
carriers.insert(crate::InterfaceCarrier::TemporalPlainYearMonth);
}
"Temporal.PlainMonthDay" => {
carriers.insert(crate::InterfaceCarrier::TemporalPlainMonthDay);
}
"TextEncoder" | "TextDecoder" => {
carriers.insert(crate::InterfaceCarrier::ObjectShape);
}
_ => {}
}
let host_carrier = match (package.as_str(), name) {
("submilli:fs", "Stat") => Some(crate::InterfaceCarrier::FsStat),
("submilli:fs", "Peek") => Some(crate::InterfaceCarrier::FsPeek),
("submilli:fs", "DirEntry") => Some(crate::InterfaceCarrier::FsDirEntry),
("submilli:fs", "Info") => Some(crate::InterfaceCarrier::FsInfo),
("submilli:fs", "MountInfo") => Some(crate::InterfaceCarrier::FsMountInfo),
("submilli:fs", "FileWriter") => Some(crate::InterfaceCarrier::FsFileWriter),
("submilli:http", "Response") => Some(crate::InterfaceCarrier::HttpResponse),
("submilli:http", "DownloadResult") => {
Some(crate::InterfaceCarrier::HttpDownloadResult)
}
("submilli:session", "Entry") => Some(crate::InterfaceCarrier::SessionEntry),
("submilli:session", "Page") => Some(crate::InterfaceCarrier::SessionPage),
("submilli:url", "URL") => Some(crate::InterfaceCarrier::Url),
_ => None,
};
carriers.extend(host_carrier);
}
carriers
}
pub(super) fn record_runtime_type_test(&mut self, ty: &Type) -> Result<(), CompilerFailure> {
self.record_runtime_type_test_inner(ty, RuntimeTestMode::General, &mut BTreeSet::new())?;
Ok(())
}
fn record_runtime_type_test_inner(
&mut self,
ty: &Type,
mode: RuntimeTestMode,
active_interfaces: &mut BTreeSet<MangledName>,
) -> Result<(), CompilerFailure> {
let key = super::generic::erase_generic_params(ty.peel());
if let Some(existing) = self.typed_ast.runtime_type_tests.get(&key) {
if mode == RuntimeTestMode::AllowAliasRefs
&& matches!(existing, crate::FieldNarrowingTest::Representation)
&& crate::typed_ast::field_runtime_type_is_testable(&key)
{
self.typed_ast
.runtime_type_tests
.insert(key.clone(), crate::FieldNarrowingTest::Shape(key));
}
return Ok(());
}
// Break recursive interface discovery conservatively. A later outer
// call replaces this placeholder with the resolved descriptor.
self.typed_ast
.runtime_type_tests
.insert(key.clone(), crate::FieldNarrowingTest::Representation);
self.record_runtime_test_dependencies(&key, active_interfaces)?;
self.record_runtime_class_fields(&key, active_interfaces)?;
let testable = if mode == RuntimeTestMode::AllowAliasRefs {
crate::typed_ast::field_runtime_type_is_testable(&key)
} else {
crate::typed_ast::runtime_type_is_testable(&key)
};
let test = if let Some(members) = self.enum_runtime_members(&key) {
crate::FieldNarrowingTest::Shape(members)
} else if let Some(interface) = self.interface_narrowing_test(&key) {
let interface_identity = match key.peel() {
Type::InterfaceRef { mangled, .. } => Some(mangled.clone()),
Type::Union(members) => members.iter().find_map(|member| match member.peel() {
Type::InterfaceRef { mangled, .. } => Some(mangled.clone()),
_ => None,
}),
_ => None,
};
if let Some(identity) = interface_identity.as_ref()
&& !active_interfaces.insert(identity.clone())
{
self.record_generic_interface_validators(&interface, identity)?;
crate::FieldNarrowingTest::Interface(interface)
} else {
if let Some(index) = &interface.index {
self.record_runtime_type_test_inner(
&index.value,
RuntimeTestMode::AllowAliasRefs,
active_interfaces,
)?;
}
for member in interface.members.values() {
self.record_runtime_type_test_inner(
&member.ty,
RuntimeTestMode::AllowAliasRefs,
active_interfaces,
)?;
}
if let Some(identity) = interface_identity {
active_interfaces.remove(&identity);
}
crate::FieldNarrowingTest::Interface(interface)
}
} else if testable {
crate::FieldNarrowingTest::Shape(key.clone())
} else {
crate::FieldNarrowingTest::Representation
};
self.typed_ast.runtime_type_tests.insert(key, test);
Ok(())
}
pub(super) fn enum_runtime_members(&self, ty: &Type) -> Option<Type> {
let (Type::NumberEnum { mangled, .. } | Type::StringEnum { mangled, .. }) = ty else {
return None;
};
// A member type `E.A` holds its own value alone.
if let Some(value) = ty.enum_member_value() {
return Some(value.literal_type());
}
let symbol = self
.type_registry
.lookup(mangled)
.or_else(|| self.types.lookup_by_mangled(mangled))?;
let members = match &symbol.kind {
TypeKind::NumberEnum { variants, .. } => variants
.iter()
.map(|(_, value)| Type::NumberLiteral(crate::types::LiteralF64(*value)))
.collect(),
TypeKind::StringEnum { variants, .. } => variants
.iter()
.map(|(_, value)| Type::StringLiteral(value.clone()))
.collect(),
_ => return None,
};
Some(Type::union(members))
}
fn record_runtime_class_fields(
&mut self,
ty: &Type,
active: &mut BTreeSet<MangledName>,
) -> Result<(), CompilerFailure> {
let Type::ClassRef { mangled, args, .. } = ty else {
return Ok(());
};
// Diagnosed source cycles have no runtime descriptor; compilation will
// return their diagnostics. Unexplained dependency cycles remain fatal.
if self.invalid_class_hierarchies.contains(mangled) {
return Ok(());
}
if !active.insert(mangled.clone()) {
self.typed_ast
.runtime_class_fields
.insert(ty.clone(), Type::Never);
return Ok(());
}
let mut fields = BTreeMap::new();
let mut guards = Vec::new();
let mut contexts = Vec::new();
let mut chain = Vec::new();
for_each_class_in_chain(
|name| self.class_by_mangled(name),
&self.type_limits,
mangled,
args,
|symbol, bindings| chain.push((symbol.clone(), bindings.clone())),
)
.ok_or_else(|| {
self.pending_limit_or(super::inference_failure(
"incomplete runtime class metadata",
))
})?;
for (symbol, bindings) in &chain {
let TypeKind::Class {
generics,
fields: declared,
narrowing_checks,
accessors,
..
} = &symbol.kind
else {
return Err(super::inference_failure(
"runtime class metadata is not a class",
));
};
if !generics.is_empty() {
contexts.push(crate::typed_ast::InstanceTypeContext {
declaration: symbol.mangled_name.clone(),
args: generics
.iter()
.map(|name| {
bindings.get(name).cloned().ok_or_else(|| {
super::inference_failure("missing runtime class generic binding")
})
})
.collect::<Result<_, _>>()?,
});
}
for (name, check) in narrowing_checks {
let field = declared
.get(name)
.ok_or_else(|| super::inference_failure("missing guarded-field signature"))?;
guards.push(crate::typed_ast::InstantiatedFieldGuard {
field: name.clone(),
target: substitute_typevars(&field_read_ty(field), bindings, &self.type_limits)
.map_err(type_limit_unlocated)?,
check: check.clone(),
});
}
for (name, field) in declared {
if accessors.iter().any(|accessor| accessor.name() == name) {
continue;
}
if let std::collections::btree_map::Entry::Vacant(entry) =
fields.entry(name.clone())
{
entry.insert(crate::ObjectField {
ty: substitute_typevars(&field.ty, bindings, &self.type_limits)
.map_err(type_limit_unlocated)?,
optional: field.optional,
readonly: field.readonly,
method: false,
});
}
}
}
self.typed_ast
.runtime_class_contexts
.insert(ty.clone(), contexts);
self.typed_ast
.runtime_field_guards
.insert(ty.clone(), guards.clone());
for guard in guards {
self.record_runtime_type_test_inner(
&guard.target,
RuntimeTestMode::AllowAliasRefs,
active,
)?;
}
let shape = Type::Object {
index: None,
fields,
};
self.typed_ast
.runtime_class_fields
.insert(ty.clone(), shape.clone());
self.record_runtime_type_test_inner(&shape, RuntimeTestMode::AllowAliasRefs, active)?;
active.remove(mangled);
Ok(())
}
fn record_runtime_test_dependencies(
&mut self,
ty: &Type,
active_interfaces: &mut BTreeSet<MangledName>,
) -> Result<(), CompilerFailure> {
let mut record = |dependency: &Type| {
self.record_runtime_type_test_inner(
dependency,
RuntimeTestMode::AllowAliasRefs,
active_interfaces,
)
};
match ty.peel() {
Type::Array(element) => record(element)?,
Type::Tuple(elements) => {
for element in elements {
record(element)?;
}
}
Type::Union(elements) | Type::ClassRef { args: elements, .. } => {
for element in elements {
record(element)?;
}
}
Type::Object { fields, index } => {
if let Some(i) = index {
record(&i.value)?;
}
for field in fields.values() {
record(&field.ty)?;
}
}
Type::Function { params, ret, .. } => {
for param in params {
record(param)?;
}
record(ret)?;
}
_ => {}
}
Ok(())
}
fn record_generic_interface_validators(
&mut self,
interface: &crate::InterfaceNarrowingTest,
identity: &MangledName,
) -> Result<(), CompilerFailure> {
let mut references = BTreeSet::new();
for member in interface.members.values() {
collect_interface_instantiations(&member.ty, identity, &mut references);
}
for reference in references {
let Type::InterfaceRef {
mangled,
name,
args,
..
} = &reference
else {
continue;
};
let Some(symbol) = self.resolver().lookup(mangled, name) else {
continue;
};
let TypeKind::Interface { generics, .. } = &symbol.kind else {
continue;
};
if args.is_empty() {
continue;
}
let mut key = reference.clone();
if let Type::InterfaceRef { args, .. } = &mut key {
*args = generics.iter().cloned().map(Type::TypeVar).collect();
}
self.record_runtime_type_test_inner(
&key,
RuntimeTestMode::AllowAliasRefs,
&mut BTreeSet::new(),
)?;
}
Ok(())
}
fn narrowing_check_for(
&self,
class: &MangledName,
field: &str,
) -> Option<Box<crate::FieldNarrowingCheck>> {
self.field_narrowing_checks
.get(&(class.clone(), field.to_string()))
.cloned()
.map(Box::new)
}
fn class_name_of(&mut self, mangled: &MangledName) -> String {
self.class_by_mangled(mangled)
.map_or_else(|| mangled.to_string(), |sym| sym.name.clone())
}
/// The class's own type parameters as fresh opaque [`Type::GenericParam`]s,
/// keyed by name for [`substitute_typevars`]. Same guard
/// `check_class_implements` uses: comparing at bare `TypeVar`s would make
/// every parameterized member match everything.
fn opaque_own_generics(
&mut self,
mangled: &MangledName,
) -> Result<BTreeMap<String, Type>, CompilerFailure> {
let Some(sym) = self.class_by_mangled(mangled) else {
return Ok(BTreeMap::new());
};
let TypeKind::Class { generics, .. } = &sym.kind else {
return Ok(BTreeMap::new());
};
generics
.clone()
.into_iter()
.map(|g| {
let opaque = self.fresh_generic_param(&g)?;
Ok((g, opaque))
})
.collect()
}
/// The mangled name of a class declared with `name`, if it resolves to a class.
fn class_mangled(&self, name: &str) -> Option<MangledName> {
let sym = self.types.lookup(name)?;
matches!(sym.kind, TypeKind::Class { .. }).then(|| sym.mangled_name.clone())
}
/// Resolve a class symbol by its mangled name — current-module classes live
/// in the type namespace, imported parents in the FQN registry.
pub(super) fn class_by_mangled(&self, mangled: &MangledName) -> Option<TypeSymbol> {
if let Some(sym) = self.type_registry.lookup(mangled)
&& matches!(sym.kind, TypeKind::Class { .. })
{
return Some(sym.clone());
}
self.types
.iter_names()
.filter_map(|n| self.types.lookup(n))
.find(|s| &s.mangled_name == mangled && matches!(s.kind, TypeKind::Class { .. }))
.cloned()
}
/// Walk the `extends` chain from `start` (instantiated at `start_args`),
/// yielding each class symbol with the type-parameter bindings active AT
/// that class. Cycle-guarded.
///
/// `visit` returns [`ControlFlow::Continue`] to keep climbing, or
/// `Break(answer)` to stop — `Break(None)` being "this class settles the
/// question, with nothing to report" (a hidden member shadowing an
/// inherited one, say).
fn walk_class_chain<T>(
&self,
start: &MangledName,
start_args: &[Type],
visit: impl FnMut(&TypeSymbol, &BTreeMap<String, Type>) -> ControlFlow<Option<T>>,
) -> Option<T> {
walk_class_chain_with(
|m| self.class_by_mangled(m),
&self.type_limits,
start,
start_args,
visit,
)
}
/// [`walk_class_chain`](Self::walk_class_chain) starting at `child`'s
/// parent — for questions about what a class *inherits*, where the class
/// itself must not answer (override compatibility, an implicit
/// constructor's inherited signature).
fn walk_ancestors<T>(
&self,
child: &MangledName,
visit: impl FnMut(&TypeSymbol, &BTreeMap<String, Type>) -> ControlFlow<Option<T>>,
) -> Option<T> {
let sym = self.class_by_mangled(child)?;
self.walk_ancestors_at(child, &identity_bindings(&sym), visit)
}
/// [`walk_ancestors`](Self::walk_ancestors) with the child's own type
/// parameters bound to something other than themselves. Comparing an
/// inherited member against a redeclaration needs both sides instantiated
/// at the *same* opaque parameters: left as bare `TypeVar`s, either side
/// makes [`super::assignable`] answer `true` unconditionally.
fn walk_ancestors_at<T>(
&self,
child: &MangledName,
own_bindings: &BTreeMap<String, Type>,
visit: impl FnMut(&TypeSymbol, &BTreeMap<String, Type>) -> ControlFlow<Option<T>>,
) -> Option<T> {
let sym = self.class_by_mangled(child)?;
// The child stands at its own parameters, so its extends-args resolve
// through them before the walk proper begins.
let (parent, parent_args) = self
.type_limits
.ok_or_record(parent_hop(&sym, own_bindings, &self.type_limits))
.flatten()?;
self.walk_class_chain(&parent, &parent_args, visit)
}
/// True when this class or an ancestor failed to resolve its `extends`
/// clause. That parent could have declared any member, so a member that
/// looks missing here is unknowable rather than wrong — callers report
/// nothing and resolve to [`Type::Error`] instead
/// (see [`Inferer::unresolved_parents`]).
pub(super) fn inherits_unresolved_parent(&self, class_mangled: &MangledName) -> bool {
if self.unresolved_parents.is_empty() {
return false;
}
self.walk_class_chain(class_mangled, &[], |sym, _| {
if self.unresolved_parents.contains(&sym.mangled_name) {
ControlFlow::Break(Some(()))
} else {
ControlFlow::Continue(())
}
})
.is_some()
}
/// [`inherits_unresolved_parent`](Self::inherits_unresolved_parent) for a
/// receiver type: true only for a class instance with an unknowable
/// inherited surface.
pub(super) fn receiver_inherits_unresolved_parent(&self, receiver_ty: &Type) -> bool {
match receiver_ty.peel() {
Type::ClassRef { mangled, .. } => self.inherits_unresolved_parent(mangled),
_ => false,
}
}
/// [`inherits_unresolved_parent`](Self::inherits_unresolved_parent) for the
/// class whose body is being checked — the question `super(...)` and
/// `super.method(...)` ask before reporting a missing parent.
fn current_class_inherits_unresolved_parent(&self) -> bool {
self.current_class
.as_ref()
.is_some_and(|ty| self.receiver_inherits_unresolved_parent(ty))
}
/// True inside a class whose parent's constructor is private to another
/// module (see [`Inferer::hidden_parent_constructors`]).
fn current_class_hides_parent_constructor(&self) -> bool {
matches!(
self.current_class.as_ref().map(Type::peel),
Some(Type::ClassRef { mangled, .. })
if self.hidden_parent_constructors.contains(mangled)
)
}
/// A class field visible at the current access site: it exists on the class
/// or an ancestor, and is either public or declared in the current module
/// (module-scoped privacy). Returns `None` for a missing or hidden field.
/// The field type comes back with the declaring class's generics
/// substituted from `class_args`.
pub(super) fn class_field_visible(
&self,
class_mangled: &MangledName,
class_args: &[Type],
field: &str,
) -> Option<(FieldSig, MangledName)> {
self.walk_class_chain(class_mangled, class_args, |sym, bindings| {
let TypeKind::Class { fields, .. } = &sym.kind else {
return ControlFlow::Break(None);
};
let Some(f) = fields.get(field) else {
return ControlFlow::Continue(());
};
let m = &sym.mangled_name;
// A private field still shadows an inherited one of the same name:
// the walk stops here either way.
if f.visibility != Visibility::Public && !self.local_class_mangles.contains(m) {
return ControlFlow::Break(None);
}
let Some(ty) = self
.type_limits
.ok_or_record(super::generic::substitute_typevars(
&f.ty,
bindings,
&self.type_limits,
))
else {
return ControlFlow::Break(None);
};
ControlFlow::Break(Some((FieldSig { ty, ..f.clone() }, m.clone())))
})
}
/// Type of reading field `name` off a class receiver: the visible field's
/// type, widened to `T | null` when optional. Reports the write-only case
/// (setter, no getter) — a property with no readable value. Shared by
/// `obj.f` and `obj?.f` so the two never disagree about what a class field
/// reads as. `None` means no such visible field.
pub(super) fn class_field_read_ty(
&mut self,
class_mangled: &MangledName,
class_args: &[Type],
name: &crate::Ident,
) -> Option<Type> {
let (field, _decl) = self.class_field_visible(class_mangled, class_args, &name.name)?;
// The getter wins over the synthesized field entry: a class declaring
// only `set name` records the *setter's* parameter type there, while the
// read runs an inherited getter whose return type is what comes back.
if let Some(read) = self.class_getter(class_mangled, class_args, &name.name) {
return Some(read);
}
if self
.class_setter(class_mangled, class_args, &name.name)
.is_some()
{
self.error_with_help(
name.span,
format!("property `{}` is write-only (no getter)", name.name),
vec![format!("add a `get {}()` accessor to read it", name.name)],
);
}
Some(field_read_ty(&field))
}
/// Reports reading a static member off an *instance* receiver, if a static
/// of that name exists on the class or an ancestor. Shared by `obj.f` and
/// `obj?.f` so both name the same fix instead of one falling back to a
/// bare "no such field".
pub(super) fn report_static_on_instance(
&mut self,
receiver_ty: &Type,
class_mangled: &MangledName,
name: &crate::Ident,
) -> bool {
if self
.class_static_in_chain(class_mangled, &name.name)
.is_none()
{
return false;
}
let class_display = receiver_ty.peel().clone();
// The help must be code that parses: a static is reached through the bare
// class name, so `Box<number>.kind` — what the receiver's `Display` gives —
// would hand the reader a parse error as its fix.
let class_name = match receiver_ty.peel() {
Type::ClassRef { name, .. } => name.clone(),
other => other.to_string(),
};
self.error_with_help(
name.span,
format!(
"`{}` is a static member of `{class_display}` — access it on the \
class, not an instance",
name.name,
),
vec![format!("write `{class_name}.{}`", name.name)],
);
true
}
/// A `readonly` data field is writable only through `this` in the
/// constructor of the class that declares it.
pub(super) fn readonly_write_allowed(
&self,
receiver: crate::ExprId,
decl_mangled: &MangledName,
) -> Result<bool, CompilerFailure> {
let current_class_mangled = match &self.current_class {
Some(Type::ClassRef { mangled, .. }) => Some(mangled.clone()),
_ => None,
};
Ok(self.in_constructor
&& matches!(
self.ast
.try_expr(receiver)
.map_err(super::arena_failure)?
.kind,
crate::ExprKind::This
)
&& current_class_mangled.as_ref() == Some(decl_mangled))
}
/// The read and write types of class field or accessor `name`, for the
/// read-modify-write forms (`x.f += v`, `x.f++`) which need both. Reports
/// and returns `None` when the target is missing, one-sided (getter-only /
/// setter-only), or optional. A `readonly` violation is reported but still
/// yields the field's types, so the RHS keeps typechecking.
pub(super) fn class_read_write_target(
&mut self,
mangled: &MangledName,
class_args: &[Type],
receiver: crate::ExprId,
receiver_ty: &Type,
name: &Ident,
op: super::diagnostics::RwOp,
) -> Result<Option<FieldRw>, CompilerFailure> {
let Some((field, decl_mangled)) = self.class_field_visible(mangled, class_args, &name.name)
else {
if !self.try_report_method_assignment(name.span, receiver_ty, &name.name) {
let help = self.interface_member_miss_help(receiver_ty, &name.name);
self.error_with_help(
name.span,
format!("field `{}` does not exist on `{receiver_ty}`", name.name),
help,
);
}
return Ok(None);
};
// An accessor is readable iff it has a getter and writable iff it has a
// setter; `(None, None)` is a data field, where the `readonly` ctor-only
// rule applies instead.
match (
self.class_getter(mangled, class_args, &name.name),
self.class_setter(mangled, class_args, &name.name),
) {
(Some(read), Some(write)) => return Ok(Some(FieldRw { read, write })),
(None, Some(_)) => {
self.error_with_help(
name.span,
format!(
"property `{}` on `{receiver_ty}` is write-only (no getter)",
name.name
),
vec![format!("add a `get {}()` accessor to read it", name.name)],
);
return Ok(None);
}
(Some(_), None) => {
self.error_with_help(
name.span,
format!(
"cannot assign to read-only accessor `{}` on `{receiver_ty}`",
name.name,
),
vec![format!(
"add a `set {}(v: T)` accessor to write it",
name.name
)],
);
return Ok(None);
}
(None, None) => {}
}
if field.readonly && !self.readonly_write_allowed(receiver, &decl_mangled)? {
self.error_with_help(
name.span,
format!(
"cannot assign to readonly field `{}` on `{receiver_ty}`",
name.name,
),
vec![
"a `readonly` field is writable only in the constructor of its declaring class"
.to_string(),
],
);
}
// Reported here rather than left to the operator check, which would
// blame `+=` without naming the null.
let recv_span = self
.ast
.try_expr(receiver)
.map_err(super::arena_failure)?
.span;
if self.try_report_nullable_rw_target(
recv_span,
receiver_ty,
name,
&field.ty,
field.optional,
op,
) {
return Ok(None);
}
Ok(Some(FieldRw::uniform(field.ty.clone())))
}
/// The read (getter return) type of accessor property `prop`, searching up the
/// `extends` chain. `None` if `prop` has no getter — a plain data field or a
/// write-only accessor.
pub(super) fn class_getter(
&self,
class_mangled: &MangledName,
class_args: &[Type],
prop: &str,
) -> Option<Type> {
self.find_accessor(class_mangled, class_args, prop, |a| match a {
AccessorSig::Getter { ret_ty, .. } => Some(ret_ty.clone()),
AccessorSig::Setter { .. } => None,
})
}
/// The write (setter parameter) type of accessor property `prop`, searching up
/// the `extends` chain. `None` if `prop` has no setter — a plain data field or a
/// read-only accessor.
pub(super) fn class_setter(
&self,
class_mangled: &MangledName,
class_args: &[Type],
prop: &str,
) -> Option<Type> {
self.find_accessor(class_mangled, class_args, prop, |a| match a {
AccessorSig::Setter { param, .. } => Some(param.ty.clone()),
AccessorSig::Getter { .. } => None,
})
}
/// Walk the `extends` chain to the class that declares the requested half of
/// accessor `prop` and `extract` its type, substituted at the declaring
/// class's bindings.
///
/// The two halves inherit independently, matching the vtable layout: a class
/// that declares only `set prop` leaves `get prop` in the slot its ancestor
/// filled, and a parent-typed receiver reads it. So a level declaring only
/// the other half is not the end of the search. A plain data field of the
/// same name *is* — it shadows any inherited accessor outright.
fn find_accessor(
&self,
class_mangled: &MangledName,
class_args: &[Type],
prop: &str,
extract: impl Fn(&AccessorSig) -> Option<Type>,
) -> Option<Type> {
self.walk_class_chain(class_mangled, class_args, |sym, bindings| {
let TypeKind::Class {
fields, accessors, ..
} = &sym.kind
else {
return ControlFlow::Break(None);
};
if let Some(ty) = accessors
.iter()
.filter(|a| a.name() == prop)
.find_map(&extract)
{
return ControlFlow::Break(self.type_limits.ok_or_record(
super::generic::substitute_typevars(&ty, bindings, &self.type_limits),
));
}
// An accessor synthesizes a `fields` entry for typing, so the data-field
// shadow only applies where this level declares neither half.
let declares_other_half = accessors.iter().any(|a| a.name() == prop);
if fields.contains_key(prop) && !declares_other_half {
return ControlFlow::Break(None);
}
ControlFlow::Continue(())
})
}
/// A class method resolved up the inheritance chain: its declared signature
/// (unsubstituted — callers deciding boxing must see the raw `TypeVar`s),
/// the type-parameter bindings active at the declaring class, the mangled
/// name of that class, and the method's visibility.
pub(super) fn class_method_in_chain(
&self,
class_mangled: &MangledName,
class_args: &[Type],
method: &str,
) -> Option<ResolvedMethod> {
self.walk_class_chain(class_mangled, class_args, |sym, bindings| {
let TypeKind::Class {
methods,
method_visibility,
..
} = &sym.kind
else {
return ControlFlow::Break(None);
};
let Some(sig) = methods.get(method) else {
return ControlFlow::Continue(());
};
ControlFlow::Break(Some(ResolvedMethod {
sig: sig.clone(),
bindings: bindings.clone(),
declared_by: sym.mangled_name.clone(),
visibility: method_visibility
.get(method)
.copied()
.unwrap_or(Visibility::Public),
}))
})
}
/// Compiled instances carry callable method payloads; native instances
/// expose only their host/vtable methods. Imported compiler metadata records
/// the same distinction used when reconstructing their runtime layouts.
pub(super) fn class_method_has_mutable_payload(&self, receiver: &Type, method: &str) -> bool {
let Type::ClassRef {
mangled,
package,
args,
..
} = receiver.peel()
else {
return false;
};
let compiled = package.as_str() == self.package_name
|| self
.packages_by_name
.get(package.as_str())
.or_else(|| self.type_only_packages.get(package.as_str()))
.is_some_and(|package| package.runtime_types.contains_key(mangled.as_str()));
compiled
&& self
.class_method_in_chain(mangled, args, method)
.is_some_and(|resolved| resolved.sig.generics.is_empty())
}
/// A static member resolved up the inheritance chain (TS hands statics down
/// to subclasses): the resolution plus the mangled name of the *defining*
/// class — the dispatch key is minted from the definer, so `B.f()` calls
/// `A#static#f`.
pub(super) fn class_static_in_chain(
&self,
class_mangled: &MangledName,
member: &str,
) -> Option<(StaticResolution, MangledName)> {
let mut cur = Some(class_mangled.clone());
let mut seen: Vec<MangledName> = Vec::new();
while let Some(m) = cur {
if seen.contains(&m) {
break;
}
seen.push(m.clone());
let TypeKind::Class {
statics,
static_visibility,
static_fields,
extends,
..
} = self.class_by_mangled(&m)?.kind
else {
break;
};
if let Some(sig) = statics.get(member) {
let vis = static_visibility
.get(member)
.copied()
.unwrap_or(Visibility::Public);
return Some((StaticResolution::Method(sig.clone(), vis), m));
}
if let Some(field) = static_fields.get(member) {
return Some((StaticResolution::Field(field.clone()), m));
}
cur = extends.map(|e| e.parent);
}
None
}
/// Whether the chain declares an *instance* member (field, method, or
/// accessor-backed property) of this name — used to steer the
/// instance-member-on-class-object diagnostic.
pub(super) fn class_instance_member_in_chain(
&self,
class_mangled: &MangledName,
member: &str,
) -> bool {
let mut cur = Some(class_mangled.clone());
let mut seen: Vec<MangledName> = Vec::new();
while let Some(m) = cur {
if seen.contains(&m) {
break;
}
seen.push(m.clone());
let Some(sym) = self.class_by_mangled(&m) else {
break;
};
let TypeKind::Class {
fields,
methods,
extends,
..
} = sym.kind
else {
break;
};
if fields.contains_key(member) || methods.contains_key(member) {
return true;
}
cur = extends.map(|e| e.parent);
}
false
}
/// All static member names visible on the class (own + inherited), for
/// did-you-mean and the bare-class-name help.
pub(super) fn class_static_names(&self, class_mangled: &MangledName) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
let mut cur = Some(class_mangled.clone());
let mut seen: Vec<MangledName> = Vec::new();
while let Some(m) = cur {
if seen.contains(&m) {
break;
}
seen.push(m.clone());
let Some(sym) = self.class_by_mangled(&m) else {
break;
};
let TypeKind::Class {
statics,
static_fields,
extends,
..
} = sym.kind
else {
break;
};
names.extend(statics.keys().cloned());
names.extend(static_fields.keys().cloned());
cur = extends.map(|e| e.parent);
}
names.sort();
names.dedup();
names
}
/// Typecheck `super(...)`: delegate to the parent constructor. Valid only in
/// a constructor body of a class with a parent.
pub(super) fn infer_super_call(
&mut self,
args: Vec<crate::ExprId>,
span: Span,
) -> Result<(crate::TypedExprKind, Type), CompilerFailure> {
// Taken before the arguments are inferred, so a `super(...)` among
// them isn't mistaken for the statement.
let is_statement = std::mem::take(&mut self.super_call_is_statement);
self.check_super_call_position(span, is_statement);
let parent = self.current_super.clone();
// The parent's ctor params, substituted at the extends clause's type
// args (`class Tagged<T> extends Box<T>` checks `super(v)` against
// `Box`'s ctor with its generics bound to the clause's args).
let ctor_params = match parent
.as_ref()
.and_then(|e| self.class_by_mangled(&e.parent).map(|sym| (e, sym)))
{
Some((e, sym)) => match sym.kind {
TypeKind::Class {
constructor,
generics,
..
} => {
if generics.len() != e.args.len() {
return Err(super::inference_failure(
"parent class generic argument mismatch",
));
}
let bindings: BTreeMap<String, Type> = generics
.iter()
.cloned()
.zip(e.args.iter().cloned())
.collect();
Some(
constructor
.iter()
.map(|p| {
// Extends args may name the child's own type
// params — map those to the body's live GPs.
let ty = super::generic::substitute_typevars(
&p.ty,
&bindings,
&self.type_limits,
)
.and_then(|ty| self.apply_body_instantiations(&ty))
.map_err(type_limit_at(span))?;
Ok(Param { ty, ..p.clone() })
})
.collect::<Result<Vec<_>, CompilerFailure>>()?,
)
}
_ => None,
},
None => None,
};
let ctor_params = ctor_params.filter(|_| !self.current_class_hides_parent_constructor());
let (Some(params), Some(parent)) = (ctor_params, parent) else {
if self.in_constructor
&& !self.current_class_inherits_unresolved_parent()
&& !self.current_class_hides_parent_constructor()
{
self.error_with_help(
span,
"`super(...)` requires a parent class".to_string(),
vec!["only a class with an `extends` clause can call `super(...)`".to_string()],
);
}
let outer = std::mem::replace(&mut self.in_super_arguments, true);
for arg in &args {
let _ = self.infer_expr(*arg, None)?;
}
self.in_super_arguments = outer;
return Ok((crate::TypedExprKind::Null, Type::Void));
};
let parent_ty = self.super_receiver_type(&parent)?;
let outer = std::mem::replace(&mut self.in_super_arguments, true);
let typed_args = self.bind_param_call_args(
¶ms,
&Type::Void,
super::expr::CallLift::Constructor {
class_ty: &parent_ty,
},
&args,
span,
)?;
self.in_super_arguments = outer;
Ok((
crate::TypedExprKind::SuperCtorCall {
parent: parent.parent,
args: typed_args,
},
Type::Void,
))
}
/// Report a `super(...)` outside a subclass constructor's own body, or
/// not a statement of its own. Record any call in that body for the
/// once-only and read-before-`super` checks.
fn check_super_call_position(&mut self, span: Span, is_statement: bool) {
if !self.in_constructor {
self.error_with_help(
span,
"`super(...)` is only valid inside a constructor".to_string(),
vec!["call the parent constructor from this class's `constructor`".to_string()],
);
return;
}
// A class with no `extends` clause is told so by `infer_super_call`
// instead. One whose parent failed to resolve is still checked.
if self.current_super.is_none() && !self.current_class_inherits_unresolved_parent() {
return;
}
if self.in_nested_function {
// Not the constructor's own call: it can run late or never, so it
// neither counts toward `super_seen` nor ends the window before it.
self.error_with_help(
span,
"`super(...)` can't be called from a function nested in a constructor".to_string(),
vec!["call the parent constructor directly in the `constructor` body".to_string()],
);
return;
}
// Still recorded below: the call is made, so the end-of-body check
// mustn't also report it missing.
if !is_statement {
self.error_with_help(
span,
"`super(...)` must be a statement of its own".to_string(),
vec!["write `super(...);` on its own line, so it runs on every path".to_string()],
);
}
self.note_constructor_super_call(span);
}
/// A read of `this`, or of a `super` member, in a subclass constructor.
/// Until `super(...)` returns the instance isn't built: a read in the
/// call's own arguments, or in a `catch` or `finally` around it, is
/// reported here, and one before the call is flagged for the call to
/// report. A read inside an arrow or nested function counts too, since
/// nothing stops the parent's constructor, or the handler, calling it
/// early. A function expression is skipped: it clears `current_class`
/// because its `this` is its own, and `super` in it is a parse error.
pub(super) fn note_read_before_super(&mut self, span: Span) {
if !self.in_constructor || self.current_super.is_none() || self.current_class.is_none() {
return;
}
if self.in_super_arguments {
self.error_with_help(
span,
"the arguments of `super(...)` can't read `this` or a `super` member".to_string(),
vec!["compute the argument from the constructor's parameters".to_string()],
);
return;
}
if self.in_super_handler {
self.error_with_help(
span,
"a `catch` or `finally` around `super(...)` can't read `this` or a `super` member"
.to_string(),
vec![
"it also runs when `super(...)` throws, before the instance is built"
.to_string(),
],
);
return;
}
if !self.super_seen {
self.read_before_super = true;
}
}
/// TS2729: a field initializer reading `this.x` before `x` is set. Field
/// initializers run in declaration order, before the constructor assigns
/// its parameter properties; a closure reading it later is fine.
pub(super) fn note_uninitialized_member_read(
&mut self,
receiver: crate::ExprId,
name: &crate::Ident,
span: Span,
) -> Result<(), CompilerFailure> {
if self.in_nested_function
|| !self
.uninitialized_members
.as_ref()
.is_some_and(|members| members.contains(&name.name))
{
return Ok(());
}
let mut receiver = receiver;
while let crate::ExprKind::Paren(inner) = &self
.ast
.try_expr(receiver)
.map_err(super::arena_failure)?
.kind
{
receiver = *inner;
}
if !matches!(
self.ast
.try_expr(receiver)
.map_err(super::arena_failure)?
.kind,
crate::ExprKind::This
) {
return Ok(());
}
self.error_with_help(
span,
format!("property `{}` is used before its initialization", name.name),
vec![
format!(
"field initializers run in declaration order, before the constructor \
assigns parameter properties, so `this.{}` is still `undefined` here",
name.name
),
"read it in the constructor instead, or declare the field it depends on first"
.to_string(),
],
);
Ok(())
}
/// Whether `expr` is a `super(...)` call, parenthesized or not, as opposed
/// to one inside it.
pub(super) fn is_super_call(&self, expr: crate::ExprId) -> Result<bool, CompilerFailure> {
match &self.ast.try_expr(expr).map_err(super::arena_failure)?.kind {
crate::ExprKind::Paren(inner) => self.is_super_call(*inner),
crate::ExprKind::Call { callee, .. } => Ok(matches!(
self.ast
.try_expr(*callee)
.map_err(super::arena_failure)?
.kind,
crate::ExprKind::Super
)),
_ => Ok(false),
}
}
/// A subclass constructor may call `super(...)` exactly once, before any
/// read of `this` or a `super` member. Record that we've seen it for the end-of-body check.
fn note_constructor_super_call(&mut self, span: Span) {
if self.super_seen {
self.error(span, "`super(...)` may only be called once".to_string());
}
if self.read_before_super {
self.error_with_help(
span,
"`super(...)` must be called before accessing `this` or a `super` member"
.to_string(),
vec!["move the `super(...)` call to the top of the constructor".to_string()],
);
}
self.super_seen = true;
}
/// Typecheck `super.method(...)`: resolve the method on the parent chain and
/// emit a direct call of the declaring class's body. Valid only inside a
/// subclass body.
pub(super) fn infer_super_method_call(
&mut self,
name: crate::Ident,
args: Vec<crate::ExprId>,
span: Span,
) -> Result<(crate::TypedExprKind, Type), CompilerFailure> {
self.note_read_before_super(span);
let Some(parent) = self.current_super.clone() else {
if !self.current_class_inherits_unresolved_parent() {
self.error_with_help(
span,
"`super.method(...)` is only valid inside a subclass".to_string(),
vec![
"only a class with an `extends` clause can call `super.method(...)`"
.to_string(),
],
);
}
for arg in &args {
let _ = self.infer_expr(*arg, None)?;
}
return Ok((crate::TypedExprKind::Null, Type::Error));
};
let Some(resolved) = self.class_method_in_chain(&parent.parent, &parent.args, &name.name)
else {
if !self.inherits_unresolved_parent(&parent.parent) {
self.error(
span,
format!("no method `{}` on the parent class", name.name),
);
}
for arg in &args {
let _ = self.infer_expr(*arg, None)?;
}
return Ok((crate::TypedExprKind::Null, Type::Error));
};
let ResolvedMethod {
sig,
bindings,
declared_by: owner,
..
} = resolved;
if sig.optional {
self.error_with_help(
name.span,
format!("method `{}` may be undefined", name.name),
vec!["check the optional method before invoking it".into()],
);
}
if !sig.generics.is_empty() {
self.error(
span,
format!(
"`super.{}(...)` on a generic method is not supported yet",
name.name
),
);
}
let sig = substitute_method_sig(&sig, &bindings, &self.type_limits)
.map_err(type_limit_at(span))?;
let sig = MethodSig {
params: sig
.params
.iter()
.map(|p| {
Ok(Param {
ty: self.apply_body_instantiations(&p.ty)?,
..p.clone()
})
})
.collect::<Result<_, TypeTooLarge>>()
.map_err(type_limit_at(span))?,
ret: self
.apply_body_instantiations(&sig.ret)
.map_err(type_limit_at(span))?,
..sig
};
let parent_ty = self.super_receiver_type(&parent)?;
let typed_args = self.bind_param_call_args(
&sig.params,
&sig.ret,
super::expr::CallLift::Method {
receiver_ty: &parent_ty,
name: &name.name,
sig: &sig,
},
&args,
span,
)?;
Ok((
crate::TypedExprKind::SuperMethodCall {
owner,
name,
args: typed_args,
},
sig.ret,
))
}
fn super_receiver_type(&self, parent: &crate::ClassExtends) -> Result<Type, CompilerFailure> {
let sym = self
.class_by_mangled(&parent.parent)
.ok_or_else(|| super::inference_failure("missing resolved parent class"))?;
Ok(Type::class_ref(
self.type_package(&sym.name),
sym.name.clone(),
parent.parent.clone(),
parent
.args
.iter()
.map(|ty| self.apply_body_instantiations(ty))
.collect::<Result<_, _>>()
.map_err(type_limit_unlocated)?,
))
}
fn class_parent(&self, mangled: &MangledName) -> Option<MangledName> {
match self.class_by_mangled(mangled)?.kind {
TypeKind::Class { extends, .. } => extends.map(|e| e.parent),
_ => None,
}
}
fn class_method_sig(&self, mangled: &MangledName, method: &str) -> Option<MethodSig> {
match self.class_by_mangled(mangled)?.kind {
TypeKind::Class { methods, .. } => methods.get(method).cloned(),
_ => None,
}
}
/// Nearest ancestor's signature for `method`, walking the `extends` chain
/// (cycle-guarded), substituted at the bindings the child's extends clause
/// instantiates — so an override check compares against the parent sig as
/// the child actually sees it. `None` when no ancestor declares it.
fn ancestor_method_sig(
&self,
child: &MangledName,
method: &str,
own_bindings: &BTreeMap<String, Type>,
) -> Option<MethodSig> {
self.walk_ancestors_at(child, own_bindings, |sym, bindings| {
let TypeKind::Class { methods, .. } = &sym.kind else {
return ControlFlow::Continue(());
};
match methods.get(method) {
Some(sig) => {
ControlFlow::Break(self.type_limits.ok_or_record(substitute_method_sig(
sig,
bindings,
&self.type_limits,
)))
}
None => ControlFlow::Continue(()),
}
})
}
/// The class's *own* [`data_field`], ignoring anything inherited. Statics
/// live in a separate map and never resolve here.
fn class_own_field_sig(&self, mangled: &MangledName, field: &str) -> Option<FieldSig> {
data_field(&self.class_by_mangled(mangled)?, field).cloned()
}
/// The *widest* ancestor declaring `field` — the farthest one up the chain.
/// Declarations narrow monotonically downward, so this is the type through
/// which the largest set of values can be written into the shared slot, and
/// therefore the one a read guard has to defend against.
/// [`ancestor_field_decl`](Self::ancestor_field_decl) answers the
/// redeclaration *rules*, which are about the adjacent pair.
fn widest_ancestor_field_decl(
&self,
child: &MangledName,
field: &str,
own_bindings: &BTreeMap<String, Type>,
) -> Option<(FieldSig, MangledName)> {
let mut widest = None;
self.walk_ancestors_at::<()>(child, own_bindings, |sym, bindings| {
if let Some(sig) = data_field(sym, field) {
let Some(ty) = self.type_limits.ok_or_record(substitute_typevars(
&sig.ty,
bindings,
&self.type_limits,
)) else {
widest = None;
return ControlFlow::Break(None);
};
widest = Some((FieldSig { ty, ..sig.clone() }, sym.mangled_name.clone()));
}
ControlFlow::Continue(())
});
widest
}
/// Nearest ancestor declaring `field` as a data field, with the class that
/// declares it, substituted at the bindings the child's `extends` clause
/// instantiates. The counterpart of
/// [`ancestor_method_sig`](Self::ancestor_method_sig) for data fields.
fn ancestor_field_decl(
&self,
child: &MangledName,
field: &str,
own_bindings: &BTreeMap<String, Type>,
) -> Option<(FieldSig, MangledName)> {
self.walk_ancestors_at(child, own_bindings, |sym, bindings| {
match data_field(sym, field) {
Some(sig) => {
let ty = self.type_limits.ok_or_record(substitute_typevars(
&sig.ty,
bindings,
&self.type_limits,
));
ControlFlow::Break(
ty.map(|ty| (FieldSig { ty, ..sig.clone() }, sym.mangled_name.clone())),
)
}
None => ControlFlow::Continue(()),
}
})
}
fn declaration_was_rejected(&self, span: Span) -> bool {
self.diagnostics.iter().any(|diagnostic| {
diagnostic.severity == crate::Severity::Error && diagnostic.span == span
})
}
/// Typecheck every class's field initializers, method bodies, and
/// constructor body, then mirror the result into the typed AST. Runs after
/// `infer_functions` so bodies can construct sibling classes and call
/// top-level functions.
pub(super) fn infer_classes(&mut self) -> Result<(), CompilerFailure> {
let top_level: Vec<_> = self.ast.top_level.clone();
for stmt_id in top_level {
let stmt = self
.ast
.try_stmt(stmt_id)
.map_err(super::arena_failure)?
.clone();
let StmtKind::ClassDecl {
name,
extends: _,
implements: _,
members,
doc,
..
} = stmt.kind
else {
continue;
};
if self.rejected_class_names.contains(&name.name) {
continue;
}
let Some(sym) = self.types.lookup(&name.name) else {
if self.declaration_was_rejected(name.span) {
continue;
}
return Err(
super::inference_failure("missing class signature").with_span(name.span)
);
};
let TypeKind::Class {
generics: class_generics,
fields: field_sigs,
methods: method_sigs,
method_visibility,
statics: static_sigs,
static_visibility,
static_fields,
constructor: ctor_params,
extends: parent,
implements,
..
} = sym.kind.clone()
else {
if self.declaration_was_rejected(name.span) {
continue;
}
return Err(
super::inference_failure("class signature has the wrong symbol kind")
.with_span(name.span),
);
};
let mangled = sym.mangled_name.clone();
self.typed_ast
.runtime_class_parameters
.insert(mangled.clone(), class_generics.clone());
// Static bodies run without an instance: checked before `current_class`
// is set so `this`/`super` get the static-specific rejections — and
// before the class generics enter body scope (a static can't
// reference them).
self.check_static_methods(&members, &static_sigs, &mangled, &name.name)?;
// Class-level generics live for the whole set of instance bodies:
// `this` is the class instantiated at its own params
// (`Box<GP(T)>`), so `this.value: T` reads as the body's `T` and
// `T` / `Box<T>` annotations inside bodies resolve. Member
// signature types entering body scopes go through `class_inst`
// (TypeVar → GenericParam); typed-AST decl types keep the raw
// signature TypeVar forms codegen expects.
let class_inst = if class_generics.is_empty() {
BTreeMap::new()
} else {
self.push_body_generics(class_generics.clone())?
};
let class_ty = Type::class_ref(
crate::Package(self.package_name.to_string()),
name.name.clone(),
mangled.clone(),
class_generics
.iter()
.map(|g| {
class_inst.get(g).cloned().ok_or_else(|| {
super::inference_failure("missing class body generic binding")
})
})
.collect::<Result<_, _>>()?,
);
let prev_class = self.current_class.replace(class_ty.clone());
let prev_super = std::mem::replace(&mut self.current_super, parent.clone());
let exprs_before = self.typed_ast.exprs_len();
let stmts_before = self.typed_ast.stmts_len();
let typed_fields =
self.check_class_fields(&members, &mangled, &field_sigs, &class_inst)?;
let typed_ctor = self.check_constructor(&members, &ctor_params, &class_inst)?;
let typed_methods =
self.check_class_methods(&members, &method_sigs, &method_visibility, &class_inst)?;
let accessors = self.check_class_accessors(&members, &field_sigs)?;
self.current_class = prev_class;
self.current_super = prev_super;
if !class_generics.is_empty() {
self.pop_body_generics();
// Erase the class-level GPs from every body typed here —
// ctor, field initializers, and accessors don't have their own
// erasure loops (methods do; a second pass over their ranges
// is a no-op).
for id in self
.typed_ast
.expr_ids()
.map_err(crate::typechecker::arena_failure)?
.skip(exprs_before)
{
erase_generic_params_in_expr(
self.typed_ast
.try_expr_mut(id)
.map_err(crate::typechecker::arena_failure)?,
);
}
for id in self
.typed_ast
.stmt_ids()
.map_err(crate::typechecker::arena_failure)?
.skip(stmts_before)
{
erase_generic_params_in_stmt(
self.typed_ast
.try_stmt_mut(id)
.map_err(crate::typechecker::arena_failure)?,
);
}
}
let decl = TypedClassDecl {
name: name.clone(),
fields: typed_fields,
static_methods: static_sigs
.keys()
.map(|name| {
(
name.clone(),
static_visibility
.get(name)
.copied()
.unwrap_or(Visibility::Public),
)
})
.collect(),
static_fields,
inherited_ctor_params: if typed_ctor.is_some() {
Vec::new()
} else {
ctor_params
.iter()
.map(|p| TypedParam {
name: crate::Ident {
name: p.name.clone(),
span: name.span,
},
ty: p.ty.clone(),
boxed: false,
rest: p.rest,
optional: p.optional,
default: p.default.clone(),
})
.collect()
},
constructor: typed_ctor,
methods: typed_methods,
accessors,
// Codegen is generics-erased: the typed AST carries only the
// parent's name, never the extends args.
extends: parent.map(|e| e.parent),
implements,
mangled_name: mangled,
doc,
};
self.add_typed_type_decl(
crate::TypedTypeDecl::Class(decl),
sym_for_export(self, &name)?,
)?;
self.type_size_checkpoint(Some(name.span))?;
}
Ok(())
}
fn check_class_fields(
&mut self,
members: &[ClassMember],
mangled: &MangledName,
field_sigs: &BTreeMap<String, FieldSig>,
class_inst: &BTreeMap<String, Type>,
) -> Result<Vec<TypedClassField>, CompilerFailure> {
let mut out = Vec::new();
// Members an initializer would read before they are set: every
// parameter property, and each instance field from the current one on.
let mut pending: std::collections::BTreeSet<String> = members
.iter()
.filter_map(|member| match member {
ClassMember::Field {
name, modifiers, ..
} if modifiers.static_span.is_none() => Some(name.name.clone()),
_ => None,
})
.collect();
if let Some(ClassMember::Constructor { params, .. }) = members
.iter()
.find(|m| matches!(m, ClassMember::Constructor { .. }))
{
pending.extend(
params
.iter()
.filter(|param| param.modifiers.is_some())
.map(|param| param.name.name.clone()),
);
}
for member in members {
let ClassMember::Field {
name,
modifiers,
initializer,
doc,
..
} = member
else {
continue;
};
// Statics live in a separate namespace and may shadow an instance
// field's name; their initializers are checked as module globals.
if modifiers.static_span.is_some() {
continue;
}
let Some(sig) = field_sigs.get(&name.name) else {
if self.declaration_was_rejected(name.span) {
continue;
}
return Err(
super::inference_failure("missing class member signature").with_span(name.span)
);
};
// Field initializers may read `this`; `current_class` is already set.
let body_ty = substitute_typevars(&sig.ty, class_inst, &self.type_limits)
.map_err(type_limit_at(name.span))?;
let previous = self.uninitialized_members.replace(pending.clone());
let typed_init = initializer
.map(|expr| {
let (typed, value_ty) = self.infer_expr(expr, Some(&body_ty))?;
if !super::assignable(&value_ty, &body_ty, self.resolver())
&& !matches!(value_ty, Type::Error)
{
let span = self.ast.try_expr(expr).map_err(super::arena_failure)?.span;
self.drop_contextual_mismatch(span, &body_ty, &value_ty);
self.error(
span,
format!(
"field `{}` initializer is `{value_ty}`, expected `{}`",
name.name, sig.ty
),
);
}
Ok::<_, CompilerFailure>(typed)
})
.transpose();
self.uninitialized_members = previous;
let typed_init = typed_init?;
pending.remove(&name.name);
out.push(TypedClassField {
name: name.clone(),
ty: sig.ty.clone(),
visibility: sig.visibility,
readonly: sig.readonly,
optional: sig.optional,
initializer: typed_init,
auto_assigned: false,
narrowing_check: self.narrowing_check_for(mangled, &name.name),
doc: doc.clone(),
});
}
// Parameter properties: declared on the constructor, assigned from the
// param. Materialized as auto-assigned fields (no initializer) so they
// get struct slots and satisfy interface conformance like a plain field.
if let Some(ClassMember::Constructor { params, .. }) = members
.iter()
.find(|m| matches!(m, ClassMember::Constructor { .. }))
{
for param in params {
if param.modifiers.is_none() {
continue;
}
let Some(sig) = field_sigs.get(¶m.name.name) else {
if self.declaration_was_rejected(param.name.span) {
continue;
}
return Err(
super::inference_failure("missing parameter-property signature")
.with_span(param.name.span),
);
};
out.push(TypedClassField {
name: param.name.clone(),
ty: sig.ty.clone(),
visibility: sig.visibility,
readonly: sig.readonly,
optional: sig.optional,
initializer: None,
auto_assigned: true,
narrowing_check: self.narrowing_check_for(mangled, ¶m.name.name),
doc: None,
});
}
}
Ok(out)
}
fn check_constructor(
&mut self,
members: &[ClassMember],
ctor_params: &[Param],
class_inst: &BTreeMap<String, Type>,
) -> Result<Option<TypedClassConstructor>, CompilerFailure> {
let Some((params, body, doc, span)) = members.iter().find_map(|m| match m {
ClassMember::Constructor {
params,
body,
doc,
span,
..
} => Some((params, *body, doc, *span)),
_ => None,
}) else {
return Ok(None);
};
let prev_in_ctor = std::mem::replace(&mut self.in_constructor, true);
let prev_super_seen = std::mem::replace(&mut self.super_seen, false);
let prev_read_before = std::mem::replace(&mut self.read_before_super, false);
let prev_nested = std::mem::replace(&mut self.in_nested_function, false);
// A constructor returns no value; a bare `return;` is fine.
let prev_return = self.current_return.replace(Type::Void);
let prev_reachable = self.enter_body_reachability();
let (typed_params, prologue) = bind_params_for_body(self, params, ctor_params, class_inst)?;
let body_id = self
.infer_body_with_narrowing_boundary(body)?
.ok_or_else(|| super::inference_failure("constructor body is a Block"))?;
let body_id = self.prepend_parameter_defaults(prologue, body_id)?;
// A subclass constructor must initialize the parent via `super(...)`.
if self.current_super.is_some() && !self.super_seen {
let ctor_span = members
.iter()
.find_map(|m| match m {
ClassMember::Constructor { span, .. } => Some(*span),
_ => None,
})
.map_or_else(
|| {
Ok::<_, CompilerFailure>(
self.ast.try_stmt(body).map_err(super::arena_failure)?.span,
)
},
Ok,
)?;
self.error_with_help(
ctor_span,
"a subclass constructor must call `super(...)`".to_string(),
vec![
"call the parent constructor with `super(...)` before using `this`".to_string(),
],
);
}
self.current_return = prev_return;
self.restore_reachability(prev_reachable);
self.in_constructor = prev_in_ctor;
self.super_seen = prev_super_seen;
self.read_before_super = prev_read_before;
self.in_nested_function = prev_nested;
self.scopes.pop();
Ok(Some(TypedClassConstructor {
doc: doc.clone().map(Box::new),
span,
params: typed_params,
body: body_id,
}))
}
fn check_class_methods(
&mut self,
members: &[ClassMember],
method_sigs: &BTreeMap<String, MethodSig>,
method_visibility: &BTreeMap<String, Visibility>,
class_inst: &BTreeMap<String, Type>,
) -> Result<Vec<TypedClassMethod>, CompilerFailure> {
let mut out = Vec::new();
for member in members {
let ClassMember::Method {
name,
modifiers,
params,
body,
doc,
..
} = member
else {
continue;
};
// A static may share an instance method's name — don't let the name
// lookup bind its body against the instance signature.
if modifiers.static_span.is_some() {
continue;
}
let Some(sig) = method_sigs.get(&name.name) else {
if self.declaration_was_rejected(name.span) {
continue;
}
return Err(
super::inference_failure("missing class member signature").with_span(name.span)
);
};
if params.len() != sig.params.len() && !self.declaration_was_rejected(name.span) {
return Err(
super::inference_failure("method parameter/signature length mismatch")
.with_span(name.span),
);
}
let body_instantiation = self.push_body_generics(sig.generics.clone())?;
// Method-level generics shadow class-level ones of the same name.
let mut merged = class_inst.clone();
merged.extend(body_instantiation);
let mut body_param_types: Vec<Type> = sig
.params
.iter()
.map(|p| substitute_typevars(&p.ty, &merged, &self.type_limits))
.collect::<Result<_, _>>()
.map_err(type_limit_at(name.span))?;
// A rejected duplicate is checked against the first declaration's
// signature; parameters that signature lacks type as errors.
body_param_types.resize(params.len(), Type::Error);
let body_ret = substitute_typevars(&sig.ret, &merged, &self.type_limits)
.map_err(type_limit_at(name.span))?;
let typed_params: Vec<TypedParam> = params
.iter()
.zip(sig.params.iter())
.map(|(p, rp)| TypedParam {
name: p.name.clone(),
ty: rp.ty.clone(),
boxed: false,
rest: rp.rest,
optional: rp.optional,
default: rp.default.clone(),
})
.collect();
self.scopes.push();
let prev_return = self.current_return.replace(body_ret);
let prev_reachable = self.enter_body_reachability();
let exprs_before = self.typed_ast.exprs_len();
let stmts_before = self.typed_ast.stmts_len();
let prologue = self.infer_parameter_defaults(params, &body_param_types)?;
let body_id = self
.infer_body_with_narrowing_boundary(*body)?
.ok_or_else(|| super::inference_failure("method body is a Block"))?;
let body_id = self.prepend_parameter_defaults(prologue, body_id)?;
self.current_return = prev_return;
self.restore_reachability(prev_reachable);
self.scopes.pop();
self.pop_body_generics();
for id in self
.typed_ast
.expr_ids()
.map_err(crate::typechecker::arena_failure)?
.skip(exprs_before)
{
erase_generic_params_in_expr(
self.typed_ast
.try_expr_mut(id)
.map_err(crate::typechecker::arena_failure)?,
);
}
for id in self
.typed_ast
.stmt_ids()
.map_err(crate::typechecker::arena_failure)?
.skip(stmts_before)
{
erase_generic_params_in_stmt(
self.typed_ast
.try_stmt_mut(id)
.map_err(crate::typechecker::arena_failure)?,
);
}
out.push(TypedClassMethod {
name: name.clone(),
generics: sig.generics.clone(),
params: typed_params,
return_type: sig.ret.clone(),
body: body_id,
visibility: method_visibility
.get(&name.name)
.copied()
.unwrap_or(Visibility::Public),
doc: doc.clone(),
});
}
Ok(out)
}
/// Typecheck each static method body into an ordinary [`crate::TypedFunction`]
/// keyed `Class#static#name` — codegen, DWARF, and the export surface treat a
/// static as a plain top-level function. Runs with `current_class` unset (no
/// receiver); `current_static` routes `this` to its tailored diagnostic.
fn check_static_methods(
&mut self,
members: &[ClassMember],
static_sigs: &BTreeMap<String, MethodSig>,
class_mangled: &MangledName,
class_name: &str,
) -> Result<(), CompilerFailure> {
for member in members {
let ClassMember::Method {
name,
modifiers,
params,
body,
doc,
span,
..
} = member
else {
continue;
};
if modifiers.static_span.is_none() {
continue;
}
let Some(sig) = static_sigs.get(&name.name) else {
if self.declaration_was_rejected(name.span) {
continue;
}
return Err(
super::inference_failure("missing class member signature").with_span(name.span)
);
};
if params.len() != sig.params.len() && !self.declaration_was_rejected(name.span) {
return Err(
super::inference_failure("method parameter/signature length mismatch")
.with_span(name.span),
);
}
let body_instantiation = self.push_body_generics(sig.generics.clone())?;
let mut body_param_types: Vec<Type> = sig
.params
.iter()
.map(|p| substitute_typevars(&p.ty, &body_instantiation, &self.type_limits))
.collect::<Result<_, _>>()
.map_err(type_limit_at(name.span))?;
// A rejected duplicate is checked against the first declaration's
// signature; parameters that signature lacks type as errors.
body_param_types.resize(params.len(), Type::Error);
let body_ret = substitute_typevars(&sig.ret, &body_instantiation, &self.type_limits)
.map_err(type_limit_at(name.span))?;
let typed_params: Vec<TypedParam> = params
.iter()
.zip(sig.params.iter())
.map(|(p, rp)| TypedParam {
name: p.name.clone(),
ty: rp.ty.clone(),
boxed: false,
rest: rp.rest,
optional: rp.optional,
default: rp.default.clone(),
})
.collect();
self.scopes.push();
let prev_return = self.current_return.replace(body_ret);
let prev_reachable = self.enter_body_reachability();
let prev_static = self
.current_static
.replace((class_name.to_string(), name.name.clone()));
let exprs_before = self.typed_ast.exprs_len();
let stmts_before = self.typed_ast.stmts_len();
let prologue = self.infer_parameter_defaults(params, &body_param_types)?;
let body_id = self
.infer_body_with_narrowing_boundary(*body)?
.ok_or_else(|| super::inference_failure("static method body is a Block"))?;
let body_id = self.prepend_parameter_defaults(prologue, body_id)?;
self.current_return = prev_return;
self.restore_reachability(prev_reachable);
self.current_static = prev_static;
self.scopes.pop();
self.pop_body_generics();
for id in self
.typed_ast
.expr_ids()
.map_err(crate::typechecker::arena_failure)?
.skip(exprs_before)
{
erase_generic_params_in_expr(
self.typed_ast
.try_expr_mut(id)
.map_err(crate::typechecker::arena_failure)?,
);
}
for id in self
.typed_ast
.stmt_ids()
.map_err(crate::typechecker::arena_failure)?
.skip(stmts_before)
{
erase_generic_params_in_stmt(
self.typed_ast
.try_stmt_mut(id)
.map_err(crate::typechecker::arena_failure)?,
);
}
self.add_typed_function(crate::TypedFunction {
name: Ident {
name: format!("{class_name}.{}", name.name),
span: name.span,
},
mangled_name: crate::mangle::static_member(class_mangled, &name.name),
generics: sig.generics.clone(),
params: typed_params,
return_type: sig.ret.clone(),
type_predicate: None,
body: body_id,
doc: doc.clone(),
span: *span,
})?;
}
Ok(())
}
/// Typecheck each accessor body into a [`TypedClassAccessor`] (one per
/// `get`/`set`). A getter returns its own read type; a setter takes its own
/// write type — the two are independent. Codegen lowers each to a vtable
/// method — they never become `TypedClassMethod`s.
fn check_class_accessors(
&mut self,
members: &[ClassMember],
field_sigs: &BTreeMap<String, FieldSig>,
) -> Result<Vec<TypedClassAccessor>, CompilerFailure> {
let mut accessors: Vec<TypedClassAccessor> = Vec::new();
for member in members {
let ClassMember::Accessor {
name,
kind,
modifiers,
param,
return_type,
body,
..
} = member
else {
continue;
};
// Duplicate members may have no property signature. Their annotations
// and bodies still need checking to report independent errors.
let visibility = field_sigs
.get(&name.name)
.map_or(modifiers.visibility, |sig| sig.visibility);
match kind {
AccessorKind::Get => {
// Annotations resolve inside the class's body-generics
// scope (`T` → GenericParam) so the body checks against
// the live form; the stored decl type is erased back to
// the signature TypeVar form codegen expects.
let ret_ty = return_type
.as_ref()
.map(|t| self.re_resolve_type(t))
.transpose()?
.unwrap_or(Type::Error);
let body_id = self.check_accessor_body(*body, None, &ret_ty)?;
accessors.push(TypedClassAccessor::Getter {
name: name.clone(),
ret_ty: erase_generic_params(&ret_ty),
visibility,
body: body_id,
});
}
AccessorKind::Set => {
let write_ty = param
.as_ref()
.and_then(|p| p.ty.as_ref())
.map(|t| self.re_resolve_type(t))
.transpose()?
.unwrap_or(Type::Error);
let pname = param.as_ref().map_or_else(
|| Ident {
name: "value".to_string(),
span: name.span,
},
|p| p.name.clone(),
);
let typed_param = TypedParam {
name: pname,
ty: write_ty,
boxed: false,
rest: false,
optional: false,
default: None,
};
let body_id = self.check_accessor_body(
*body,
Some((param.as_deref(), &typed_param)),
&Type::Void,
)?;
accessors.push(TypedClassAccessor::Setter {
name: name.clone(),
param: TypedParam {
ty: erase_generic_params(&typed_param.ty),
..typed_param
},
visibility,
body: body_id,
});
}
}
}
Ok(accessors)
}
/// Typecheck an accessor body with the given return type. A setter's
/// parameter is in scope, its destructuring pattern decomposed by the
/// body's prologue; one the parser recovered without a declaration binds
/// by name alone.
fn check_accessor_body(
&mut self,
body: crate::StmtId,
setter_param: Option<(Option<&crate::ParamDecl>, &TypedParam)>,
ret: &Type,
) -> Result<crate::StmtId, CompilerFailure> {
self.scopes.push();
let prologue = match setter_param {
Some((Some(decl), typed)) => self.infer_parameter_defaults(
std::slice::from_ref(decl),
std::slice::from_ref(&typed.ty),
)?,
Some((None, typed)) => {
let body_ty = self.local_storage_ty(&typed.name, typed.ty.clone());
self.scopes.insert_annotated_param(
typed.name.name.clone(),
body_ty,
typed.name.span,
);
Vec::new()
}
None => Vec::new(),
};
let prev_return = self.current_return.replace(ret.clone());
let prev_reachable = self.enter_body_reachability();
let body_id = self
.infer_body_with_narrowing_boundary(body)?
.ok_or_else(|| super::inference_failure("accessor body is a Block"))?;
let body_id = self.prepend_parameter_defaults(prologue, body_id)?;
self.current_return = prev_return;
self.restore_reachability(prev_reachable);
self.scopes.pop();
Ok(body_id)
}
}
/// What [`Inferer::carrier_fit`] decided about a collection carrier's
/// instantiations.
enum CarrierFit {
/// No instantiation satisfies the target.
None,
/// Every instantiation does.
Every,
/// It depends on the arguments, so each candidate is tried.
TryEach,
}
impl CarrierFit {
/// The candidates whose instantiation satisfies the target, trying each
/// with `satisfies` only when the fit is not already decided.
fn matching(self, candidates: &[Type], mut satisfies: impl FnMut(&Type) -> bool) -> Vec<Type> {
match self {
Self::None => Vec::new(),
Self::Every => candidates.to_vec(),
Self::TryEach => candidates
.iter()
.filter(|candidate| satisfies(candidate))
.cloned()
.collect(),
}
}
}
fn runtime_carrier_candidates(
members: &std::collections::BTreeMap<String, crate::ObjectField>,
) -> Vec<Type> {
let mut candidates = vec![
Type::Unknown,
Type::Number,
Type::Boolean,
Type::String,
Type::BigInt,
Type::Uint8Array,
];
for member in members.values() {
collect_runtime_carrier_candidates(&member.ty, &mut candidates);
}
candidates
}
fn collect_runtime_carrier_candidates(ty: &Type, out: &mut Vec<Type>) {
let ty = ty.peel();
if !out.contains(ty) && !matches!(ty, Type::Void | Type::Error) {
out.push(ty.clone());
}
match ty {
Type::Array(element) => collect_runtime_carrier_candidates(element, out),
Type::Tuple(elements) => {
for element in elements {
collect_runtime_carrier_candidates(element, out);
}
}
Type::Union(elements) => {
for element in elements {
collect_runtime_carrier_candidates(element, out);
}
}
Type::Object { fields, index } => {
if let Some(index) = index {
collect_runtime_carrier_candidates(&index.value, out);
}
for field in fields.values() {
collect_runtime_carrier_candidates(&field.ty, out);
}
}
Type::Function { params, ret, .. } => {
for param in params {
collect_runtime_carrier_candidates(param, out);
}
collect_runtime_carrier_candidates(ret, out);
}
Type::InterfaceRef { args, .. }
| Type::ClassRef { args, .. }
| Type::AliasRef { args, .. } => {
for arg in args {
collect_runtime_carrier_candidates(arg, out);
}
}
_ => {}
}
}
fn collect_interface_instantiations(ty: &Type, identity: &MangledName, out: &mut BTreeSet<Type>) {
match ty.peel() {
Type::InterfaceRef { mangled, .. } if mangled == identity => {
out.insert(ty.peel().clone());
}
Type::Array(element) => collect_interface_instantiations(element, identity, out),
Type::Tuple(elements) => {
for element in elements {
collect_interface_instantiations(element, identity, out);
}
}
Type::Union(elements) => {
for element in elements {
collect_interface_instantiations(element, identity, out);
}
}
Type::Object { fields, index } => {
if let Some(index) = index {
collect_interface_instantiations(&index.value, identity, out);
}
for field in fields.values() {
collect_interface_instantiations(&field.ty, identity, out);
}
}
Type::Function { params, ret, .. } => {
for param in params {
collect_interface_instantiations(param, identity, out);
}
collect_interface_instantiations(ret, identity, out);
}
Type::InterfaceRef { args, .. }
| Type::ClassRef { args, .. }
| Type::AliasRef { args, .. } => {
for arg in args {
collect_interface_instantiations(arg, identity, out);
}
}
_ => {}
}
}
/// A method resolved somewhere up a class's `extends` chain.
pub(super) struct ResolvedMethod {
/// The declared signature — unsubstituted, so callers deciding physical
/// boxing still see the raw type variables.
pub sig: MethodSig,
/// Type-parameter bindings active at the declaring class.
pub bindings: BTreeMap<String, Type>,
pub declared_by: MangledName,
pub visibility: Visibility,
}
/// [`Inferer::walk_class_chain`](Inferer::walk_class_chain) over any symbol
/// source, so the assignability resolver — which has its own lookup tables —
/// climbs chains by the same rules rather than by a second hand-rolled loop.
pub(super) fn walk_class_chain_with<T>(
lookup: impl Fn(&MangledName) -> Option<TypeSymbol>,
limits: &TypeLimits,
start: &MangledName,
start_args: &[Type],
visit: impl FnMut(&TypeSymbol, &BTreeMap<String, Type>) -> ControlFlow<Option<T>>,
) -> Option<T> {
walk_chain(lookup, limits, start, start_args, visit).0
}
/// The walk, plus whether the whole chain was seen. A chain is *not* whole when
/// a link fails to resolve or turns out not to be a class, or when a parent's
/// type arguments pass a type limit (recorded in `limits`); callers that
/// accumulate need that distinction, callers that search do not.
fn walk_chain<T>(
lookup: impl Fn(&MangledName) -> Option<TypeSymbol>,
limits: &TypeLimits,
start: &MangledName,
start_args: &[Type],
mut visit: impl FnMut(&TypeSymbol, &BTreeMap<String, Type>) -> ControlFlow<Option<T>>,
) -> (Option<T>, bool) {
let mut cur = Some((start.clone(), start_args.to_vec()));
let mut seen: Vec<MangledName> = Vec::new();
while let Some((m, cur_args)) = cur {
if seen.contains(&m) {
return (None, false);
}
seen.push(m.clone());
let Some(sym) = lookup(&m) else {
return (None, false);
};
let TypeKind::Class { generics, .. } = &sym.kind else {
return (None, false);
};
if generics.len() != cur_args.len() {
return (None, false);
}
let bindings: BTreeMap<String, Type> = generics
.iter()
.cloned()
.zip(cur_args.iter().cloned())
.collect();
if let ControlFlow::Break(answer) = visit(&sym, &bindings) {
return (answer, true);
}
cur = match parent_hop(&sym, &bindings, limits) {
Ok(hop) => hop,
Err(exceeded) => {
limits.record(exceeded);
return (None, false);
}
};
}
(None, true)
}
/// A class's own type parameters bound to themselves — the standpoint of the
/// class's own declaration, where `T` still means `T`.
fn identity_bindings(sym: &TypeSymbol) -> BTreeMap<String, Type> {
let TypeKind::Class { generics, .. } = &sym.kind else {
return BTreeMap::new();
};
generics
.iter()
.map(|g| (g.clone(), Type::TypeVar(g.clone())))
.collect()
}
/// Stand-in constructor for a class whose parent's constructor it can't know:
/// the parent is unresolvable, or its constructor is private to another module.
/// Public and variadic, at the type that silences argument diagnostics.
fn erased_constructor() -> (Vec<Param>, Visibility) {
(vec![erased_ctor_rest_param()], Visibility::Public)
}
/// The parameter of [`erased_constructor`].
fn erased_ctor_rest_param() -> Param {
Param {
name: "args".to_string(),
ty: Type::Array(Box::new(Type::Error)),
optional: false,
default: None,
rest: true,
}
}
/// Visit every class in an `extends` chain from `start`, accumulating rather
/// than searching. `None` means the chain broke — a symbol that could not be
/// resolved, or a non-class in the middle — which callers must not mistake for
/// a complete walk.
pub(super) fn for_each_class_in_chain(
lookup: impl Fn(&MangledName) -> Option<TypeSymbol>,
limits: &TypeLimits,
start: &MangledName,
start_args: &[Type],
mut visit: impl FnMut(&TypeSymbol, &BTreeMap<String, Type>),
) -> Option<()> {
let (_, whole) = walk_chain(lookup, limits, start, start_args, |sym, bindings| {
visit(sym, bindings);
ControlFlow::<Option<()>>::Continue(())
});
whole.then_some(())
}
/// One hop up an `extends` chain: the parent's mangled name paired with the
/// clause's type arguments resolved through the child's bindings. `None` for a
/// root class or a non-class symbol.
pub(super) fn parent_hop(
sym: &TypeSymbol,
bindings: &BTreeMap<String, Type>,
limits: &TypeLimits,
) -> Result<Option<(MangledName, Vec<Type>)>, TypeTooLarge> {
let TypeKind::Class {
extends: Some(extends),
..
} = &sym.kind
else {
return Ok(None);
};
let args = extends
.args
.iter()
.map(|a| substitute_typevars(a, bindings, limits))
.collect::<Result<_, _>>()?;
Ok(Some((extends.parent.clone(), args)))
}
/// A method signature with the declaring class's type parameters substituted
/// from `bindings` — param types, return, and the guard predicate's asserted
/// type. Method-level generics and doc pass through unchanged.
fn substitute_method_sig(
sig: &MethodSig,
bindings: &BTreeMap<String, Type>,
limits: &TypeLimits,
) -> Result<MethodSig, TypeTooLarge> {
use super::generic::substitute_typevars;
Ok(MethodSig {
optional: sig.optional,
generics: sig.generics.clone(),
params: sig
.params
.iter()
.map(|p| {
Ok(Param {
ty: substitute_typevars(&p.ty, bindings, limits)?,
..p.clone()
})
})
.collect::<Result<_, TypeTooLarge>>()?,
ret: substitute_typevars(&sig.ret, bindings, limits)?,
predicate: match &sig.predicate {
Some(p) => Some(crate::TypePredicate {
parameter_index: p.parameter_index,
asserted_type: substitute_typevars(&p.asserted_type, bindings, limits)?,
}),
None => None,
},
doc: sig.doc.clone(),
})
}
/// A class's own instance field `name`, if it is backed by a payload slot.
/// `None` when an accessor of that name owns the property instead: an accessor
/// appears in `fields` for typing but stores nothing, so
/// [`shadows_inherited_field`](crate::codegen::classes::shadows_inherited_field)
/// looks straight past it when laying out the payload. Every walk that reasons
/// about slot sharing has to skip the same entries, or an accessor anywhere in
/// a chain silently changes which declaration a redeclaration is checked
/// against.
fn data_field<'a>(sym: &'a TypeSymbol, name: &str) -> Option<&'a FieldSig> {
let TypeKind::Class {
fields, accessors, ..
} = &sym.kind
else {
return None;
};
if accessors.iter().any(|a| a.name() == name) {
return None;
}
fields.get(name)
}
/// One accessor half compared against the inherited declaration of the same
/// half: `subtype` must be assignable to `supertype`, and the two rendered
/// signatures are what the diagnostic prints.
struct AccessorComparison {
/// Which half this compares, so the diagnostic lands on that declaration.
half: AccessorKind,
accessor: String,
inherited: String,
redeclared: String,
subtype: Type,
supertype: Type,
}
/// Build the comparison for `own` against `inherited`, both halves of the same
/// kind. A getter is covariant in its return — a parent-typed read must see a
/// value the inherited declaration admits — and a setter contravariant in its
/// parameter, since a parent-typed write hands over whatever the inherited
/// declaration accepts. `None` when the two halves don't match, which
/// [`Inferer::ancestor_accessor`] already rules out.
fn accessor_comparison(
name: &str,
own: &AccessorSig,
inherited: &AccessorSig,
opaque: &BTreeMap<String, Type>,
limits: &TypeLimits,
) -> Result<Option<AccessorComparison>, TypeTooLarge> {
Ok(match (own, inherited) {
(
AccessorSig::Getter { ret_ty: own, .. },
AccessorSig::Getter {
ret_ty: inherited, ..
},
) => {
let own = substitute_typevars(own, opaque, limits)?;
Some(AccessorComparison {
half: AccessorKind::Get,
accessor: format!("get {name}"),
inherited: format!("get {name}(): {inherited}"),
redeclared: format!("get {name}(): {own}"),
subtype: own,
supertype: inherited.clone(),
})
}
(
AccessorSig::Setter { param: own, .. },
AccessorSig::Setter {
param: inherited, ..
},
) => {
let own = substitute_typevars(&own.ty, opaque, limits)?;
Some(AccessorComparison {
half: AccessorKind::Set,
accessor: format!("set {name}"),
inherited: format!("set {name}(v: {})", inherited.ty),
redeclared: format!("set {name}(v: {own})"),
subtype: inherited.ty.clone(),
supertype: own,
})
}
_ => None,
})
}
/// Which kind of member `sym` declares `name` as, if any. Accessors are tested
/// first: an accessor's property also appears in `fields` for typing while
/// backing no data slot (see [`data_field`]), so reading `fields` first would
/// report every accessor as a field.
fn declared_member_kind(sym: &TypeSymbol, name: &str) -> Option<MemberKind> {
let TypeKind::Class {
fields,
methods,
accessors,
..
} = &sym.kind
else {
return None;
};
if accessors.iter().any(|a| a.name() == name) {
return Some(MemberKind::Accessor);
}
if methods.contains_key(name) {
return Some(MemberKind::Method);
}
fields.contains_key(name).then_some(MemberKind::Field)
}
/// [`substitute_typevars`] applied through an accessor signature, so an
/// inherited accessor is compared at the type arguments the child's `extends`
/// clause instantiates.
fn substitute_accessor_sig(
sig: &AccessorSig,
bindings: &BTreeMap<String, Type>,
limits: &TypeLimits,
) -> Result<AccessorSig, TypeTooLarge> {
Ok(match sig {
AccessorSig::Getter { name, ret_ty } => AccessorSig::Getter {
name: name.clone(),
ret_ty: substitute_typevars(ret_ty, bindings, limits)?,
},
AccessorSig::Setter { name, param } => AccessorSig::Setter {
name: name.clone(),
param: Param {
ty: substitute_typevars(¶m.ty, bindings, limits)?,
..param.clone()
},
},
})
}
/// How a visibility renders as the source keyword that produces it. `public` is
/// the default and usually written implicitly, but a diagnostic naming the fix
/// has to spell it.
fn visibility_keyword(v: Visibility) -> &'static str {
match v {
Visibility::Public => "public",
Visibility::Private => "private",
}
}
/// What a field reads as: its declared type, widened to `T | null` when
/// optional. Shared by [`Inferer::class_field_read_ty`] and the shadowing
/// check, so the latter compares the types access sites actually see.
fn field_read_ty(field: &FieldSig) -> Type {
if field.optional {
Type::union(vec![field.ty.clone(), Type::Undefined])
} else {
field.ty.clone()
}
}
/// Build the `(params) => ret` function form of a method signature for the
/// override-compatibility check (param-contravariant, return-covariant via
/// [`super::assignable`]).
fn method_fn_type(sig: &MethodSig) -> Type {
Type::Function {
params: sig.params.iter().map(|p| p.ty.clone()).collect(),
ret: Box::new(sig.ret.clone()),
predicate: None,
has_rest: sig.params.last().is_some_and(|p| p.rest),
optional: crate::package_declaration::optional_parameter_count(&sig.params),
}
}
/// Push a fresh scope and bind the body's parameters (using the resolved
/// signature types). Mirrors the parameter-binding loop in `infer_functions`.
/// Caller owns the matching `scopes.pop()`.
fn bind_params_for_body(
tc: &mut Inferer<'_>,
params: &[crate::ParamDecl],
sig_params: &[Param],
bindings: &BTreeMap<String, Type>,
) -> Result<(Vec<TypedParam>, Vec<crate::StmtId>), CompilerFailure> {
if params.len() != sig_params.len() {
return Err(super::inference_failure(
"constructor parameter/signature length mismatch",
));
}
tc.scopes.push();
let input_types = params
.iter()
.zip(sig_params)
.map(|(p, sp)| {
substitute_typevars(&sp.ty, bindings, &tc.type_limits)
.map_err(type_limit_at(p.name.span))
})
.collect::<Result<Vec<_>, _>>()?;
let prologue = tc.infer_parameter_defaults(params, &input_types)?;
Ok((
params
.iter()
.zip(sig_params.iter())
.map(|(p, sp)| TypedParam {
name: p.name.clone(),
ty: sp.ty.clone(),
boxed: false,
rest: sp.rest,
optional: sp.optional,
default: sp.default.clone(),
})
.collect(),
prologue,
))
}
/// Signature-space scan for a `TypeVar` mention, over the one child traversal
/// that covers every `Type` variant, so this can't drift from the enum.
fn signature_mentions_typevar(ty: &Type, name: &str) -> bool {
let mut pending = vec![ty];
while let Some(ty) = pending.pop() {
if matches!(ty, Type::TypeVar(var) if var == name) {
return true;
}
crate::type_size::for_each_child(ty, |child| pending.push(child));
}
false
}
/// Re-fetch the class's bound symbol for the export surface (it was registered
/// in `bind_class`; `add_typed_type_decl` records it into the module's exports).
fn sym_for_export(tc: &Inferer<'_>, name: &Ident) -> Result<TypeSymbol, CompilerFailure> {
tc.types.lookup(&name.name).cloned().ok_or_else(|| {
super::inference_failure("missing class symbol from signature pass").with_span(name.span)
})
}
fn type_mentions_erased_parameter(ty: &Type) -> bool {
match ty.peel() {
Type::TypeVar(_) | Type::GenericParam { .. } => true,
Type::Array(elem) => type_mentions_erased_parameter(elem),
Type::Tuple(elems) => elems.iter().any(type_mentions_erased_parameter),
Type::Union(elems) => elems.iter().any(type_mentions_erased_parameter),
Type::Object { fields, index } => {
index
.as_ref()
.is_some_and(|i| type_mentions_erased_parameter(&i.value))
|| fields
.values()
.any(|field| type_mentions_erased_parameter(&field.ty))
}
Type::Function { params, ret, .. } => {
params.iter().any(type_mentions_erased_parameter) || type_mentions_erased_parameter(ret)
}
Type::InterfaceRef { args, .. }
| Type::ClassRef { args, .. }
| Type::AliasRef { args, .. } => args.iter().any(type_mentions_erased_parameter),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::super::test_support::{run, run_clean};
/// The source text a diagnostic's span covers.
fn spanned<'a>(source: &'a str, diag: &crate::Diagnostic) -> &'a str {
&source[diag.span.start as usize..diag.span.end as usize]
}
/// `get p` and `set p` are one property and one candidate, but each half is
/// compared against the inherited accessor on its own — so each mismatch has
/// to point its caret at the half that is wrong. The fixture harness matches
/// only `Diagnostic.message`, so nothing there can pin this.
#[test]
fn an_incompatible_setter_reports_on_the_setter_not_the_getter() {
let source = r#"
class Base {
private n: string = "b";
get p(): string { return this.n; }
set p(x: string | null) { this.n = x === null ? "n" : x; }
}
class Sub extends Base {
get p(): string { return "child"; }
set p(x: string) { this.q = x; }
private q: string = "";
}
export function main(): string { return "x"; }
"#;
let (_, diags) = run(source);
let reported: Vec<&crate::Diagnostic> = diags
.iter()
.filter(|d| {
d.message
.contains("is not compatible with the inherited accessor")
})
.collect();
assert_eq!(
reported.len(),
1,
"only the setter is incompatible: {:?}",
diags.iter().map(|d| &d.message).collect::<Vec<_>>()
);
assert!(
reported[0].message.contains("`set p`"),
"names the setter: {}",
reported[0].message
);
let at = spanned(source, reported[0]);
assert!(
at.starts_with("set p"),
"caret sits on the setter, not the getter above it: {at:?}"
);
}
/// See [`an_incompatible_setter_reports_on_the_setter_not_the_getter`] for
/// why this is a unit test rather than a fixture.
#[test]
fn both_accessor_halves_report_separately() {
let source = r#"
class Base {
private n: string = "b";
get p(): string { return this.n; }
set p(x: string | null) { this.n = x === null ? "n" : x; }
}
class Sub extends Base {
get p(): string | null { return null; }
set p(x: string) { this.q = x; }
private q: string = "";
}
export function main(): string { return "x"; }
"#;
let (_, diags) = run(source);
let spans: Vec<&str> = diags
.iter()
.filter(|d| {
d.message
.contains("is not compatible with the inherited accessor")
})
.map(|d| spanned(source, d))
.collect();
assert_eq!(
spans.len(),
2,
"one diagnostic per incompatible half: {:?}",
diags.iter().map(|d| &d.message).collect::<Vec<_>>()
);
assert!(
spans.iter().any(|at| at.starts_with("get p")),
"one caret on the getter: {spans:?}"
);
assert!(
spans.iter().any(|at| at.starts_with("set p")),
"one caret on the setter: {spans:?}"
);
}
#[test]
fn static_members_bind_into_the_statics_maps() {
let ta = run_clean(
r#"
export class Calc {
static readonly MAX: number = 10;
private static key(): number { return 1; }
static make(n: number): number { return Calc.key() + n; }
make(): number { return 0; }
}
"#,
);
// A static method lands in `ta.functions` under `Calc#static#name`
// (disjoint from the instance method `make`, which is vtable-bound and
// absent from the top-level functions); a static field becomes a module
// global under the same key scheme.
let fn_mangles: Vec<&str> = ta
.functions
.iter()
.map(|f| f.mangled_name.as_str())
.collect();
assert!(
fn_mangles.iter().any(|m| m.ends_with("Calc#static#make")),
"{fn_mangles:?}"
);
assert!(
fn_mangles.iter().any(|m| m.ends_with("Calc#static#key")),
"{fn_mangles:?}"
);
assert!(
ta.globals
.iter()
.any(|g| g.mangled_name.as_str().ends_with("Calc#static#MAX")),
);
// Only the public statics reach the export surface.
let export_names: Vec<&str> = ta.exports.iter().map(|e| e.public_name.as_str()).collect();
assert!(
export_names.iter().any(|m| m.ends_with("Calc#static#make")),
"{export_names:?}"
);
assert!(
export_names.iter().any(|m| m.ends_with("Calc#static#MAX")),
"{export_names:?}"
);
assert!(
!export_names.iter().any(|m| m.ends_with("Calc#static#key")),
"{export_names:?}"
);
}
#[test]
fn duplicate_static_member_diagnoses() {
let (_, diags) =
run("class C { static f(): number { return 1; } static readonly f: number = 2; }");
assert!(
diags
.iter()
.any(|d| d.message.contains("duplicate static member `f`")),
"got: {diags:?}"
);
}
#[test]
fn static_referencing_class_generic_diagnoses() {
let (_, diags) = run("class Box<T> { static id(x: T): number { return 1; } }");
assert!(
diags.iter().any(|d| d
.message
.contains("static member `id` cannot reference class type parameter `T`")),
"got: {diags:?}"
);
}
#[test]
fn constructor_calls_share_argument_diagnostics() {
let (_, diags) = run(r#"
class Point {
constructor(readonly x: number, readonly y: number = 0, ...labels: string[]) {}
move(dx: number, dy: number = 0): number { return dx + dy; }
}
class Child extends Point {
constructor() { super(); }
bad(): number { return super.move(); }
}
function main(): void { new Point(); new Point("wrong"); }
"#);
let errors: Vec<_> = diags
.iter()
.filter(|d| d.severity == crate::Severity::Error)
.collect();
assert_eq!(errors.len(), 4, "{errors:?}");
let arity: Vec<_> = errors
.iter()
.filter(|d| d.message.contains("argument(s)"))
.collect();
assert_eq!(arity.len(), 3, "{errors:?}");
assert!(arity.iter().all(|d| !d.help.is_empty()), "{errors:?}");
assert!(
arity
.iter()
.filter(|d| d.message.contains("constructor"))
.all(|d| d
.help
.iter()
.any(|h| h.contains("y?: number, ...labels: string[]"))),
"{errors:?}"
);
assert!(
arity.iter().any(|d| d
.help
.iter()
.any(|h| h.contains("Point.move(dx: number, dy?: number)"))),
"{errors:?}"
);
}
const ANIMAL: &str = r#"
class Animal {
name: string;
private sound: string;
readonly species: string;
constructor(name: string, sound: string, species: string) {
this.name = name;
this.sound = sound;
this.species = species;
}
speak(): string {
return this.name + " says " + this.sound;
}
}
"#;
#[test]
fn animal_class_typechecks() {
run_clean(ANIMAL);
}
#[test]
fn dog_extends_animal_with_super() {
let src = format!(
r#"{ANIMAL}
class Dog extends Animal {{
private tricks: string[];
constructor(name: string) {{
super(name, "woof", "canis familiaris");
this.tricks = [];
}}
learn(trick: string): void {{
this.tricks.push(trick);
}}
}}
"#
);
run_clean(&src);
}
#[test]
fn super_method_call_typechecks() {
let src = format!(
r#"{ANIMAL}
class Dog extends Animal {{
constructor(name: string) {{ super(name, "woof", "dog"); }}
speak(): string {{ return super.speak() + " (bark)"; }}
}}
"#
);
run_clean(&src);
}
#[test]
fn implicit_constructor_inherits_parent_signature() {
// `Dog` declares no constructor, so `new Dog(...)` must check against
// `Animal`'s constructor signature.
let src = format!(
r#"{ANIMAL}
class Dog extends Animal {{
bark(): string {{ return this.name; }}
}}
function make(): Dog {{ return new Dog("rex", "woof", "dog"); }}
"#
);
run_clean(&src);
}
#[test]
fn subclass_constructor_without_super_rejected() {
let src = format!(
r#"{ANIMAL}
class Dog extends Animal {{
private tricks: number;
constructor() {{ this.tricks = 0; }}
}}
"#
);
let (_, diags) = run(&src);
assert!(
diags.iter().any(|d| d.message.contains("must call `super")),
"expected a missing-super diagnostic, got: {diags:?}"
);
}
#[test]
fn read_before_super_rejected() {
let src = format!(
r#"{ANIMAL}
class Dog extends Animal {{
private tricks: number;
constructor(name: string) {{
this.tricks = 0;
super(name, "woof", "dog");
}}
}}
"#
);
let (_, diags) = run(&src);
assert!(
diags
.iter()
.any(|d| d.message.contains("before accessing `this`")),
"expected a read-before-super diagnostic, got: {diags:?}"
);
}
#[test]
fn super_method_outside_subclass_rejected() {
let src = r#"
class Animal {
name: string;
constructor(name: string) { this.name = name; }
speak(): string { return super.speak(); }
}
"#;
let (_, diags) = run(src);
assert!(
diags
.iter()
.any(|d| d.message.contains("only valid inside a subclass")),
"expected a super-outside-subclass diagnostic, got: {diags:?}"
);
}
#[test]
fn super_unknown_method_rejected() {
let src = format!(
r#"{ANIMAL}
class Dog extends Animal {{
constructor(name: string) {{ super(name, "woof", "dog"); }}
speak(): string {{ return super.nope(); }}
}}
"#
);
let (_, diags) = run(&src);
assert!(
diags.iter().any(|d| d.message.contains("no method `nope`")),
"expected an unknown-super-method diagnostic, got: {diags:?}"
);
}
#[test]
fn new_constructs_instance_type() {
let src = format!(
r#"{ANIMAL}
function make(): Animal {{
return new Animal("rex", "woof", "dog");
}}
"#
);
run_clean(&src);
}
#[test]
fn subclass_instance_assignable_to_parent() {
let src = format!(
r#"{ANIMAL}
class Dog extends Animal {{
constructor(name: string) {{ super(name, "woof", "dog"); }}
}}
function adopt(): Animal {{ return new Dog("rex"); }}
"#
);
run_clean(&src);
}
#[test]
fn class_implements_satisfied_interface() {
let src = r#"
interface Named { name(): string; }
class Person implements Named {
private who: string;
constructor(who: string) { this.who = who; }
name(): string { return this.who; }
}
"#;
run_clean(src);
}
#[test]
fn private_field_visible_within_declaring_module() {
// Module-scoped privacy: a sibling function in the same module may read
// a private field (single-file = single module).
let src = format!(
r#"{ANIMAL}
function noise(a: Animal): string {{ return a.sound; }}
"#
);
run_clean(&src);
}
#[test]
fn readonly_write_outside_constructor_rejected() {
let src = r#"
class Box {
readonly value: number;
constructor(v: number) { this.value = v; }
reset(): void { this.value = 0; }
}
"#;
let (_, diags) = run(src);
assert!(
diags.iter().any(|d| d.message.contains("readonly")),
"expected a readonly diagnostic, got: {diags:?}"
);
}
#[test]
fn bad_override_rejected() {
let src = r#"
class Base { value(): number { return 1; } }
class Sub extends Base { value(): string { return "x"; } }
"#;
let (_, diags) = run(src);
assert!(
diags.iter().any(|d| d.message.contains("override")),
"expected an override diagnostic, got: {diags:?}"
);
}
#[test]
fn extends_cycle_rejected() {
let src = r#"
class A extends B { }
class B extends A { }
"#;
let (_, diags) = run(src);
assert!(
diags
.iter()
.any(|d| d.message.contains("circular inheritance")),
"expected a cycle diagnostic, got: {diags:?}"
);
}
#[test]
fn extends_non_class_rejected() {
let src = r#"
interface Shape { area(): number; }
class Circle extends Shape { }
"#;
let (_, diags) = run(src);
assert!(
diags
.iter()
.any(|d| d.message.contains("can only `extends` another class")),
"expected an extends-non-class diagnostic, got: {diags:?}"
);
}
#[test]
fn unresolved_parent_silences_dependent_diagnostics() {
let src = r#"
interface Named { name(): string; }
class Base extends Nope implements Named { }
class Sub extends Base {
set(): void { this.count = 5; }
call(): number { return this.inherited() + super.bump(); }
}
export function main(): string {
const s = new Sub(1, 2);
return Base.make() + s.label;
}
"#;
let (_, diags) = run(src);
assert_eq!(
diags.len(),
1,
"only the `extends` clause itself should be reported, got: {diags:?}"
);
assert!(
diags[0].message.contains("unknown type `Nope`"),
"got: {diags:?}"
);
}
#[test]
fn unresolved_parent_keeps_unrelated_diagnostics() {
let src = r#"
class Broken extends Nope {
go(): number { const x: number = "oops"; return this.whatever(); }
}
"#;
let (_, diags) = run(src);
assert!(
diags
.iter()
.any(|d| d.message.contains("expected `number`, got `string`")),
"an error unrelated to inheritance must survive, got: {diags:?}"
);
assert!(
!diags.iter().any(|d| d.message.contains("whatever")),
"the member miss is unknowable, not wrong, got: {diags:?}"
);
}
#[test]
fn unresolved_parent_leaves_no_error_typed_follow_on() {
let src = r#"
class Broken extends Nope {
chain(): void { const x = this.a?.b; }
coalesce(): number { return this.n ?? 1; }
}
"#;
let (_, diags) = run(src);
assert!(
!diags.iter().any(|d| d.message.contains("<error>")),
"silencing the miss must not leave a diagnostic naming the poisoned \
type, got: {diags:?}"
);
}
#[test]
fn unresolved_parent_silences_implements_on_child_declared_first() {
let src = r#"
interface Named { name(): string; }
class Sub extends Base implements Named { }
class Base extends Nope { }
"#;
let (_, diags) = run(src);
assert_eq!(
diags.len(),
1,
"conformance is checked after every signature binds, so declaration \
order must not resurrect the cascade, got: {diags:?}"
);
assert!(
diags[0].message.contains("unknown type `Nope`"),
"got: {diags:?}"
);
}
#[test]
fn implements_still_rejected_when_a_later_parent_lacks_the_member() {
let src = r#"
interface Named { name(): string; }
class Sub extends Base implements Named { }
class Base { other(): number { return 1; } }
"#;
let (_, diags) = run(src);
assert!(
diags
.iter()
.any(|d| d.message.contains("does not implement")
&& d.message.contains("missing member `name`")),
"deferring the check must not silence a genuinely unsatisfied \
interface, got: {diags:?}"
);
}
#[test]
fn implements_satisfied_by_a_later_declared_parent() {
let src = r#"
interface Named { name(): string; }
class Sub extends Base implements Named { }
class Base { name(): string { return "b"; } }
"#;
let (_, diags) = run(src);
assert!(diags.is_empty(), "got: {diags:?}");
}
#[test]
fn resolved_parent_still_reports_missing_members() {
let src = r#"
class Base { m(): number { return 1; } }
class Sub extends Base { go(): number { return this.nope(); } }
"#;
let (_, diags) = run(src);
assert!(
diags
.iter()
.any(|d| d.message.contains("field `nope` does not exist on `Sub`")),
"a known parent chain still knows what is missing, got: {diags:?}"
);
}
#[test]
fn unsatisfied_implements_rejected() {
let src = r#"
interface Named { name(): string; }
class Anon implements Named { }
"#;
let (_, diags) = run(src);
let diag = diags
.iter()
.find(|d| d.message.contains("does not implement"))
.unwrap_or_else(|| panic!("expected an implements diagnostic, got: {diags:?}"));
assert!(
diag.message.contains("missing member `name`"),
"expected the message to name the missing member, got: {}",
diag.message
);
assert!(
diag.help.iter().any(|h| h.contains("interface Named")),
"expected the help to lift the interface shape, got: {:?}",
diag.help
);
}
#[test]
fn implements_wrong_signature_rejected() {
let src = r#"
interface Named { name(): string; }
class Bad implements Named {
name(): number { return 1; }
}
"#;
let (_, diags) = run(src);
let diag = diags
.iter()
.find(|d| d.message.contains("does not implement"))
.unwrap_or_else(|| panic!("expected an implements diagnostic, got: {diags:?}"));
assert!(
diag.message
.contains("member `name` has an incompatible signature"),
"expected the message to flag the incompatible member, got: {}",
diag.message
);
assert!(
diag.help.iter().any(|h| h.contains("Bad.name")),
"expected the help to lift the class's actual signature, got: {:?}",
diag.help
);
}
#[test]
fn implements_wrong_arity_rejected() {
// A method may declare fewer parameters, as in TypeScript, but not more.
let src = r#"
interface Greeter { greet(n: number): number; }
class Bad implements Greeter {
greet(n: number, m: number): number { return n + m; }
}
"#;
let (_, diags) = run(src);
assert!(
diags
.iter()
.any(|d| d.message.contains("does not implement")
&& d.message
.contains("member `greet` has an incompatible signature")),
"expected a wrong-arity implements diagnostic, got: {diags:?}"
);
}
}
#[cfg(test)]
mod invariant_tests {
use super::*;
#[test]
fn missing_class_metadata_stops_descriptor_and_export_construction() {
super::super::test_support::with_inferer(|tc| {
let name = Ident {
name: "Missing".into(),
span: Span::at(crate::FileId(0)),
};
assert!(matches!(
sym_for_export(tc, &name),
Err(CompilerFailure::Internal { .. })
));
let ty = Type::class_ref(
crate::Package("missing".into()),
"Missing",
crate::mangle::package_symbol("missing", "Missing"),
Vec::new(),
);
assert!(matches!(
tc.record_runtime_type_test(&ty),
Err(CompilerFailure::Internal { .. })
));
assert!(!tc.typed_ast.runtime_class_fields.contains_key(&ty));
});
}
}
#[cfg(test)]
mod review_regressions {
use super::super::test_support::{run, with_source_inferer};
use super::*;
#[test]
fn missing_guarded_field_stops_runtime_metadata_construction() {
with_source_inferer("class C {}", |tc| {
assert!(tc.signatures().unwrap());
let symbol = tc.types.lookup_mut("C").unwrap();
let mangled = symbol.mangled_name.clone();
let TypeKind::Class {
narrowing_checks, ..
} = &mut symbol.kind
else {
panic!("class signature");
};
narrowing_checks.insert(
"missing".into(),
crate::FieldNarrowingCheck {
declaration: Some(mangled.clone()),
test: crate::FieldNarrowingTest::NonNull,
minimal_test_target: None,
message: "test guard".into(),
},
);
let ty = Type::class_ref(
crate::Package(tc.package_name.into()),
"C",
mangled,
Vec::new(),
);
assert!(matches!(
tc.record_runtime_type_test(&ty),
Err(CompilerFailure::Internal { .. })
));
assert!(!tc.typed_ast.runtime_field_guards.contains_key(&ty));
assert!(!tc.typed_ast.runtime_class_fields.contains_key(&ty));
});
}
#[test]
fn duplicate_methods_and_inheritance_cycles_remain_source_errors() {
for source in [
"class C { value: number = 1; m(): number { return 1; } } class C {} function main(): number { return 0; }",
"class C { value: number = 1; } interface C { x: number; } function main(): number { return 0; }",
"class C { m(): number { return 1; } m(x: number): number { return x; } } function main(): number { return 0; }",
"class C { static m(): number { return 1; } static m(x: number): number { return x; } } function main(): number { return 0; }",
"class A extends B { constructor() { super(); } } class B extends A { constructor() { super(); } } function main(): number { const a = new A(); return 0; }",
] {
let (_, diagnostics) = run(source);
assert!(
diagnostics
.iter()
.any(|diagnostic| diagnostic.severity == crate::Severity::Error)
);
assert!(
!diagnostics
.iter()
.any(|diagnostic| diagnostic.message.contains("internal compiler failure")),
"{diagnostics:?}"
);
}
}
#[test]
fn missing_class_and_member_signatures_are_fatal_without_source_errors() {
let source = "class C { value: number = 1; m(): number { return 1; } static s(): number { return 2; } }";
for missing in ["class", "field", "method", "static", "parameter-property"] {
let source = if missing == "parameter-property" {
"class C { constructor(public value: number) {} }"
} else {
source
};
with_source_inferer(source, |tc| {
assert!(tc.signatures().unwrap());
assert!(tc.diagnostics.is_empty());
if missing == "class" {
tc.types = super::super::TypeNamespace::new();
} else {
let TypeKind::Class {
fields,
methods,
statics,
..
} = &mut tc.types.lookup_mut("C").unwrap().kind
else {
panic!("class signature");
};
match missing {
"field" | "parameter-property" => fields.clear(),
"method" => methods.clear(),
"static" => statics.clear(),
_ => panic!("test case"),
}
}
assert!(
matches!(tc.infer_classes(), Err(CompilerFailure::Internal { .. })),
"{missing}"
);
assert!(
tc.typed_ast.types.is_empty(),
"failed class must not be published"
);
});
}
}
}