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
//! Generic inference — body walks for generic and non-generic function decls,
//! call-site type-param unification, and the GP→TypeVar erasure pass.
//!
//! Invariant: `GenericParam`s are allocated in `infer_functions` and live only
//! inside `scopes`/`current_return` during the body walk. Downstream passes
//! (PackageDeclaration, codegen) see only `TypeVar`s.
use crate::compiler_error::CompilerFailure;
use std::collections::BTreeMap;
use crate::{
ExprId, ExprKind, Ident, MethodSig, Span, StmtKind, Type, TypeAnnotation, TypedExprKind,
TypedParam, TypedStmt, TypedStmtKind, ValueKind,
};
use super::{Inferer, type_limit_at};
use crate::type_size::{TypeBudget, TypeLimits, TypeTooLarge, map_children};
use crate::typechecker::type_param_substitution::{CloseMatch, TypeParamSubstitution, UnifyError};
/// What a receiver-less generic call is calling. Only diagnostics differ: a
/// constructor has to be described as one, because `function Box<T>(…)` is not
/// a form anyone can write and `Box<string>(…)` without `new` is two more
/// errors.
#[derive(Clone, Copy, PartialEq)]
pub(super) enum GenericCallee {
Function,
Constructor,
}
impl GenericCallee {
/// How the diagnostic names the thing being called.
fn subject(self, name: &str, generics: &[String]) -> String {
match self {
Self::Function => format!("`{name}`"),
Self::Constructor if generics.is_empty() => format!("constructor of `{name}`"),
Self::Constructor => {
format!("constructor of `{name}<{}>`", generics.join(", "))
}
}
}
/// The "add an explicit type argument" hint, in a form that compiles: every
/// parameter has to be listed, not just the ones inference failed on, or
/// following the hint trades this error for an arity error.
fn explicit_arg_hint(
self,
name: &str,
generics: &[String],
sub: &crate::typechecker::type_param_substitution::TypeParamSubstitution,
limits: &TypeLimits,
) -> String {
let args = generics
.iter()
.map(|g| {
// Leave an uninferable parameter as its own name for the
// caller to replace; show the ones inference did settle. One
// too large to build is left for the caller too.
match sub.apply(&Type::TypeVar(g.clone()), limits) {
Ok(Type::TypeVar(n)) if n == g[..] => g.clone(),
Ok(resolved) => resolved.to_string(),
Err(exceeded) => {
limits.record(exceeded);
g.clone()
}
}
})
.collect::<Vec<_>>()
.join(", ");
match self {
Self::Function => {
format!("add an explicit type argument: `{name}<{args}>(…)`")
}
Self::Constructor => {
format!("add an explicit type argument: `new {name}<{args}>(…)`")
}
}
}
}
use super::format_signature::SignatureKind;
use crate::Param;
/// Replaces each `TypeVar` bound in `bindings` with its binding, once: unlike
/// [`TypeParamSubstitution::apply`] it does not chase variables inside a
/// binding. Fails, without building the rest, once the result passes a type
/// limit.
///
/// [`TypeParamSubstitution::apply`]: crate::typechecker::type_param_substitution::TypeParamSubstitution::apply
pub(super) fn substitute_typevars(
ty: &Type,
bindings: &BTreeMap<String, Type>,
limits: &TypeLimits,
) -> Result<Type, TypeTooLarge> {
substitute_at(ty, bindings, 1, &mut limits.budget())
}
/// [`substitute_typevars`] where the caller cannot return an error: a type past
/// a limit is recorded in `limits` and comes back as `Type::Error`.
pub(super) fn substitute_or_record(
ty: &Type,
bindings: &BTreeMap<String, Type>,
limits: &TypeLimits,
) -> Type {
limits.type_or_error(substitute_typevars(ty, bindings, limits))
}
fn substitute_at(
ty: &Type,
bindings: &BTreeMap<String, Type>,
depth: u32,
budget: &mut TypeBudget<'_>,
) -> Result<Type, TypeTooLarge> {
if let Type::TypeVar(name) = ty
&& let Some(bound) = bindings.get(name)
{
budget.charge_copy(bound, depth)?;
return Ok(bound.clone());
}
budget.charge(depth)?;
let child = depth.saturating_add(1);
map_children(ty, |inner| substitute_at(inner, bindings, child, budget))
}
pub(super) fn erase_generic_params(ty: &Type) -> Type {
match ty {
Type::Refined { original, ty } => Type::Refined {
original: Box::new(erase_generic_params(original)),
ty: Box::new(erase_generic_params(ty)),
},
Type::GenericParam { name, .. } => Type::TypeVar(name.clone()),
Type::Object { fields, index } => Type::Object {
index: index.as_ref().map(|i| i.map_value(erase_generic_params)),
fields: fields
.iter()
.map(|(k, v)| {
(
k.clone(),
crate::ObjectField {
ty: erase_generic_params(&v.ty),
optional: v.optional,
readonly: v.readonly,
method: v.method,
},
)
})
.collect(),
},
Type::Array(elem) => Type::Array(Box::new(erase_generic_params(elem))),
Type::Readonly(inner) => Type::Readonly(Box::new(erase_generic_params(inner))),
Type::Tuple(elements) => Type::Tuple(elements.map(erase_generic_params)),
Type::Function {
params,
ret,
predicate,
has_rest,
optional,
} => Type::Function {
params: params.iter().map(erase_generic_params).collect(),
ret: Box::new(erase_generic_params(ret)),
predicate: predicate.as_ref().map(|p| {
Box::new(crate::TypePredicate {
parameter_index: p.parameter_index,
asserted_type: erase_generic_params(&p.asserted_type),
})
}),
has_rest: *has_rest,
optional: *optional,
},
Type::InterfaceRef {
mangled,
package,
name,
args,
} => Type::InterfaceRef {
mangled: mangled.clone(),
package: package.clone(),
name: name.clone(),
args: args.iter().map(erase_generic_params).collect(),
},
Type::ClassRef {
mangled,
package,
name,
args,
} => Type::ClassRef {
mangled: mangled.clone(),
package: package.clone(),
name: name.clone(),
args: args.iter().map(erase_generic_params).collect(),
},
Type::Union(members) => Type::union(members.iter().map(erase_generic_params).collect()),
Type::Alias {
mangled,
package,
name,
args,
ty: inner,
} => Type::Alias {
mangled: mangled.clone(),
package: package.clone(),
name: name.clone(),
args: args.iter().map(erase_generic_params).collect(),
ty: Box::new(erase_generic_params(inner)),
},
Type::AliasRef {
mangled,
package,
name,
args,
} => Type::AliasRef {
mangled: mangled.clone(),
package: package.clone(),
name: name.clone(),
args: args.iter().map(erase_generic_params).collect(),
},
Type::TypeVar(_)
| Type::Number
| Type::BigInt
| Type::BigIntLiteral(_)
| Type::NumberLiteral(_)
| Type::String
| Type::StringLiteral(_)
| Type::Uint8Array
| Type::Boolean
| Type::BooleanLiteral(_)
| Type::Null
| Type::Undefined
| Type::Void
| Type::Never
| Type::Unknown
| Type::Error
| Type::NumberEnum { .. }
| Type::StringEnum { .. } => ty.clone(),
}
}
/// Erase a typed expression's own type *and* every type embedded in its kind.
///
/// The node's `ty` is not the only spelling that escapes: an object literal's
/// field types become the key the shape collector and codegen agree on, a
/// closure's parameter types become its signature, and so on. Leaving those as
/// `GenericParam` while the node's `ty` says `TypeVar` produces two spellings
/// of one shape, and codegen then fails to find what it registered.
pub(super) fn erase_generic_params_in_expr(expr: &mut crate::TypedExpr) {
expr.ty = erase_generic_params(&expr.ty);
match &mut expr.kind {
TypedExprKind::ObjectLiteral { fields, .. } => {
for f in fields {
f.ty = erase_generic_params(&f.ty);
}
}
TypedExprKind::ArrayLiteral { element_ty, .. } => {
*element_ty = erase_generic_params(element_ty);
}
TypedExprKind::TupleLiteral { element_types, .. } => {
for t in element_types {
*t = erase_generic_params(t);
}
}
TypedExprKind::Closure {
params,
return_type,
captured,
..
} => {
for p in params {
p.ty = erase_generic_params(&p.ty);
}
*return_type = erase_generic_params(return_type);
for c in captured {
c.ty = erase_generic_params(&c.ty);
}
}
TypedExprKind::GenericCall {
type_args,
return_cast,
..
} => {
for arg in type_args {
*arg = erase_generic_params(arg);
}
if let Some(t) = return_cast {
*t = erase_generic_params(t);
}
}
TypedExprKind::GenericMethodCall {
return_cast: Some(t),
..
} => {
*t = erase_generic_params(t);
}
TypedExprKind::InstanceOf { class, .. } => {
*class = erase_generic_params(class);
}
TypedExprKind::Cast { target_ty, .. } => {
*target_ty = erase_generic_params(target_ty);
}
_ => {}
}
}
pub(super) fn erase_generic_params_in_stmt(stmt: &mut TypedStmt) {
match &mut stmt.kind {
TypedStmtKind::Let { ty, .. } | TypedStmtKind::Const { ty, .. } => {
*ty = erase_generic_params(ty);
}
_ => {}
}
}
/// True when a generic wrapper's declared return lowers to the universal
/// `(ref null $Object)` slot, so the substituted call result must be cast
/// back to its concrete shape at the call boundary. Covers a bare `T`, an
/// erased union (`T | null` and friends), and `unknown` — mirrors the
/// `needs_box` shape used for the non-generic-method return path.
fn return_erases_to_object_slot(ret: &Type) -> bool {
matches!(
ret.peel(),
Type::TypeVar(_) | Type::Unknown | Type::Union(_)
)
}
impl Inferer<'_> {
fn resolve_call_type_argument(
&mut self,
annot: &TypeAnnotation,
subject: &str,
) -> Result<Type, CompilerFailure> {
let resolved = self.resolve_type(annot)?;
if let Some(offender) = super::value_operand::valueless_within_type_argument(&resolved) {
let offender = offender.clone();
self.error(
annot.span,
format!(
"`{offender}` cannot be used as a type argument to {subject} — use a value type"
),
);
return Ok(Type::Error);
}
Ok(resolved)
}
/// Structural retry for unification: when a direct param/arg unify fails
/// and the param (or a union member of it) is an interface, bind its type
/// params by unifying member signatures against the arg's own interface
/// form. The structural counterpart of nominal arg unification — keyed on
/// [`Type::interface_routing`], never on interface names.
fn structural_member_unify(
&mut self,
sub: &mut crate::typechecker::type_param_substitution::TypeParamSubstitution,
param_ty: &Type,
arg_ty: &Type,
) -> bool {
let members: Vec<Type> = match param_ty.peel() {
Type::Union(ms) => ms.clone(),
other => vec![other.clone()],
};
let Some((ma, _pa, na, aa)) = arg_ty.interface_routing() else {
return false;
};
let Some(actual_form) = self.structural_form(&ma, na, &aa) else {
return false;
};
for member in &members {
// An object type routes to the `Object` interface, whose members
// every value has; its own fields are unified directly. A type
// parameter's binding is not a structural member to fill in.
if matches!(member.peel(), Type::Object { .. } | Type::TypeVar(_)) {
continue;
}
let Some((me, _pe, ne, ae)) = member.interface_routing() else {
continue;
};
if me == ma {
continue;
}
let Some(expected_form) = self.structural_form(&me, ne, &ae) else {
continue;
};
if expected_form.is_empty() {
continue;
}
let snapshot = sub.clone();
let resolver = self.resolver();
let all = expected_form.iter().all(|(name, exp)| {
actual_form
.get(name)
.is_some_and(|act| sub.unify(&exp.ty, &act.ty, resolver).is_ok())
});
if all {
return true;
}
*sub = snapshot;
}
false
}
pub(super) fn infer_functions(&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 span = stmt.span;
let StmtKind::Function {
name,
params,
body,
doc,
..
} = stmt.kind
else {
continue;
};
let (generic_names, sig_param_types, sig_ret_type, sig_param_defaults): (
Vec<String>,
Vec<Type>,
Type,
Vec<Option<crate::DefaultValue>>,
) = match self.top_symbols.get(&name.name) {
Some(entry) => match &entry.kind {
ValueKind::Function {
generics,
params,
ret,
..
} => (
generics.clone(),
params.iter().map(|p| p.ty.clone()).collect(),
ret.clone(),
params.iter().map(|p| p.default.clone()).collect(),
),
_ => (
Vec::new(),
vec![Type::Error; params.len()],
Type::Error,
vec![None; params.len()],
),
},
None => (
Vec::new(),
vec![Type::Error; params.len()],
Type::Error,
vec![None; params.len()],
),
};
let resolved_predicate = match self.top_symbols.get(&name.name) {
Some(entry) => match &entry.kind {
ValueKind::Function { type_predicate, .. } => type_predicate.clone(),
_ => None,
},
None => None,
};
let body_instantiation = self.push_body_generics(generic_names.clone())?;
let body_param_types: Vec<Type> = sig_param_types
.iter()
.map(|t| substitute_typevars(t, &body_instantiation, &self.type_limits))
.collect::<Result<_, _>>()
.map_err(type_limit_at(name.span))?;
let body_ret_type =
substitute_typevars(&sig_ret_type, &body_instantiation, &self.type_limits)
.map_err(type_limit_at(name.span))?;
// typed_params stores signature TypeVars, not body GPs — GPs must
// not escape the body; PackageDeclaration and codegen read these externally.
let typed_params: Vec<TypedParam> = params
.iter()
.zip(sig_param_types.iter())
.zip(sig_param_defaults.iter())
.map(|((p, ty), default)| TypedParam {
name: p.name.clone(),
ty: ty.clone(),
boxed: false,
rest: p.rest,
optional: p.is_omittable(),
default: default.clone(),
})
.collect();
let stored_return = sig_ret_type.clone();
self.scopes.push();
let prev_return = self.current_return.replace(body_ret_type.clone());
// Reset to `true`: a previous function that ended unreachable would
// otherwise taint this body's reachability joins, dropping post-if
// narrowings.
let prev_reachable = self.enter_body_reachability();
let prev_predicate = self.current_type_predicate.take();
if let Some(pred) = &resolved_predicate {
let idx = pred.parameter_index as usize;
if let Some(param) = params.get(idx) {
self.current_type_predicate = Some((pred.clone(), param.name.name.clone()));
}
}
// Snapshot arena lengths to bound which IDs this body walk allocates —
// only those need GP erasure.
let exprs_before = self.typed_ast.exprs_len();
let stmts_before = self.typed_ast.stmts_len();
let prologue = self.infer_parameter_defaults(¶ms, &body_param_types)?;
let body_id = self
.infer_body_with_narrowing_boundary(body)?
.ok_or_else(|| {
super::inference_failure("function body is a Block, never a type-only decl")
})?;
let body_id = self.prepend_parameter_defaults(prologue, body_id)?;
self.current_return = prev_return;
self.current_type_predicate = prev_predicate;
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)?,
);
}
let ret_type = stored_return;
let mangled_name = self.mangle_top_symbol(&name.name)?;
self.add_typed_function(crate::TypedFunction {
name,
mangled_name,
generics: generic_names,
params: typed_params,
return_type: ret_type,
type_predicate: resolved_predicate,
body: body_id,
doc,
span,
})?;
}
Ok(())
}
/// Generic interface-method dispatch. Pre-seeds the unification map with the
/// receiver's interface bindings so interface-level and method-level generics
/// share one map — method-level unification won't accidentally rebind them.
#[allow(clippy::too_many_arguments)]
pub(super) fn infer_generic_method_call(
&mut self,
typed_receiver: ExprId,
iface_mangled: crate::MangledName,
name: Ident,
sig: MethodSig,
interface_bindings: BTreeMap<String, Type>,
type_args: Option<Vec<TypeAnnotation>>,
args: Vec<ExprId>,
expected: Option<&Type>,
span: Span,
) -> Result<(TypedExprKind, Type), CompilerFailure> {
// The no-mapper form preserves the source type; the mapped form has
// an independent result parameter, like TypeScript's two overloads.
let mut sig = sig;
if iface_mangled == crate::mangle::prelude("ArrayConstructor")
&& name.name == "from"
&& args.len() == 1
{
sig.generics = vec!["T".into()];
sig.ret = Type::Array(Box::new(Type::TypeVar("T".into())));
sig.params
.get_mut(1)
.ok_or_else(|| super::inference_failure("missing Array.from map parameter"))?
.ty = Type::Undefined;
}
let receiver_ty = self
.typed_ast
.try_expr(typed_receiver)
.map_err(crate::typechecker::arena_failure)?
.ty
.clone();
let mut sub = TypeParamSubstitution::new();
for (k, v) in interface_bindings {
sub.insert(k, v);
}
if let Some(targs) = &type_args {
if targs.len() != sig.generics.len() {
let help = self.format_signature(SignatureKind::Method {
receiver_ty: &receiver_ty,
name: &name.name,
sig: &sig,
});
self.error_with_help(
span,
format!(
"method `{}` expects {} type argument(s), got {}",
name.name,
sig.generics.len(),
targs.len(),
),
vec![help],
);
}
let subject = format!("method `{}`", name.name);
for (gname, annot) in sig.generics.iter().zip(targs.iter()) {
let resolved = self.resolve_call_type_argument(annot, &subject)?;
sub.insert(gname.clone(), resolved);
}
}
if let Some(want) = expected.filter(|want| pins_type_parameters(want)) {
self.bind_from_expected_result(&mut sub, &sig.ret, want);
}
let has_rest = sig.params.last().is_some_and(|p| p.rest);
let fixed_count = sig.params.iter().take_while(|p| !p.rest).count();
let max_args = if has_rest {
usize::MAX
} else {
sig.params.len()
};
let min_args = super::expr::required_parameter_count(&sig.params);
let arity_ok = args.len() >= min_args && args.len() <= max_args;
if !arity_ok {
let help = self.format_signature(SignatureKind::Method {
receiver_ty: &receiver_ty,
name: &name.name,
sig: &sig,
});
let msg = if has_rest {
format!(
"method `{}` expects {}+ argument(s), got {}",
name.name,
min_args,
args.len(),
)
} else if min_args == max_args {
format!(
"method `{}` expects {} argument(s), got {}",
name.name,
max_args,
args.len(),
)
} else {
format!(
"method `{}` expects {}-{} argument(s), got {}",
name.name,
min_args,
max_args,
args.len(),
)
};
self.error_with_help(span, msg, vec![help]);
}
let rest_elem_ty: Type = if has_rest {
match &sig
.params
.last()
.ok_or_else(|| super::inference_failure("rest signature has no parameters"))?
.ty
.rest_element()
{
Some(elem) => Type::clone(elem),
None => Type::Error,
}
} else {
Type::Error
};
let signature_help = |this: &mut Self| {
this.format_signature(SignatureKind::Method {
receiver_ty: &receiver_ty,
name: &name.name,
sig: &sig,
})
};
let errors_before_args = self.error_count();
let inferred_generics: &[String] = if type_args.is_some() {
&[]
} else {
&sig.generics
};
let (mut typed_args, argument_checks) = self.infer_generic_arguments(
&args,
&sig.params,
&sig.ret,
inferred_generics,
&rest_elem_ty,
&mut sub,
signature_help,
)?;
if has_rest || typed_args.len() < sig.params.len() {
self.typed_ast
.record_authored_arguments(span, typed_args.clone());
}
if arity_ok {
self.fill_omitted_defaults(&sig.params, args.len(), span, &mut typed_args)?;
}
if arity_ok && has_rest {
self.pack_rest_tail(fixed_count, rest_elem_ty.clone(), span, &mut typed_args)?;
}
let array_from =
iface_mangled == crate::mangle::prelude("ArrayConstructor") && name.name == "from";
let array_from_mapper = array_from && sig.generics.len() == 2;
let mapper_type = typed_args
.get(1)
.map(|id| {
Ok::<_, crate::compiler_error::CompilerFailure>(
self.typed_ast
.try_expr(*id)
.map_err(crate::typechecker::arena_failure)?
.ty
.clone(),
)
})
.transpose()?;
// An array-like `{ length }` has no elements to infer the element type
// from.
if array_from
&& let Some(element) = sig.generics.first()
&& sub.get(element).is_none()
{
sub.insert(element.clone(), Type::Unknown);
}
let array_like = if array_from {
self.array_like_source(&typed_args)?
} else {
None
};
if array_from_mapper && array_like.is_some() {
self.reject_array_like_element_annotation(&typed_args, mapper_type.as_ref())?;
}
if array_from_mapper
&& mapper_type
.as_ref()
.is_some_and(|ty| ty.peel() == &Type::Undefined)
{
let element = sub
.apply(&Type::TypeVar("T".into()), &self.type_limits)
.map_err(type_limit_at(span))?;
sub.insert("U".into(), element);
}
sub.bind_whole_union_fallbacks();
let close_match_spans = self.check_deferred_close_matches(&mut sub, span);
self.bind_leftover_type_parameters(
&mut sub,
&sig.generics,
&sig.ret,
expected,
errors_before_args,
);
self.bind_uninferred_to_unknown(&mut sub, &sig.generics, &iface_mangled, span)?;
if let Err(unbound) = sub
.resolve_all(&sig.generics, &self.type_limits)
.map_err(type_limit_at(span))?
{
self.error_with_help(
span,
format!(
"cannot infer type parameter(s) {} for method `{}`; consider adding an explicit type argument",
unbound
.iter()
.map(|n| format!("`{n}`"))
.collect::<Vec<_>>()
.join(", "),
name.name,
),
vec![format!(
"add an explicit type argument: `receiver.{}<T>(…)`",
name.name
)],
);
}
self.check_arguments_after_inference(&sub, argument_checks, &close_match_spans)?;
if array_from && !array_from_mapper && array_like.is_some() {
let element = self.instantiate(&sub, &Type::TypeVar("T".into()), span)?;
self.reject_array_like_element_type(&element, span);
}
let mut result_ty = self.instantiate(&sub, &sig.ret, span)?;
if array_from_mapper && mapper_type.as_ref().is_some_and(|ty| {
matches!(ty.peel(), Type::Union(members) if members.iter().any(|member| member.peel() == &Type::Undefined))
}) {
result_ty = Type::Array(Box::new(Type::union(vec![
self.instantiate(&sub, &Type::TypeVar("T".into()), span)?,
self.instantiate(&sub, &Type::TypeVar("U".into()), span)?,
])));
}
let type_predicate = match &sig.predicate {
Some(p) => Some(Box::new(crate::TypePredicate {
parameter_index: p.parameter_index,
asserted_type: self.instantiate(&sub, &p.asserted_type, span)?,
})),
None => None,
};
self.record_generic_call_arguments(&typed_args, &sig.params, &sig.ret, type_args.is_some());
// TypeVar params/return need box/cast at the Wasm boundary; composite types use plain MethodCall.
let any_generic_arg = sig.params.iter().any(|p| matches!(p.ty, Type::TypeVar(_)));
// The wrapper erases any TypeVar-mentioning return to `$Object`, so the
// substituted result needs a cast back to its static shape — not only a
// bare `V`, but also `V | null` and other erased unions (their object
// members lower to the narrower `$ObjectShape`).
let return_needs_cast = return_erases_to_object_slot(&sig.ret);
if any_generic_arg || return_needs_cast {
let generic_args: Vec<crate::GenericArgument> = typed_args
.into_iter()
.zip(sig.params.iter())
.map(|(expr, p)| crate::GenericArgument {
expr,
is_generic: matches!(p.ty, Type::TypeVar(_)),
})
.collect();
let return_cast = if return_needs_cast {
Some(result_ty.clone())
} else {
None
};
return Ok((
TypedExprKind::GenericMethodCall {
receiver: typed_receiver,
iface: iface_mangled,
name,
args: generic_args,
return_cast,
type_predicate,
},
result_ty,
));
}
// sub carries interface bindings even when the method itself isn't generic.
Ok((
TypedExprKind::MethodCall {
receiver: typed_receiver,
iface: iface_mangled,
name,
args: typed_args,
type_predicate,
},
result_ty,
))
}
/// The lifted signature a generic-call diagnostic shows: a real function
/// signature, or a class header with its constructor line.
fn generic_callee_lift(
&self,
callee: GenericCallee,
callee_ident: &Ident,
generics: &[String],
params: &[Param],
ret: &Type,
) -> String {
match callee {
GenericCallee::Function => {
let doc = self.lookup_function_doc(&callee_ident.name);
self.format_signature(SignatureKind::Function {
name: &callee_ident.name,
predicate: None,
generics,
params,
ret,
doc: doc.as_ref(),
})
}
GenericCallee::Constructor => {
let header = if generics.is_empty() {
callee_ident.name.clone()
} else {
format!("{}<{}>", callee_ident.name, generics.join(", "))
};
let rendered: Vec<String> = params
.iter()
.map(|p| format!("{}: {}", p.name, p.ty))
.collect();
format!("class {header} {{ constructor({}); }}", rendered.join(", "))
}
}
}
/// Bind the type parameters the arguments left open: from an `unknown`
/// expected result, which [`pins_type_parameters`] kept out of the
/// bindings made before the arguments; then, if an argument was reported
/// wrong (it may be what would have bound one), to `Error`, so the
/// parameter isn't reported as uninferable too.
fn bind_leftover_type_parameters(
&self,
sub: &mut TypeParamSubstitution,
generics: &[String],
ret: &Type,
expected: Option<&Type>,
errors_before_args: usize,
) {
if let Some(want) = expected.filter(|want| !pins_type_parameters(want)) {
let _ = sub.unify(ret, want, self.resolver());
}
if self.error_count() > errors_before_args
&& let Err(exceeded) = bind_remaining(sub, generics, Type::Error, &self.type_limits)
{
self.type_limits.record(exceeded);
}
}
/// Bind type parameters from the type a call's result is expected to have,
/// before its arguments are inferred, as bindings an argument may still
/// replace (see [`TypeParamSubstitution::mark_from_expected_result`]).
///
/// The expected type is not an argument, so the union members it closely
/// matches are not checked.
fn bind_from_expected_result(&self, sub: &mut TypeParamSubstitution, ret: &Type, want: &Type) {
let before = sub.clone();
self.bind_from_expected_type(sub, ret, want);
sub.mark_from_expected_result(&before);
sub.forget_close_matches_after(before.close_match_count());
}
/// Bind type parameters by unifying the result type `ret` with `want`.
///
/// When `want` is a union and the result type is neither a type
/// variable nor a union (both unify with the whole union), the result is
/// unified with each member of its own [`ShapeKind`]. The type parameters
/// bind only if every such member unifies, all to the same bindings;
/// otherwise nothing binds. `Cmp<T>` expected as `Cmp<P> | null` binds
/// `T = P`.
///
/// Adopting a partial match would fix the type parameters before the
/// arguments are seen, although the result could still be assigned to a
/// member unification can't match, such as a wider object or an interface.
/// A mismatch is reported later, where the call's result is checked
/// against the expected type.
fn bind_from_expected_type(&self, sub: &mut TypeParamSubstitution, ret: &Type, want: &Type) {
// A result with several bare type parameters (`A | B`) can't say which
// of them takes which part of `want`: tsc gives each the whole of it,
// where pairing members would bind `A` to one literal of a `Mode`.
if let Type::Union(members) = ret.peel() {
let bare: Vec<&String> = members
.iter()
.filter_map(|member| match member.peel() {
Type::TypeVar(name) if sub.is_unbound(name) => Some(name),
_ => None,
})
.collect();
if bare.len() > 1 {
for name in bare {
sub.insert(name.clone(), want.clone());
}
return;
}
}
let unifies_with_whole_union = matches!(ret.peel(), Type::TypeVar(_) | Type::Union(_));
let members = match want.peel() {
Type::Union(members) if !unifies_with_whole_union => members,
_ => {
let _ = sub.unify(ret, want, self.resolver());
return;
}
};
let ret_kind = ShapeKind::of(ret);
let mut agreed: Option<TypeParamSubstitution> = None;
for member in members {
if !ret_kind.could_be(ShapeKind::of(member)) {
continue;
}
let mut trial = sub.clone();
if trial.unify(ret, member, self.resolver()).is_err() {
return;
}
match &agreed {
Some(bindings) if *bindings != trial => return,
_ => agreed = Some(trial),
}
}
if let Some(bindings) = agreed {
*sub = bindings;
}
}
/// Bind the type parameters of a program's own generic that nothing
/// inferred to `unknown`, as tsc does: every type is assignable to it.
/// Built-in generics keep reporting them, since tsc gives several of them
/// `any` instead (`new Map()` is `Map<any, any>`), which a later use may
/// still resolve here (`new Map().set(k, v)`).
fn bind_uninferred_to_unknown(
&self,
sub: &mut TypeParamSubstitution,
generics: &[String],
declared_by: &crate::MangledName,
span: Span,
) -> Result<(), CompilerFailure> {
if crate::mangle::is_builtin(declared_by) {
return Ok(());
}
bind_remaining(sub, generics, Type::Unknown, &self.type_limits).map_err(type_limit_at(span))
}
/// Report each union argument member that closely matched a parameter
/// member while inference ran and fits no member of the parameter now
/// that it is done, against the member it closely matched, at its
/// argument (or at the call at `span` when no argument was located).
/// Returns where each was reported.
fn check_deferred_close_matches(
&mut self,
sub: &mut TypeParamSubstitution,
span: Span,
) -> Vec<Span> {
let mut reported = Vec::new();
for close_match in sub.take_close_matches() {
if sub
.clone()
.unify(&close_match.param, &close_match.arg, self.resolver())
.is_ok()
{
continue;
}
let error_span = close_match.argument_span.unwrap_or(span);
let (expected, got) = self.close_match_mismatch(sub, close_match);
self.error_with_help(
error_span,
format!("expected `{expected}`, got `{got}`"),
self.render_help_list(super::type_diff::type_mismatch_help(&expected, &got)),
);
reported.push(error_span);
}
reported
}
/// The types to report a close match under: where the argument departs
/// from its matched member, or that member as `sub` resolves it when it
/// does not depart structurally.
fn close_match_mismatch(
&self,
sub: &TypeParamSubstitution,
close_match: CloseMatch,
) -> (Type, Type) {
match sub.clone().unify(
&close_match.matched_member,
&close_match.arg,
self.resolver(),
) {
Err(UnifyError::Mismatch { expected, got }) => {
(sub.apply_or_record(&expected, &self.type_limits), got)
}
_ => (
sub.apply_or_record(&close_match.matched_member, &self.type_limits),
close_match.arg,
),
}
}
/// `ty` with `sub` applied, at a call site at `span`.
fn instantiate(
&self,
sub: &TypeParamSubstitution,
ty: &Type,
span: Span,
) -> Result<Type, CompilerFailure> {
sub.apply(ty, &self.type_limits)
.map_err(type_limit_at(span))
}
/// Bind type parameters from the annotated parameters of a function
/// literal whose inference is deferred, so the arguments inferred before
/// it see them: `reduce((acc: number[], x) => …, [])` types `[]` as
/// `number[]`. The annotations are resolved again, and any error in them
/// reported, when the literal itself is inferred.
fn bind_from_annotated_params(
&mut self,
literal: ExprId,
param_ty: &Type,
sub: &mut TypeParamSubstitution,
) -> Result<(), CompilerFailure> {
let Some(Type::Function { params, .. }) = function_part(param_ty) else {
return Ok(());
};
let Some(declared_params) = self.function_literal_params(literal)? else {
return Ok(());
};
let diagnostics_before = self.diagnostics.len();
// An annotation only has to accept what the slot passes, so its
// closely matched members are not checked.
let close_matches_before = sub.close_match_count();
for (declared, param) in declared_params.iter().zip(params) {
if let Some(annotation) = &declared.ty {
let annotated = self.resolve_type(annotation)?;
let _ = sub.unify_argument(param, &annotated, self.resolver());
}
}
sub.forget_close_matches_after(close_matches_before);
self.diagnostics.truncate(diagnostics_before);
Ok(())
}
/// Start inferring an object or tuple literal argument's slots one at a
/// time, when one of them is a function literal with an unannotated
/// parameter: as in tsc, a type parameter another slot binds then types
/// that function's parameters. `test({ produce: (n: number) => n,
/// consume: (x) => ... })` types `x` from `produce`. Returns the inference
/// this one interrupts.
fn start_literal_argument_inference(
&mut self,
arg: ExprId,
param_ty: &Type,
sub: &TypeParamSubstitution,
) -> Result<Option<LiteralArgumentInference>, CompilerFailure> {
let enclosing = self.literal_argument_inference.take();
let slots = match self
.ast
.try_expr(arg)
.map_err(super::arena_failure)?
.kind
.clone()
{
ExprKind::ObjectLiteral { members } => {
self.object_argument_fields(&members, param_ty)?
}
ExprKind::ArrayLiteral { elements } => {
self.tuple_argument_slots(&elements, param_ty)?
}
_ => None,
};
if let Some(slots) = slots {
self.literal_argument_inference = Some(LiteralArgumentInference {
literal: arg,
slots,
sub: sub.clone(),
fallback_echoes: Vec::new(),
});
}
Ok(enclosing)
}
/// The fields of `param_ty` an object literal argument with `members` is
/// inferred against one at a time, when one of them is a function literal
/// with an unannotated parameter.
fn object_argument_fields(
&self,
members: &[crate::ObjectLiteralMember],
param_ty: &Type,
) -> Result<Option<BTreeMap<String, crate::ObjectField>>, CompilerFailure> {
let mut has_context_sensitive_field = false;
for member in members {
if let crate::ObjectLiteralMember::Field(field) = member {
has_context_sensitive_field |= self.is_context_sensitive_function(field.value)?;
}
}
if !has_context_sensitive_field {
return Ok(None);
}
Ok(match param_ty.peel() {
Type::Object { fields, .. } => Some(fields.clone()),
interface @ Type::InterfaceRef { .. } => {
match super::assignable::expand_interface_data_shape(interface, self.resolver()) {
Some(Type::Object { fields, .. }) => Some(fields),
_ => None,
}
}
_ => None,
})
}
/// The type parameters in `inferred` that keep the literals a function
/// value returns. For each, count the fields of the object literal `arg`
/// it types in each object shape of `param_ty`, leaving out plain values
/// (`w: 2`), and keep it when the largest count is at most one: tsc's
/// common supertype of two function values (`{ v: () => 1, w: () => 2 }`)
/// widens what they return to `() => number`. An empty list when `arg`
/// spreads another object; every one of `inferred` when `arg` is not an
/// object literal or `param_ty` has no object shape.
fn type_params_of_one_field(
&self,
arg: ExprId,
param_ty: &Type,
inferred: &[String],
) -> Result<Vec<String>, CompilerFailure> {
let ExprKind::ObjectLiteral { members } =
&self.ast.try_expr(arg).map_err(super::arena_failure)?.kind
else {
return Ok(inferred.to_vec());
};
let shapes = self.object_shapes(param_ty);
if shapes.is_empty() {
return Ok(inferred.to_vec());
}
// A spread may give any field, and so a second function value for any
// type parameter.
if members
.iter()
.any(|member| matches!(member, crate::ObjectLiteralMember::Spread { .. }))
{
return Ok(Vec::new());
}
let mut given_fields = Vec::new();
for member in members {
let crate::ObjectLiteralMember::Field(field) = member else {
continue;
};
if !self.is_plain_value(field.value)? {
given_fields.push(field.name.name.as_str());
}
}
// Each object shape of the parameter (`{ kind: "a"; get: T; fallback:
// T } | { kind: "b"; get: T }`) may be the one the literal fits.
let most_fields_typed_by = |name: &str| {
shapes
.iter()
.map(|fields| {
given_fields
.iter()
.filter_map(|field| fields.get(*field))
.filter(|field| is_or_has_type_var(&field.ty, name))
.count()
})
.max()
.unwrap_or(0)
};
Ok(inferred
.iter()
.filter(|name| most_fields_typed_by(name) <= 1)
.cloned()
.collect())
}
/// Whether `expr` can never be a function, whatever its operands: a
/// literal, an operator that yields a primitive, or a choice between such
/// values, seen through parentheses and a non-null assertion. Values of
/// other forms (a name, a call, a cast) may be one.
fn is_plain_value(&self, expr: ExprId) -> Result<bool, CompilerFailure> {
let kind = &self.ast.try_expr(expr).map_err(super::arena_failure)?.kind;
Ok(match kind {
// The forms that yield an operand (parentheses, `x!`, `&&`, `||`,
// `??`) come before the operator arms that yield a primitive.
ExprKind::Paren(inner)
| ExprKind::PostfixUnary {
op: crate::PostfixOp::NonNullAssert,
operand: inner,
} => self.is_plain_value(*inner)?,
ExprKind::Binary {
op: crate::BinOp::And | crate::BinOp::Or | crate::BinOp::NullishCoalesce,
lhs,
rhs,
} => self.is_plain_value(*lhs)? && self.is_plain_value(*rhs)?,
ExprKind::Ternary { then_, else_, .. } => {
self.is_plain_value(*then_)? && self.is_plain_value(*else_)?
}
ExprKind::Number(_)
| ExprKind::BigInt(_)
| ExprKind::String(_)
| ExprKind::Boolean(_)
| ExprKind::Null
| ExprKind::ObjectLiteral { .. }
| ExprKind::ArrayLiteral { .. }
| ExprKind::TemplateLiteral { .. }
| ExprKind::Regex { .. }
| ExprKind::Binary { .. }
| ExprKind::Unary { .. }
| ExprKind::PostfixUnary { .. }
| ExprKind::Typeof { .. }
| ExprKind::Delete { .. }
| ExprKind::InstanceOf { .. } => true,
_ => false,
})
}
/// The object shapes of `ty`: an object type, an interface with the
/// members it extends, or those among a union's members.
fn object_shapes(&self, ty: &Type) -> Vec<BTreeMap<String, crate::ObjectField>> {
match ty.peel() {
Type::Object { fields, .. } => vec![fields.clone()],
interface @ Type::InterfaceRef { .. } => {
match super::assignable::expand_interface_data_shape(interface, self.resolver()) {
Some(Type::Object { fields, .. }) => vec![fields],
_ => Vec::new(),
}
}
Type::Union(members) => members
.iter()
.filter(|member| !matches!(member.peel(), Type::Union(_)))
.flat_map(|member| self.object_shapes(member))
.collect(),
_ => Vec::new(),
}
}
/// The slots of the tuple `param_ty`, keyed by index, that an array
/// literal argument with `elements` is inferred against one at a time,
/// when one of them is a function literal with an unannotated parameter:
/// `callIt([() => 0, (n) => n.toFixed()])` types `n` from the first.
fn tuple_argument_slots(
&self,
elements: &[crate::ArrayLiteralElement],
param_ty: &Type,
) -> Result<Option<BTreeMap<String, crate::ObjectField>>, CompilerFailure> {
let Type::Tuple(slots) = super::expr::array_literal_hint_shape(param_ty) else {
return Ok(None);
};
if slots.len() != elements.len() {
return Ok(None);
}
let mut has_context_sensitive_element = false;
for element in elements {
let crate::ArrayLiteralElement::Value(value) = element else {
return Ok(None);
};
has_context_sensitive_element |= self.is_context_sensitive_function(*value)?;
}
Ok(has_context_sensitive_element.then(|| {
slots
.iter()
.enumerate()
.map(|(index, slot)| {
(
index.to_string(),
crate::ObjectField::required(slot.clone()),
)
})
.collect()
}))
}
/// Keep what the fields of the argument bound, and resume `enclosing`.
fn finish_literal_argument_inference(
&mut self,
enclosing: Option<LiteralArgumentInference>,
sub: &mut TypeParamSubstitution,
) {
if let Some(mut finished) =
std::mem::replace(&mut self.literal_argument_inference, enclosing)
{
finished
.sub
.bind_whole_union_fallbacks_named(&finished.fallback_echoes);
*sub = finished.sub;
}
}
/// Whether `literal`, a generic call's argument, has its fields or
/// elements inferred one at a time.
pub(super) fn infers_one_at_a_time(&self, literal: ExprId) -> bool {
self.literal_argument_inference
.as_ref()
.is_some_and(|inference| inference.literal == literal)
}
/// The hint for slot `name` (a field, or a tuple element's index) of
/// `literal`, with what its other slots bound so far, if the literal's
/// slots are being inferred one at a time. A callback slot's parameters
/// take the whole-union fallbacks of the type parameters still unbound, as
/// [`fix_callback_parameters`] gives them; they apply to the hint only, so
/// its returns or a later slot can still bind them.
pub(super) fn argument_slot_hint(&self, literal: ExprId, name: &str) -> Option<Type> {
let inference = self
.literal_argument_inference
.as_ref()
.filter(|inference| inference.literal == literal)?;
let slot = inference.slots.get(name)?;
let mut sub = inference.sub.clone();
if let Some(Type::Function { params, .. }) = function_part(&slot.ty) {
sub.bind_whole_union_fallbacks_in(params);
}
Some(sub.apply_or_record(&slot.ty, &self.type_limits))
}
/// Infer `value`, the value of slot `name` of `literal`, with `infer`.
/// A slot typed as a bare type parameter bound to a candidate may still
/// widen it (`{ v: new Dog(), w: new Animal() }`), so a value the
/// candidate fits is not reported against it, as tsc's contextual type
/// guides without checking.
pub(super) fn infer_argument_slot_value<R>(
&mut self,
literal: ExprId,
name: &str,
value: ExprId,
infer: impl FnOnce(&mut Self) -> Result<R, CompilerFailure>,
) -> Result<R, CompilerFailure> {
if !self.slot_widens_candidate(literal, name) {
return infer(self);
}
// Already marked by an enclosing inference, which unmarks it.
if !self.values_widening_candidates.insert(value) {
return infer(self);
}
let inferred = infer(self);
self.values_widening_candidates.remove(&value);
inferred
}
/// Whether slot `name` of `literal` is typed as a bare type parameter an
/// earlier value bound to a candidate it may still widen.
fn slot_widens_candidate(&self, literal: ExprId, name: &str) -> bool {
let Some(inference) = self
.literal_argument_inference
.as_ref()
.filter(|inference| inference.literal == literal)
else {
return false;
};
let Some(Type::TypeVar(var)) = inference.slots.get(name).map(|slot| slot.ty.peel()) else {
return false;
};
inference.sub.is_widenable(var)
}
/// Whether a function literal in a field of `literal` typed `field_ty`
/// keeps the literal types it returns: `literal` is an argument of a
/// generic call and the field is typed as a type parameter the call
/// infers that types no other field the literal gives, as tsc keeps a
/// literal returned where a type parameter is expected (`foo({ a: () =>
/// 42, b(a) {} })` binds `() => 42`) but widens two such values (`{ v:
/// () => 1, w: () => 2 }` binds `() => number`).
pub(super) fn field_keeps_returned_literals(
&self,
literal: ExprId,
field_ty: Option<&Type>,
) -> bool {
let Some((argument, inferred)) = &self.fields_keeping_returned_literals else {
return false;
};
*argument == literal
&& matches!(field_ty.map(Type::peel), Some(Type::TypeVar(name)) if inferred.contains(name))
}
/// Bind the type parameters slot `name` of `literal` determines, for the
/// slots typed after it. A mismatch is reported when the whole argument is.
pub(super) fn infer_from_argument_slot(
&mut self,
literal: ExprId,
name: &str,
value_ty: &Type,
) {
let Some(mut inference) = self
.literal_argument_inference
.take_if(|inference| inference.literal == literal)
else {
return;
};
if let Some(slot) = inference.slots.get(name) {
let before = inference.sub.clone();
let close_matches_before = inference.sub.close_match_count();
let _ = inference
.sub
.unify_argument(&slot.ty, value_ty, self.resolver());
inference
.sub
.nest_close_matches_after(close_matches_before, name);
// Only a callback field's parameters took the fallback from the
// hint; another field binding the same type binds it for real.
if function_part(&slot.ty).is_some() {
let echoes = inference.sub.unbind_fallback_echoes(&before);
inference.fallback_echoes.extend(echoes);
}
}
self.literal_argument_inference = Some(inference);
}
/// The hint for field `name` of the object literal `literal`: an
/// override slot's own signature, then what the literal's earlier fields
/// bound when it is a generic call's argument, then the expected type.
pub(super) fn object_field_hint(
&self,
literal: ExprId,
name: &str,
expected_fields: Option<&BTreeMap<String, crate::ObjectField>>,
expected_index: Option<&crate::IndexSignature>,
) -> Option<Type> {
super::reserved::override_field_signature(name)
.or_else(|| self.argument_slot_hint(literal, name))
.or_else(|| expected_field_hint(name, expected_fields, expected_index))
}
/// Infer the fields of a generic call's object literal argument other than
/// its function literals with an unannotated parameter, in source order,
/// ahead of those: tsc infers such a context-sensitive field last, so a
/// later field still binds the type parameter its parameters read
/// (`{ cb: (t) => t.length, value: "abc" }` types `t` as `string`). The
/// values land in `inferred` for the field loop to reuse; returns the ones
/// already unified. Only a literal without spreads or methods is
/// reordered, since a spread's fields and a method's `this` depend on the
/// members before them.
pub(super) fn infer_fields_ahead_of_callbacks(
&mut self,
literal: ExprId,
members: &[crate::ObjectLiteralMember],
expected_fields: Option<&BTreeMap<String, crate::ObjectField>>,
expected_index: Option<&crate::IndexSignature>,
inferred: &mut super::expr::InferredObjectFields,
) -> Result<std::collections::BTreeSet<ExprId>, CompilerFailure> {
let mut ahead = std::collections::BTreeSet::new();
if !self.infers_one_at_a_time(literal) {
return Ok(ahead);
}
let mut fields = Vec::new();
for member in members {
let crate::ObjectLiteralMember::Field(field) = member else {
return Ok(ahead);
};
if matches!(
self.ast
.try_expr(field.value)
.map_err(super::arena_failure)?
.kind,
ExprKind::FunctionExpression { .. }
) {
return Ok(ahead);
}
fields.push(field);
}
for field in fields {
if self.is_context_sensitive_function(field.value)?
|| inferred.contains_key(&field.value)
|| super::reserved::is_reserved_object_field(&field.name.name)
{
continue;
}
let name = &field.name.name;
let hint = self.object_field_hint(literal, name, expected_fields, expected_index);
let expected_field_ty = expected_fields
.and_then(|fields| fields.get(name))
.map(|field| &field.ty);
self.next_function_keeps_returned_literals =
self.field_keeps_returned_literals(literal, expected_field_ty);
let errors_before = self.error_count();
let (typed_value, value_ty) =
self.infer_argument_slot_value(literal, name, field.value, |this| {
this.infer_expr(field.value, hint.as_ref())
})?;
self.next_function_keeps_returned_literals = false;
let errored = self.error_count() > errors_before;
let unified_ty =
if expected_field_ty.is_some_and(super::expr::is_type_parameter_position) {
self.widen_fresh_literals(typed_value, &value_ty)?
} else {
value_ty.clone()
};
self.infer_from_argument_slot(literal, name, &unified_ty);
inferred.insert(field.value, (typed_value, value_ty, errored));
ahead.insert(field.value);
}
Ok(ahead)
}
fn function_literal_params(
&self,
expr: ExprId,
) -> Result<Option<Vec<crate::ParamDecl>>, CompilerFailure> {
Ok(
match &self.ast.try_expr(expr).map_err(super::arena_failure)?.kind {
ExprKind::Paren(inner) => self.function_literal_params(*inner)?,
ExprKind::FunctionExpression { function, .. } => {
self.function_literal_params(*function)?
}
ExprKind::Arrow { params, .. } => Some(params.clone()),
_ => None,
},
)
}
/// A function literal with a parameter left for its context to type,
/// which is what TypeScript infers after the other arguments.
pub(super) fn is_context_sensitive_function(
&self,
expr: ExprId,
) -> Result<bool, CompilerFailure> {
Ok(self
.function_literal_params(expr)?
.is_some_and(|params| params.iter().any(|p| p.ty.is_none())))
}
/// A function literal that annotates every parameter, so it types itself.
pub(super) fn is_fully_annotated_function(
&self,
expr: ExprId,
) -> Result<bool, CompilerFailure> {
Ok(self
.function_literal_params(expr)?
.is_some_and(|params| params.iter().all(|p| p.ty.is_some())))
}
/// Infer a generic call's arguments against `params`, binding its type
/// parameters in `sub`. A function literal with an unannotated parameter,
/// passed for a function-typed parameter, is inferred after the others,
/// so its hint sees what they bound: `reduce((acc, x) => acc + x, 0)` binds
/// `U` from `0` before typing `acc`. Only such a literal is deferred:
/// creating it runs nothing and its body sees no outer narrowing, so
/// checking it late can't observe a later argument's assignment, while any
/// other argument could. A fully annotated one binds from its annotations
/// in order, as in TypeScript.
///
/// `inferred_generics` names the type parameters the call infers rather
/// than takes as written type arguments. An object literal one of them
/// types, when only literals are its candidates, is a source for it and
/// isn't checked for unknown fields ([`super::inference_sources`]).
///
/// `signature_help` renders the callee for a mismatch diagnostic.
#[allow(clippy::too_many_arguments)]
fn infer_generic_arguments(
&mut self,
args: &[ExprId],
params: &[Param],
ret: &Type,
inferred_generics: &[String],
rest_elem_ty: &Type,
sub: &mut TypeParamSubstitution,
signature_help: impl Fn(&mut Self) -> String,
) -> Result<(Vec<ExprId>, Vec<ArgumentCheck>), CompilerFailure> {
let has_rest = params.last().is_some_and(|p| p.rest);
let fixed_count = params.iter().take_while(|p| !p.rest).count();
let mut checks = Vec::new();
let args_with_param_types: Vec<(ExprId, Type)> = args
.iter()
.enumerate()
.map(|(i, &arg_id)| {
let param_ty = match params.get(i) {
// An omittable parameter takes an explicit `undefined` too.
Some(param) if i < fixed_count => super::expr::callable_parameter_type(param),
_ if has_rest => rest_elem_ty.clone(),
_ => Type::Error,
};
(arg_id, param_ty)
})
.collect();
let arguments = GenericArguments {
inferred_generics,
sourced_by_literals: self
.literal_inferred_type_params(&args_with_param_types, inferred_generics)?,
literal_types: LiteralTypeArguments::new(
&args_with_param_types,
ret,
inferred_generics,
),
};
let mut typed_slots: Vec<Option<ExprId>> = vec![None; args.len()];
for deferred_pass in [false, true] {
for (i, (arg_id, param_ty)) in args_with_param_types.iter().enumerate() {
let (arg_id, param_ty) = (*arg_id, param_ty.clone());
if typed_slots[i].is_some() {
continue;
}
let deferred = function_part(¶m_ty).is_some()
&& self.is_context_sensitive_function(arg_id)?;
if deferred && !deferred_pass {
self.bind_from_annotated_params(arg_id, ¶m_ty, sub)?;
}
if deferred != deferred_pass {
continue;
}
if deferred {
fix_callback_parameters(sub, ¶m_ty, inferred_generics);
}
let errors_before = self.error_count();
let diagnostics_before = self.diagnostics.len();
let close_matches_before = sub.close_match_count();
let (typed_id, arg_ty) =
self.infer_generic_argument(arg_id, ¶m_ty, &arguments, sub)?;
typed_slots[i] = Some(typed_id);
let missing_slot = i >= fixed_count && !has_rest;
if missing_slot || matches!(arg_ty, Type::Error) {
continue;
}
// An error inferring the argument already covers a mismatch here.
let already_reported = self.error_count() > errors_before;
// The argument was already reported against the expected
// result's binding; replacing it would report the result too.
if already_reported {
sub.keep_replaceable_bindings(¶m_ty);
}
let unified = if self.builds_literal(arg_id)? {
sub.unify_literal_argument(¶m_ty, &arg_ty, self.resolver())
} else {
sub.unify_argument(¶m_ty, &arg_ty, self.resolver())
};
if unified.is_err() {
sub.forget_close_matches_after(close_matches_before);
} else {
self.locate_argument_close_matches(
sub,
arg_id,
typed_id,
close_matches_before,
diagnostics_before,
)?;
}
match unified {
Err(error) => self.unify_argument_error(
error,
sub,
(¶m_ty, &arg_ty),
typed_id,
already_reported,
&signature_help,
)?,
Ok(()) if !already_reported => checks.push(ArgumentCheck {
arg: typed_id,
param_ty,
arg_ty,
}),
Ok(()) => {}
}
}
}
Ok((typed_slots.into_iter().flatten().collect(), checks))
}
/// Check each argument against its parameter once the call's type
/// parameters are all bound, as tsc does after inference: unification
/// takes an argument as a candidate, which a later one may widen past
/// what an earlier one accepts. One `already_reported` at is skipped.
fn check_arguments_after_inference(
&mut self,
sub: &TypeParamSubstitution,
checks: Vec<ArgumentCheck>,
already_reported: &[Span],
) -> Result<(), CompilerFailure> {
for check in checks {
let param = sub.apply_or_record(&check.param_ty, &self.type_limits);
if super::expr::type_contains_type_var(¶m)
|| super::assignable(&check.arg_ty, ¶m, self.resolver())
{
continue;
}
let span = self.argument_span(check.arg)?;
if already_reported
.iter()
.any(|reported| span_contains(span, *reported))
{
continue;
}
let help =
self.render_help_list(super::type_diff::type_mismatch_help(¶m, &check.arg_ty));
self.error_with_help(
span,
format!("expected `{param}`, got `{}`", check.arg_ty),
help,
);
}
Ok(())
}
/// Infer one argument of a generic call against `param_ty`, with what
/// `sub` has bound so far as its hint, and return the type to unify with
/// `param_ty`: a fresh literal widened where tsc would widen it.
fn infer_generic_argument(
&mut self,
arg_id: ExprId,
param_ty: &Type,
arguments: &GenericArguments,
sub: &mut TypeParamSubstitution,
) -> Result<(ExprId, Type), CompilerFailure> {
// An oversized hint fails at the argument's own checkpoint.
let hint = sub.apply_or_record(param_ty, &self.type_limits);
let diagnostics_before = self.diagnostics.len();
let errors_before = self.error_count();
let first = self.infer_generic_argument_with(arg_id, param_ty, hint, arguments, sub)?;
// An object or array literal widens only what other literals bound,
// as in tsc: one is checked against what a non-literal inferred.
if self.error_count() == errors_before
|| !sub.mentions_candidate_binding(param_ty)
|| (self.builds_literal(arg_id)?
&& sub.mentions_non_literal_candidate_binding(param_ty))
{
return Ok(first);
}
// The binding the hint came from is only a candidate, which this
// argument may widen: tsc infers the common supertype of the two.
// Inferred without it, an argument that fits is not reported. A
// callback's parameters stay fixed, as tsc fixes them.
let first_diagnostics = self.diagnostics.split_off(diagnostics_before);
let mut loose = sub.without_candidate_bindings();
for name in arguments.inferred_generics {
if let Some(bound) = sub.get(name).filter(|_| takes_in_callback(param_ty, name)) {
loose.insert(name.clone(), bound.clone());
}
}
let loose_hint = loose.apply_or_record(param_ty, &self.type_limits);
let second =
self.infer_generic_argument_with(arg_id, param_ty, loose_hint, arguments, sub)?;
if self.error_count() == errors_before {
return Ok(second);
}
self.diagnostics.truncate(diagnostics_before);
self.diagnostics.extend(first_diagnostics);
Ok(first)
}
/// [`Self::infer_generic_argument`] against one hint for the argument.
fn infer_generic_argument_with(
&mut self,
arg_id: ExprId,
param_ty: &Type,
hint: Type,
arguments: &GenericArguments,
sub: &mut TypeParamSubstitution,
) -> Result<(ExprId, Type), CompilerFailure> {
let hint = self.method_interface_literal_hint(arg_id, hint, param_ty, sub)?;
let hint = self.literal_argument_hint(arg_id, hint, arguments.inferred_generics)?;
let hinted_by_replaceable_binding = sub.mentions_replaceable_binding(param_ty);
if hinted_by_replaceable_binding {
self.arguments_with_replaceable_hints.insert(arg_id);
}
let enclosing = self.start_literal_argument_inference(arg_id, param_ty, sub)?;
let params_keeping_returned_literals =
self.type_params_of_one_field(arg_id, param_ty, arguments.inferred_generics)?;
let enclosing_fields = self
.fields_keeping_returned_literals
.replace((arg_id, params_keeping_returned_literals));
let keeps_literal = arguments.literal_types.keeps(param_ty);
let inferred = self.with_inferred_positions(
arg_id,
param_ty,
&arguments.sourced_by_literals,
|this| {
this.keeps_literal_types = keeps_literal;
this.next_function_keeps_returned_literals =
arguments.literal_types.keeps_returned(param_ty);
this.infer_expr(arg_id, Some(&hint))
},
);
self.finish_literal_argument_inference(enclosing, sub);
self.fields_keeping_returned_literals = enclosing_fields;
self.arguments_with_replaceable_hints.remove(&arg_id);
let (typed_id, arg_ty) = inferred?;
if keeps_literal {
self.record_kept_literal_argument(typed_id);
}
// A literal that fits what the type parameter is already bound to is
// not widened, so it doesn't conflict with that binding:
// `pick(mode, "off")` with `mode: Mode` binds `Mode`, as tsc does when
// the type parameter is the result (where it isn't, tsc widens to
// `string`, and a later push of another string is SUB-1397). Nor is
// one the call's expected result asks for: `const f: () => "a" =
// later(c)` binds `"a"`.
let hint_is_known = !super::expr::mentions_type_var(&hint, &|var| {
arguments.inferred_generics.iter().any(|name| name == var)
});
let fits_binding = (hinted_by_replaceable_binding || hint_is_known)
&& super::assignable(&arg_ty, &hint, self.resolver());
if arguments.literal_types.widens(param_ty)
&& !fits_binding
&& !is_literal_member_of(&arg_ty, param_ty)
&& !self.fits_without_fallback_type_params(sub, param_ty, &arg_ty)
{
let widened = self.widen_fresh_literals(typed_id, &arg_ty)?;
return Ok((typed_id, widened));
}
Ok((typed_id, arg_ty))
}
/// Whether `arg_ty` fits `param_ty` without the type parameters that
/// have a whole-union fallback. `"x"` for `T | "x"` then goes to the
/// other members, as tsc matches it before widening, and must not bind
/// the type parameter widened (see `unify_with_member_beside_fallback`).
fn fits_without_fallback_type_params(
&self,
sub: &TypeParamSubstitution,
param_ty: &Type,
arg_ty: &Type,
) -> bool {
sub.without_fallback_type_params(param_ty, &self.type_limits)
.is_some_and(|concrete| super::assignable(arg_ty, &concrete, self.resolver()))
}
/// The hint for an object literal argument for an interface with methods
/// whose type arguments are still being inferred: the interface with
/// what the literal's own members bind. The literal is typed as the
/// interface, which binds nothing, so its members are first inferred
/// against the interface's fields and methods as a plain shape, whose
/// diagnostics are dropped: `get({ v: 1, get() { return 1; } })` for
/// `Getter<T>` takes `Getter<number>` as its hint.
fn method_interface_literal_hint(
&mut self,
arg_id: ExprId,
hint: Type,
param_ty: &Type,
sub: &TypeParamSubstitution,
) -> Result<Type, CompilerFailure> {
let Type::InterfaceRef {
mangled,
name,
args,
..
} = hint.peel()
else {
return Ok(hint);
};
if !super::expr::type_contains_type_var(&hint)
|| !matches!(
self.ast
.try_expr(arg_id)
.map_err(super::arena_failure)?
.kind,
ExprKind::ObjectLiteral { .. }
)
|| !self.resolver().interface_has_methods(mangled, name)
{
return Ok(hint);
}
let Some(fields) = self.structural_form(mangled, name, args) else {
return Ok(hint);
};
let shape = Type::Object {
fields,
index: None,
};
let diagnostics_before = self.diagnostics.len();
let scratch = self.infer_expr(arg_id, Some(&shape));
self.diagnostics.truncate(diagnostics_before);
let (_, scratch_ty) = scratch?;
// A member that conflicts with what an earlier one bound is then
// reported against that binding, as tsc reports it.
let mut bound = sub.clone();
let _ = bound.unify_argument(&shape, &scratch_ty, self.resolver());
Ok(bound.apply_or_record(param_ty, &self.type_limits))
}
/// The hint for an object or array literal argument, with each data-only
/// interface whose type arguments are still being inferred replaced by
/// its fields, so the literal keeps its own field types to bind them
/// from. Typed as `Box<T>` itself, it would bind nothing
/// (`unbox({ v: "s" })`). A function literal's return gets the same
/// treatment, for the literals it returns (`fn(() => ({ v: "f" }))`).
fn literal_argument_hint(
&self,
arg_id: ExprId,
hint: Type,
inferred_generics: &[String],
) -> Result<Type, CompilerFailure> {
if self.builds_literal(arg_id)? {
return Ok(expand_hint_interfaces(
&hint,
inferred_generics,
self.resolver(),
));
}
if self.function_literal_params(arg_id)?.is_none() {
return Ok(hint);
}
let Type::Function {
params,
optional,
ret,
predicate,
has_rest,
} = hint.peel()
else {
return Ok(hint);
};
Ok(Type::Function {
params: params.clone(),
optional: *optional,
ret: Box::new(expand_hint_interfaces(
ret,
inferred_generics,
self.resolver(),
)),
predicate: predicate.clone(),
has_rest: *has_rest,
})
}
/// Whether `expr` is an object or array literal, in parentheses or as both
/// of a conditional's branches.
fn builds_literal(&self, expr: ExprId) -> Result<bool, CompilerFailure> {
Ok(
match &self.ast.try_expr(expr).map_err(super::arena_failure)?.kind {
ExprKind::ObjectLiteral { .. } | ExprKind::ArrayLiteral { .. } => true,
ExprKind::Paren(inner) => self.builds_literal(*inner)?,
ExprKind::Ternary { then_, else_, .. } => {
self.builds_literal(*then_)? && self.builds_literal(*else_)?
}
_ => false,
},
)
}
/// The source of an `Array.from` call when it is an array-like `{ length }`
/// rather than an array, iterator or iterable. Only an object type is an
/// array-like: TypeScript's `ArrayLike` has a number index signature,
/// which an object type has implicitly and an interface or class doesn't.
/// A source with a string index signature or an index-named field is
/// rejected too, since those entries would be its elements.
fn array_like_source(
&mut self,
typed_args: &[ExprId],
) -> Result<Option<Type>, crate::compiler_error::CompilerFailure> {
let Some(source) = typed_args.first() else {
return Ok(None);
};
let source = self
.typed_ast
.try_expr(*source)
.map_err(crate::typechecker::arena_failure)?;
let (source_ty, source_span) = (source.ty.clone(), source.span);
if matches!(source_ty.peel(), Type::Error | Type::Unknown) {
return Ok(None);
}
let iterable = Type::union(vec![
Type::Readonly(Box::new(Type::Array(Box::new(Type::Unknown)))),
Type::prelude_interface("Iterator".to_string(), vec![Type::Unknown]),
Type::prelude_interface("Iterable".to_string(), vec![Type::Unknown]),
]);
let has_length = crate::runtime::prelude::array::array_like_type();
// A source that is neither was already reported against the parameter.
if super::assignable(&source_ty, &iterable, self.resolver())
|| !super::assignable(&source_ty, &has_length, self.resolver())
{
return Ok(None);
}
if self.has_keyed_entries(&source_ty) {
self.error_with_help(
source_span,
format!(
"`Array.from` doesn't read the keyed entries of `{source_ty}`: Submilli \
treats an array-like `{{ length }}` as having no elements"
),
vec!["convert the entries to an array first, or pass an array".to_string()],
);
return Ok(None);
}
if !matches!(source_ty.peel(), Type::Object { .. }) {
self.error_with_help(
source_span,
format!(
"`Array.from` takes an array-like only as an object type: `{source_ty}` \
has no number index signature, so it isn't an `ArrayLike`"
),
vec![
"annotate the value with an object type such as `{ length: number }`, or \
pass an array"
.to_string(),
],
);
return Ok(None);
}
Ok(Some(source_ty))
}
/// Whether an array-like source may hold entries JavaScript reads as its
/// elements: a string index signature, or a field named by an array index.
fn has_keyed_entries(&self, source: &Type) -> bool {
if self.resolver().index_signature(source).is_some() {
return true;
}
match source.peel() {
Type::Object { fields, .. } => fields.keys().any(|name| is_array_index(name)),
Type::Union(members) => members.iter().any(|member| self.has_keyed_entries(member)),
_ => false,
}
}
/// `Array.from` of an array-like with no callback makes an array of
/// `undefined`, which only an element type admitting it can hold.
fn reject_array_like_element_type(&mut self, element: &Type, span: Span) {
if admits_undefined(element) {
return;
}
self.error_with_help(
span,
format!(
"`Array.from` of an array-like `{{ length }}` has no elements, so it makes an \
array of `undefined`, not of `{element}`"
),
vec![
"give the array an element type that admits `undefined`, such as \
`(number | undefined)[]`, or pass a callback that builds each element from its \
index"
.to_string(),
],
);
}
/// `Array.from({ length }, mapFn)` calls `mapFn` with `undefined` for each
/// element. A callback whose element type doesn't admit `undefined` would
/// read it as its declared type (`v: number` gives `undefined + i`, not a
/// number), so it is refused rather than run with a wrong value.
fn reject_array_like_element_annotation(
&mut self,
typed_args: &[ExprId],
mapper_type: Option<&Type>,
) -> Result<(), crate::compiler_error::CompilerFailure> {
let Some(mapper) = typed_args.get(1) else {
return Ok(());
};
let Some(Type::Function { params, .. }) = mapper_type.map(Type::peel) else {
return Ok(());
};
let Some(element) = params.first() else {
return Ok(());
};
if admits_undefined(element) {
return Ok(());
}
let span = self
.typed_ast
.try_expr(*mapper)
.map_err(crate::typechecker::arena_failure)?
.span;
self.error_with_help(
span,
format!(
"`Array.from` of an array-like `{{ length }}` has no elements, so the callback's \
element parameter receives `undefined`, not a `{element}`"
),
vec![
"declare the element parameter as `unknown` or a type that admits `undefined`, or \
leave it unannotated, and build the value from the index"
.to_string(),
],
);
Ok(())
}
/// Handle an argument that didn't unify with its parameter: a structural
/// match may still bind it; otherwise report it, unless `already_reported`.
fn unify_argument_error(
&mut self,
error: UnifyError,
sub: &mut TypeParamSubstitution,
(param_ty, arg_ty): (&Type, &Type),
arg: ExprId,
already_reported: bool,
signature_help: &impl Fn(&mut Self) -> String,
) -> Result<(), crate::compiler_error::CompilerFailure> {
let arg_span = self.argument_span(arg)?;
let _: () = match error {
UnifyError::Conflict { .. } if already_reported => {}
UnifyError::Conflict { name, prev, new } => self.error(
arg_span,
format!(
"type parameter `{name}` already bound to `{prev}`, cannot bind to `{new}`"
),
),
UnifyError::Mismatch { expected, got } => {
if self.structural_member_unify(sub, param_ty, arg_ty) || already_reported {
return Ok(());
}
let expected = sub.apply_or_record(&expected, &self.type_limits);
let mut help = vec![signature_help(self)];
help.extend(
self.render_help_list(super::type_diff::type_mismatch_help(&expected, &got)),
);
self.error_with_help(
arg_span,
super::diagnostics::mismatch_message(&expected, &got),
help,
);
}
};
Ok(())
}
/// Locate the close matches the argument `arg` (typed as `typed_arg`)
/// recorded after the first `close_matches_before`, each at the field it
/// came from, and drop those an error reported since
/// `diagnostics_before` lies inside: an error inside a close match's field
/// usually is that mismatch, while one elsewhere in the argument (a
/// callback field's body) leaves it to report.
fn locate_argument_close_matches(
&self,
sub: &mut TypeParamSubstitution,
arg: ExprId,
typed_arg: ExprId,
close_matches_before: usize,
diagnostics_before: usize,
) -> Result<(), CompilerFailure> {
let arg_span = self.argument_span(typed_arg)?;
sub.locate_close_matches_after(close_matches_before, |path| {
self.argument_field_span(arg, path).unwrap_or(arg_span)
});
let reported: Vec<Span> = self
.diagnostics
.get(diagnostics_before..)
.unwrap_or_default()
.iter()
.filter(|diagnostic| diagnostic.severity == crate::Severity::Error)
.map(|diagnostic| diagnostic.span)
.collect();
sub.retain_close_matches_after(close_matches_before, |close_match| {
close_match
.argument_span
.is_some_and(|span| !reported.iter().any(|error| span_contains(span, *error)))
});
Ok(())
}
/// The span of the value of field `path` of the object literal argument
/// `arg`, as deep as the literal spells the path out; `None` when it names
/// no field of a literal.
fn argument_field_span(&self, arg: ExprId, path: &[String]) -> Option<Span> {
let mut expr = self.ast.try_expr(arg).ok()?;
let mut found = None;
for name in path {
while let ExprKind::Paren(inner) = expr.kind {
expr = self.ast.try_expr(inner).ok()?;
}
let ExprKind::ObjectLiteral { members } = &expr.kind else {
break;
};
let value = members.iter().rev().find_map(|member| match member {
crate::ObjectLiteralMember::Field(field) if field.name.name == *name => {
Some(field.value)
}
_ => None,
});
let Some(value) = value else {
break;
};
expr = self.ast.try_expr(value).ok()?;
found = Some(expr.span);
}
found
}
fn argument_span(&self, arg: ExprId) -> Result<Span, crate::compiler_error::CompilerFailure> {
Ok(self
.typed_ast
.try_expr(arg)
.map_err(crate::typechecker::arena_failure)?
.span)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn infer_generic_call(
&mut self,
callee_ident: Ident,
generics: Vec<String>,
params: Vec<Param>,
ret: Type,
mangled: crate::MangledName,
predicate: Option<crate::TypePredicate>,
type_args: Option<Vec<crate::TypeAnnotation>>,
args: Vec<ExprId>,
expected: Option<&Type>,
span: Span,
callee: GenericCallee,
) -> Result<(TypedExprKind, Type), CompilerFailure> {
let mut sub = TypeParamSubstitution::new();
let type_args_written = type_args.is_some();
// `session.get<T>` is lowered as a runtime-checked cast rather than an
// ordinary generic call; the two sites below are the two halves of that
// one decision, so it is read once here.
let checked_get = crate::stdlib::session::declaration::is_checked_get(&mangled);
// Schema-checked calls (`llm.call<T>`, `llm.batch<T>`, `agents.run<T>`)
// lower the same way and for the same reason. They differ from
// `session.get` only in what a bare call means — a typed default such as
// the `Completion` envelope rather than an unchecked `unknown` — and in
// carrying a compile-time schema into the trailing argument.
let schema_checked = crate::stdlib::schema_checked_call(&mangled);
if let Some(targs) = &type_args {
if targs.len() != generics.len() {
let help =
self.generic_callee_lift(callee, &callee_ident, &generics, ¶ms, &ret);
self.error_with_help(
span,
format!(
"{} expects {} type argument(s), got {}",
callee.subject(&callee_ident.name, &generics),
generics.len(),
targs.len(),
),
vec![help],
);
}
let subject = callee.subject(&callee_ident.name, &generics);
for (name, annot) in generics.iter().zip(targs.iter()) {
let resolved = self.resolve_call_type_argument(annot, &subject)?;
sub.insert(name.clone(), resolved);
}
}
if let Some(want) = expected.filter(|want| pins_type_parameters(want)) {
self.bind_from_expected_result(&mut sub, &ret, want);
}
let has_rest = params.last().is_some_and(|p| p.rest);
let fixed_count = params.iter().take_while(|p| !p.rest).count();
let max_args = if has_rest { usize::MAX } else { params.len() };
let min_args = super::expr::required_parameter_count(¶ms);
let arity_ok = args.len() >= min_args && args.len() <= max_args;
if !arity_ok {
let help = self.generic_callee_lift(callee, &callee_ident, &generics, ¶ms, &ret);
let subject = callee.subject(&callee_ident.name, &generics);
let msg = if has_rest {
format!(
"{subject} expects {}+ argument(s), got {}",
min_args,
args.len(),
)
} else if min_args == max_args {
format!(
"{subject} expects {} argument(s), got {}",
max_args,
args.len()
)
} else {
format!(
"expected {}-{} argument(s), got {}",
min_args,
max_args,
args.len(),
)
};
self.error_with_help(span, msg, vec![help]);
}
let rest_elem_ty: Type = if has_rest {
match ¶ms
.last()
.ok_or_else(|| super::inference_failure("rest signature has no parameters"))?
.ty
.rest_element()
{
Some(elem) => Type::clone(elem),
None => Type::Error,
}
} else {
Type::Error
};
let signature_help = |this: &mut Self| {
this.generic_callee_lift(callee, &callee_ident, &generics, ¶ms, &ret)
};
let errors_before_args = self.error_count();
let inferred_generics: &[String] = if type_args_written { &[] } else { &generics };
let (mut typed_args, argument_checks) = self.infer_generic_arguments(
&args,
¶ms,
&ret,
inferred_generics,
&rest_elem_ty,
&mut sub,
signature_help,
)?;
if has_rest || typed_args.len() < params.len() {
self.typed_ast
.record_authored_arguments(span, typed_args.clone());
}
if arity_ok {
self.fill_omitted_defaults(¶ms, args.len(), span, &mut typed_args)?;
}
// Packed rest array has type T[] — a composite, not a bare TypeVar —
// so the GenericArgument zip tags it is_generic: false.
if arity_ok && has_rest {
self.pack_rest_tail(fixed_count, rest_elem_ty.clone(), span, &mut typed_args)?;
}
// `session.get(key)` without a type argument keeps its pre-generic
// meaning: an unchecked read of `unknown` the caller narrows with a
// runtime-checked `as`. Only a *written* `<unknown>` is an error, so
// bind the parameter here rather than letting it go unbound and trip
// both the inference error and the erasure gate below.
if checked_get && !type_args_written {
bind_remaining(&mut sub, &generics, Type::Unknown, &self.type_limits)
.map_err(type_limit_at(span))?;
}
// Same reasoning for `llm.call(model, prompt)`, but the untyped default
// is the `Completion` envelope rather than `unknown`: an untyped call
// is not an unchecked read, it is a different fully-typed result. `T`
// appears only in the return type, so it is never inferable from an
// argument and would otherwise always trip the unbound-parameter error.
if let Some(checked) = &schema_checked
&& !type_args_written
{
bind_remaining(
&mut sub,
&generics,
checked.untyped_result.clone(),
&self.type_limits,
)
.map_err(type_limit_at(span))?;
}
sub.bind_whole_union_fallbacks();
let close_match_spans = self.check_deferred_close_matches(&mut sub, span);
self.bind_leftover_type_parameters(&mut sub, &generics, &ret, expected, errors_before_args);
self.bind_uninferred_to_unknown(&mut sub, &generics, &mangled, span)?;
if let Err(unbound) = sub
.resolve_all(&generics, &self.type_limits)
.map_err(type_limit_at(span))?
{
self.error_with_help(
span,
format!(
"cannot infer type parameter(s) {}; consider adding an explicit type argument",
unbound
.iter()
.map(|n| format!("`{n}`"))
.collect::<Vec<_>>()
.join(", "),
),
vec![callee.explicit_arg_hint(
&callee_ident.name,
&generics,
&sub,
&self.type_limits,
)],
);
}
self.check_arguments_after_inference(&sub, argument_checks, &close_match_spans)?;
let result_ty = self.instantiate(&sub, &ret, span)?;
// A typed `llm.call<T>` is rewritten before the argument list is frozen,
// because the schema emitted from `T` has to replace the trailing
// `schema` argument the default filled with `null`. The rewrite can also
// fail (an unschemable or unverifiable `T`), in which case the whole
// call is already an error and no node is built.
// The `schema` slot is compiler-filled, never program-written. Rejecting
// a written one is a soundness requirement, not tidiness: the host keys
// "this call is typed" off that argument being non-null
// (`stdlib/llm/mod.rs`), while the structural check rides on the cast
// emitted here. A hand-written schema sets the first without the second,
// so raw parsed JSON reaches the guest wearing the `Completion`
// interface type — reading `ok` off a JSON object yields a fabricated
// `true`, and reading `text` traps outside the error taxonomy. It also
// hands guest-controlled bytes to the provider as the schema.
//
// This rejects rather than ignoring the argument, because silently
// discarding what a program wrote is its own trap. Typed calls are
// unaffected in behavior — `substitute_schema_argument` overwrites the
// slot — but a written argument there is equally meaningless, so both
// forms are refused and no working program changes.
if let Some(checked) = &schema_checked
&& args.len() > checked.written_param_count
{
let name = &callee_ident.name;
let written = checked.written_params;
let extra = checked.schema_argument_ordinal();
self.error_with_help(
span,
format!(
"`{name}` takes {written}; the schema argument is filled by \
the compiler from the type argument"
),
vec![format!(
"drop the {extra} argument — write `{name}<T>(...)` to send a schema for `T`, \
or `{name}(...)` for an untyped call"
)],
);
return Ok((TypedExprKind::Null, Type::Error));
}
let mut emitted_schema = None;
if let Some(checked) = &schema_checked {
match self.schema_checked_call_schema(checked, &result_ty, type_args_written, span) {
Ok(schema) => emitted_schema = schema,
Err(()) => return Ok((TypedExprKind::Null, Type::Error)),
}
}
if let Some(schema) = &emitted_schema {
self.substitute_schema_argument(¶ms, &mut typed_args, schema, span)?;
}
self.record_generic_call_arguments(&typed_args, ¶ms, &ret, type_args_written);
let generic_args: Vec<crate::GenericArgument> = typed_args
.into_iter()
.zip(params.iter())
.map(|(expr, p)| crate::GenericArgument {
expr,
is_generic: matches!(p.ty, Type::TypeVar(_)),
})
.collect();
let return_cast = if return_erases_to_object_slot(&ret) {
Some(result_ty.clone())
} else {
None
};
let type_predicate = match predicate {
Some(p) => Some(Box::new(crate::TypePredicate {
parameter_index: p.parameter_index,
asserted_type: self.instantiate(&sub, &p.asserted_type, span)?,
})),
None => None,
};
// A checked read must not keep `return_cast`: it is a representation
// cast that tests nothing, and on a stored or missing `null` its
// `ref.cast` traps uncatchably before any structural check could run.
// The call node is left producing `unknown` and the checked `Cast`
// wrapped around it does the verifying. Intercepting here rather than
// at a callsite is what covers every import form, since all four
// callers thread the package-export mangled name through unchanged.
let runtime_args: Vec<_> = generics
.iter()
.map(|name| self.instantiate(&sub, &Type::TypeVar(name.clone()), span))
.collect::<Result<_, _>>()?;
for arg in &runtime_args {
self.record_runtime_type_test(arg)?;
}
let call = TypedExprKind::GenericCall {
mangled,
type_args: runtime_args,
args: generic_args,
return_cast: if checked_get || schema_checked.is_some() {
None
} else {
return_cast
},
type_predicate,
};
if checked_get {
return self.checked_session_get(call, &result_ty, type_args_written, span);
}
// An untyped schema-checked call emitted no schema and needs no check: it
// returns the default the declaration already typed.
if schema_checked.is_some() && emitted_schema.is_some() {
return self.schema_checked_cast(call, &result_ty, span);
}
Ok((call, result_ty))
}
}
/// An argument that unified with its parameter, to check against the
/// parameter once inference is done.
struct ArgumentCheck {
arg: ExprId,
param_ty: Type,
arg_ty: Type,
}
/// What every argument of one generic call is inferred with.
struct GenericArguments<'a> {
/// The type parameters the call infers rather than takes as written.
inferred_generics: &'a [String],
/// Those that only object and array literals are candidates for
/// ([`super::inference_sources`]).
sourced_by_literals: Vec<String>,
literal_types: LiteralTypeArguments,
}
/// What a call does with the literal type of an argument passed straight for
/// one of its inferred type parameters, as tsc does: a parameter the result
/// is (`id<T>(x: T): T`, or a union naming it) keeps the literal (`id(1)` is
/// `1`), and any other widens a fresh one (`box(c)` with `const c = "a"`
/// is a `{ v: string }`), so the result can hold other values. An annotated
/// literal type is not fresh and stays.
///
/// This applies only to a type parameter every parameter names at its top
/// level: one nested in another (`append<T>(a: T[], x: T)`) has candidates
/// tsc doesn't widen. Several kept literals of one primitive bind their
/// union (`pick(1, 2)` is a `1 | 2`).
struct LiteralTypeArguments {
kept: Vec<String>,
/// Those of `kept` with one candidate: a function literal passed for one
/// keeps the literals it returns, where several such candidates widen
/// theirs (`pick(() => "a", () => "b")` binds `() => string`).
sole: Vec<String>,
widened: Vec<String>,
}
impl LiteralTypeArguments {
fn new(args: &[(ExprId, Type)], ret: &Type, inferred_generics: &[String]) -> Self {
let in_result = top_level_type_params(ret);
let mut kept = Vec::new();
let mut sole = Vec::new();
let mut widened = Vec::new();
for name in inferred_generics {
let mentioning: Vec<&Type> = args
.iter()
.map(|(_, param)| param)
.filter(|param| super::expr::mentions_type_var(param, &|var| var == name))
.collect();
let only_top_level = mentioning
.iter()
.all(|param| top_level_type_params(param).contains(&name.as_str()));
if mentioning.is_empty() || !only_top_level {
continue;
}
if in_result.contains(&name.as_str()) {
if mentioning.len() == 1 {
sole.push(name.clone());
}
kept.push(name.clone());
} else {
widened.push(name.clone());
}
}
Self {
kept,
sole,
widened,
}
}
/// Whether an argument for `param` keeps its literal type.
fn keeps(&self, param: &Type) -> bool {
top_level_type_params(param)
.iter()
.any(|name| self.kept.iter().any(|kept| kept == name))
}
/// Whether a function literal passed for `param` keeps the literal types
/// it returns.
fn keeps_returned(&self, param: &Type) -> bool {
top_level_type_params(param)
.iter()
.any(|name| self.sole.iter().any(|sole| sole == name))
}
/// Whether an argument for `param` widens its fresh literal types.
fn widens(&self, param: &Type) -> bool {
top_level_type_params(param)
.iter()
.any(|name| self.widened.iter().any(|widened| widened == name))
}
}
/// Whether `arg` is a literal type `param` names as a member of its union
/// (`"x"` for `T | U | "x"`): tsc matches it there before widening it, so
/// it stays a `"x"`.
fn is_literal_member_of(arg: &Type, param: &Type) -> bool {
arg.literal_base().is_some()
&& matches!(param.peel(), Type::Union(members) if members.iter().any(|member| member.peel() == arg.peel()))
}
/// The type field `name` of an object literal is expected to have, from the
/// expected type's own field or its index signature.
fn expected_field_hint(
name: &str,
expected_fields: Option<&BTreeMap<String, crate::ObjectField>>,
expected_index: Option<&crate::IndexSignature>,
) -> Option<Type> {
// An optional field also takes `undefined`; a record key's value doesn't.
expected_fields
.and_then(|fields| fields.get(name))
.map(crate::ObjectField::read_ty)
.or_else(|| expected_index.map(|index| (*index.value).clone()))
}
/// Whether `inner` lies within `outer`.
fn span_contains(outer: Span, inner: Span) -> bool {
outer.file == inner.file && outer.start <= inner.start && inner.end <= outer.end
}
/// The type parameters `ty` is, alone or as a member of a union.
fn top_level_type_params(ty: &Type) -> Vec<&str> {
match ty.peel() {
Type::Union(members) => members.iter().filter_map(type_param_name).collect(),
other => type_param_name(other).into_iter().collect(),
}
}
fn type_param_name(ty: &Type) -> Option<&str> {
match ty.peel() {
Type::TypeVar(name) => Some(name),
_ => None,
}
}
/// How many interfaces one literal argument's hint expands at most per pass
/// of [`expand_hint_interfaces`], apart from the first pass, which may also
/// expand as many again at the top union level. Interfaces that name each
/// other in their fields expand along every order of them, so without a
/// bound the hint grows factorially, and checking a literal against a large
/// structural hint takes time in proportion to its size; a literal's hint
/// needs few levels in practice.
const MAX_HINT_INTERFACE_EXPANSIONS: usize = 64;
/// How many unions deep one literal argument's hint expands at most.
const MAX_HINT_UNION_DEPTH: usize = 8;
/// The state of one [`expand_inferred_interfaces`] walk.
struct InterfaceExpansion {
/// The interfaces being expanded, outermost first.
expanding: Vec<crate::MangledName>,
/// How many more interfaces may expand under `max_union_depth` unions.
remaining_at_max_depth: usize,
/// How many more interfaces may expand under fewer unions.
remaining_shallower: usize,
/// How many interfaces have expanded.
expansion_count: usize,
/// How many unions enclose the type being expanded.
union_depth: usize,
/// How many enclosing unions an interface may have and still expand.
max_union_depth: usize,
/// Whether an interface stayed as it is for want of budget.
starved: bool,
/// Whether an interface stayed as it is for being nested in more unions
/// than `max_union_depth`.
cut_at_union_depth: bool,
}
impl InterfaceExpansion {
/// A walk that expands up to `remaining_at_max_depth` interfaces under
/// `max_union_depth` unions, after those under fewer.
fn new(max_union_depth: usize, remaining_at_max_depth: usize) -> Self {
Self {
expanding: Vec::new(),
remaining_at_max_depth,
remaining_shallower: MAX_HINT_INTERFACE_EXPANSIONS,
expansion_count: 0,
union_depth: 0,
max_union_depth,
starved: false,
cut_at_union_depth: false,
}
}
/// The budget an interface at the current union depth expands from.
fn budget(&mut self) -> &mut usize {
if self.union_depth < self.max_union_depth {
&mut self.remaining_shallower
} else {
&mut self.remaining_at_max_depth
}
}
/// Whether an interface at the current union depth may expand, noting
/// when one may not.
fn can_expand(&mut self) -> bool {
let available = *self.budget() > 0;
self.starved |= !available;
available
}
/// Count an interface at the current union depth as expanded.
fn spend(&mut self) {
*self.budget() -= 1;
self.expansion_count += 1;
}
}
/// `ty` expanded by [`expand_inferred_interfaces`] through as many levels of
/// nested unions as the budget covers. Each pass re-expands what the pass
/// before did and gives the interfaces one union deeper the rest of
/// [`MAX_HINT_INTERFACE_EXPANSIONS`]; the passes stop once one runs out of
/// budget, cuts nothing at its depth, or leaves no budget for the next. So
/// the members of an outer union all expand before any member of a union
/// inside them: a wide union of interfaces that name it again
/// (`Lit<T> | Add<T> | …`) expands its own members rather than the first
/// member's descendants.
fn expand_hint_interfaces(
ty: &Type,
inferred_generics: &[String],
types: super::assignable::TypeResolver,
) -> Type {
let mut expansion = InterfaceExpansion::new(1, MAX_HINT_INTERFACE_EXPANSIONS);
let mut deepest = expand_inferred_interfaces(ty, inferred_generics, types, &mut expansion);
for max_union_depth in 2..=MAX_HINT_UNION_DEPTH {
let remaining = MAX_HINT_INTERFACE_EXPANSIONS.saturating_sub(expansion.expansion_count);
if expansion.starved || !expansion.cut_at_union_depth || remaining == 0 {
break;
}
expansion = InterfaceExpansion::new(max_union_depth, remaining);
deepest = expand_inferred_interfaces(ty, inferred_generics, types, &mut expansion);
}
deepest
}
/// `ty` with each data-only interface that names one of `inferred_generics`
/// replaced by its fields, through object fields and index values, array and
/// tuple elements and union members: the positions a literal's own fields and
/// elements take their hints from. An interface stays as it is when met again inside its
/// own fields (so a recursive one expands once), when more unions than the
/// walk allows enclose it, or once the walk has used its budget.
fn expand_inferred_interfaces(
ty: &Type,
inferred_generics: &[String],
types: super::assignable::TypeResolver,
expansion: &mut InterfaceExpansion,
) -> Type {
let expand = |inner: &Type, expansion: &mut InterfaceExpansion| {
expand_inferred_interfaces(inner, inferred_generics, types, expansion)
};
match ty.peel() {
interface @ Type::InterfaceRef { mangled, .. }
if !expansion.expanding.contains(mangled)
&& super::expr::mentions_type_var(interface, &|var| {
inferred_generics.iter().any(|name| name == var)
}) =>
{
if expansion.union_depth > expansion.max_union_depth {
expansion.cut_at_union_depth = true;
return ty.clone();
}
if !expansion.can_expand() {
return ty.clone();
}
let Some(shape) = super::assignable::expand_interface_data_shape(interface, types)
else {
return ty.clone();
};
expansion.spend();
expansion.expanding.push(mangled.clone());
let expanded = expand(&shape, expansion);
expansion.expanding.pop();
expanded
}
Type::Object { fields, index } => Type::Object {
fields: fields
.iter()
.map(|(name, field)| {
let ty = expand(&field.ty, expansion);
(
name.clone(),
crate::types::ObjectField {
ty,
..field.clone()
},
)
})
.collect(),
index: index
.as_ref()
.map(|index| index.map_value(|value| expand(value, expansion))),
},
Type::Array(element) => Type::Array(Box::new(expand(element, expansion))),
Type::Tuple(elements) => Type::Tuple(elements.map(|element| expand(element, expansion))),
Type::Union(members) => {
expansion.union_depth += 1;
let expanded = members
.iter()
.map(|member| expand(member, expansion))
.collect();
expansion.union_depth -= 1;
Type::union(expanded)
}
_ => ty.clone(),
}
}
/// The function type a parameter holds: itself through aliases, or the one
/// function member of a union such as `((x: T) => U) | null`.
fn function_part(ty: &Type) -> Option<&Type> {
match ty.peel() {
function @ Type::Function { .. } => Some(function),
Type::Union(members) => {
let mut functions = members
.iter()
.map(Type::peel)
.filter(|member| matches!(member, Type::Function { .. }));
let function = functions.next()?;
functions.next().is_none().then_some(function)
}
_ => None,
}
}
/// Bind the type parameters a deferred callback's parameters take that no
/// other argument inferred to their whole-union fallback, or to `unknown`
/// when there is none, as tsc fixes them before typing the callback:
/// `Array.from({ length: 3 }, (_, i) => i)` types `_` as `unknown`.
fn fix_callback_parameters(sub: &mut TypeParamSubstitution, param_ty: &Type, inferred: &[String]) {
for name in inferred {
if takes_in_callback(param_ty, name) && sub.get(name).is_none() {
let fixed = sub.whole_union_fallback(name).cloned();
sub.insert(name.clone(), fixed.unwrap_or(Type::Unknown));
}
}
}
/// Whether the callback `param_ty` describes takes the type parameter `name`
/// in one of its parameters.
fn takes_in_callback(param_ty: &Type, name: &str) -> bool {
let Some(Type::Function { params, .. }) = function_part(param_ty) else {
return false;
};
params
.iter()
.any(|param| super::expr::mentions_type_var(param, &|var| var == name))
}
/// An object or tuple literal argument whose slots, its fields or elements,
/// bind a generic call's type parameters one at a time, for the callback slots
/// typed after them.
pub(crate) struct LiteralArgumentInference {
literal: ExprId,
/// The parameter's slots in terms of the type parameters, keyed by field
/// name or by element index (`"0"`, `"1"`, …).
slots: std::collections::BTreeMap<String, crate::ObjectField>,
sub: TypeParamSubstitution,
/// Type parameters a callback slot bound to just their whole-union
/// fallback, left unbound so a later slot may bind them; see
/// [`TypeParamSubstitution::unbind_fallback_echoes`].
fallback_echoes: Vec<String>,
}
/// A coarse category of value, used to skip the union members a call's result
/// can never be (a function result and `null`). `Uint8Array` is a primitive
/// here: no generic result type can be one.
#[derive(Clone, Copy, PartialEq)]
enum ShapeKind {
Function,
/// An object, interface, class instance, array or tuple.
Structured,
Primitive,
/// A type parameter, `unknown`, an error: anything.
Any,
}
impl ShapeKind {
fn of(ty: &Type) -> Self {
match ty.peel() {
Type::Function { .. } => Self::Function,
// An array is assignable to an interface or object type of the
// fields it has (`{ length: number }`), so it is one kind with them.
Type::Object { .. }
| Type::InterfaceRef { .. }
| Type::ClassRef { .. }
| Type::Array(_)
| Type::Tuple(_) => Self::Structured,
Type::Number
| Type::NumberLiteral(_)
| Type::BigInt
| Type::BigIntLiteral(_)
| Type::String
| Type::StringLiteral(_)
| Type::Uint8Array
| Type::Boolean
| Type::BooleanLiteral(_)
| Type::NumberEnum { .. }
| Type::StringEnum { .. }
| Type::Null
| Type::Undefined
| Type::Void
| Type::Never => Self::Primitive,
_ => Self::Any,
}
}
fn could_be(self, other: Self) -> bool {
self == other || self == Self::Any || other == Self::Any
}
}
/// Whether a call's expected result type is worth binding its type parameters
/// from before the arguments are inferred. `unknown` is not: every type is
/// assignable to it, so binding a parameter to it first would hide what the
/// arguments say (`console.log(xs.reduce((a, b) => a + b, 0))` would type `a`
/// as `unknown`). It only fills the parameters the arguments leave unbound.
fn pins_type_parameters(want: &Type) -> bool {
// An enclosing call's own unbound type parameter (`use(first(1, 2))`,
// or `T | null` for `orNull(first(1, 2))`) says nothing yet, and binding
// to it would bind it from inside this call.
match want.peel() {
Type::Error | Type::Unknown | Type::TypeVar(_) => false,
Type::Union(members) => !members
.iter()
.any(|member| matches!(member.peel(), Type::TypeVar(_))),
_ => true,
}
}
/// Bind every type parameter inference left unsolved to `fallback`, so the call
/// resolves at a default rather than erroring as uninferable. Already-bound
/// parameters keep what inference gave them.
fn bind_remaining(
sub: &mut crate::typechecker::type_param_substitution::TypeParamSubstitution,
generics: &[String],
fallback: Type,
limits: &TypeLimits,
) -> Result<(), TypeTooLarge> {
if let Err(unbound) = sub.resolve_all(generics, limits)? {
for name in unbound {
sub.insert(name, fallback.clone());
}
}
Ok(())
}
/// Whether `ty` is the type parameter `name` or a union with it directly as a
/// member (`T | number`): a value given for a field of that type may be a
/// candidate for `name`.
fn is_or_has_type_var(ty: &Type, name: &str) -> bool {
let is_var = |ty: &Type| matches!(ty.peel(), Type::TypeVar(var) if var == name);
match ty.peel() {
Type::Union(members) => members.iter().any(is_var),
_ => is_var(ty),
}
}
/// Whether a property name is a canonical array index, such as `"0"` or `"12"`.
fn is_array_index(name: &str) -> bool {
name.parse::<u32>()
.is_ok_and(|index| index != u32::MAX && index.to_string() == name)
}
/// Whether an `undefined` element fits `ty`. A type parameter doesn't count,
/// unlike in `type_admits_undefined`: the caller may instantiate it with a
/// type that can't hold `undefined`.
fn admits_undefined(ty: &Type) -> bool {
let holds_undefined =
|ty: &Type| matches!(ty.peel(), Type::Undefined | Type::Void | Type::Unknown);
match ty.peel() {
Type::Error => true,
Type::Union(members) => members.iter().any(holds_undefined),
other => holds_undefined(other),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn substitute_typevars_replaces_top_level_typevar() {
let mut bindings: BTreeMap<String, Type> = BTreeMap::new();
bindings.insert("T".into(), Type::Number);
let out = substitute_typevars(
&Type::TypeVar("T".into()),
&bindings,
&crate::type_size::TypeLimits::default(),
)
.unwrap();
assert_eq!(out, Type::Number);
}
#[test]
fn substitute_typevars_recurses_into_nested_constructors() {
let mut bindings: BTreeMap<String, Type> = BTreeMap::new();
bindings.insert("T".into(), Type::String);
let arr = Type::Array(Box::new(Type::TypeVar("T".into())));
let out =
substitute_typevars(&arr, &bindings, &crate::type_size::TypeLimits::default()).unwrap();
assert_eq!(out, Type::Array(Box::new(Type::String)));
let func = Type::Function {
params: vec![Type::TypeVar("T".into())],
ret: Box::new(Type::TypeVar("T".into())),
predicate: None,
has_rest: false,
optional: 0,
};
let out = substitute_typevars(&func, &bindings, &crate::type_size::TypeLimits::default())
.unwrap();
assert_eq!(
out,
Type::Function {
params: vec![Type::String],
ret: Box::new(Type::String),
predicate: None,
has_rest: false,
optional: 0,
}
);
}
#[test]
fn substitute_typevars_leaves_unbound_names_alone() {
let mut bindings: BTreeMap<String, Type> = BTreeMap::new();
bindings.insert("T".into(), Type::Number);
let out = substitute_typevars(
&Type::TypeVar("U".into()),
&bindings,
&crate::type_size::TypeLimits::default(),
)
.unwrap();
assert_eq!(out, Type::TypeVar("U".into()));
}
#[test]
fn substitute_typevars_charges_each_copy_of_a_binding() {
crate::type_size::tests::on_compiler_stack(
substitute_typevars_charges_each_copy_of_a_binding_inner,
);
}
fn substitute_typevars_charges_each_copy_of_a_binding_inner() {
use crate::compiler_limits::{MAX_TYPE_DEPTH, MAX_TYPE_NODES};
use crate::type_size::{TypeLimits, TypeTooLarge};
let pair = Type::Tuple(vec![Type::TypeVar("T".into()), Type::TypeVar("T".into())].into());
let limits = TypeLimits::default();
// The tuple itself plus two copies of the binding, each a tuple of
// numbers: MAX_TYPE_NODES - 1 nodes, then MAX_TYPE_NODES + 1.
let half = Type::Tuple(vec![Type::Number; (MAX_TYPE_NODES / 2 - 2) as usize].into());
let bindings = BTreeMap::from([("T".to_string(), half)]);
assert!(substitute_typevars(&pair, &bindings, &limits).is_ok());
let over = Type::Tuple(vec![Type::Number; (MAX_TYPE_NODES / 2 - 1) as usize].into());
let bindings = BTreeMap::from([("T".to_string(), over)]);
assert_eq!(
substitute_typevars(&pair, &bindings, &limits),
Err(TypeTooLarge::Nodes)
);
let deep = (1..MAX_TYPE_DEPTH).fold(Type::Number, |inner, _| Type::Array(Box::new(inner)));
let bindings = BTreeMap::from([("T".to_string(), deep)]);
assert_eq!(
substitute_typevars(&pair, &bindings, &limits),
Err(TypeTooLarge::Depth)
);
}
use super::super::test_support::{run, run_clean};
use crate::{ExprId, PackageDeclaration, Param, StmtId, TypedAst, TypedStmtKind, ValueKind};
fn last_call_resolved_ty(ta: &TypedAst) -> Type {
for &id in ta.top_level_statements.iter().rev() {
if let TypedStmtKind::AssignGlobal { value, .. } = &ta.try_stmt(id).unwrap().kind {
return ta.try_expr(*value).unwrap().ty.clone();
}
}
panic!("no top-level let/const init found");
}
#[test]
fn hof_map_infers_return_with_defaulted_callback_parameter() {
let (ta, diags) = run(r#"
function addDefault(value: number, index: number = 100): number {
return value + index;
}
let result = [1, 2, 3].map(addDefault);
"#);
assert!(diags.is_empty(), "unexpected diags: {diags:?}");
assert_eq!(
last_call_resolved_ty(&ta),
Type::Array(Box::new(Type::Number))
);
}
#[test]
fn hof_map_infers_return_with_wider_callback_parameter() {
let (ta, diags) = run(r#"
function describe(value: number | null): string { return "value"; }
let result = [1, 2, 3].map(describe);
"#);
assert!(diags.is_empty(), "unexpected diags: {diags:?}");
assert_eq!(
last_call_resolved_ty(&ta),
Type::Array(Box::new(Type::String))
);
}
#[test]
fn hof_map_rejects_narrower_callback_parameter() {
let (_, diags) = run(r#"
function describe(value: number): string { return "value"; }
let values: (number | null)[] = [1, null];
let result = values.map(describe);
"#);
assert!(
!diags.is_empty(),
"narrow callback must reject nullable inputs"
);
}
#[test]
fn hof_map_typechecks_closure_arg() {
let (ta, diags) = run(r#"
function map<T, U>(arr: T[], fn: (x: T) => U): U[] {
return [];
}
let result = map([1, 2, 3], (x: number): string => x.toString());
"#);
assert!(diags.is_empty(), "unexpected diags: {diags:?}");
let ty = last_call_resolved_ty(&ta);
assert_eq!(
ty,
Type::Array(Box::new(Type::String)),
"expected string[], got {ty:?}",
);
}
#[test]
fn hof_filter_typechecks_predicate() {
let (ta, diags) = run(r#"
function filter<T>(arr: T[], pred: (x: T) => boolean): T[] {
return [];
}
let result = filter(["a", "b"], (x: string): boolean => x === "a");
"#);
assert!(diags.is_empty(), "unexpected diags: {diags:?}");
let ty = last_call_resolved_ty(&ta);
assert_eq!(ty, Type::Array(Box::new(Type::String)));
}
#[test]
fn hof_reduce_typechecks_with_accumulator() {
let (ta, diags) = run(r#"
function reduce<T, U>(arr: T[], fn: (acc: U, x: T) => U, init: U): U {
return init;
}
let result = reduce([1, 2, 3], (acc: number, x: number): number => acc + x, 0);
"#);
assert!(diags.is_empty(), "unexpected diags: {diags:?}");
let ty = last_call_resolved_ty(&ta);
assert_eq!(ty, Type::Number);
}
#[test]
fn hof_bidirectional_return_seeds_t_from_lhs_annotation() {
let (ta, diags) = run(r#"
function none<T>(): T[] {
return [];
}
let result: number[] = none();
"#);
assert!(diags.is_empty(), "unexpected diags: {diags:?}");
let ty = last_call_resolved_ty(&ta);
assert_eq!(ty, Type::Array(Box::new(Type::Number)));
}
fn collect_gps(ty: &Type, out: &mut Vec<u32>) {
match ty {
Type::GenericParam { id, .. } => out.push(*id),
Type::Array(elem) => collect_gps(elem, out),
Type::Function { params, ret, .. } => {
for p in params {
collect_gps(p, out);
}
collect_gps(ret, out);
}
Type::Object { fields, .. } => {
for v in fields.values() {
collect_gps(&v.ty, out);
}
}
_ => {}
}
}
fn collect_body_expr_types(ta: &TypedAst, stmt_id: StmtId, out: &mut Vec<Type>) {
let stmt = ta.try_stmt(stmt_id).unwrap();
match &stmt.kind {
TypedStmtKind::Block(children) => {
for &c in children {
collect_body_expr_types(ta, c, out);
}
}
TypedStmtKind::Let { value, .. }
| TypedStmtKind::Const { value, .. }
| TypedStmtKind::AssignLocal { value, .. }
| TypedStmtKind::AssignGlobal { value, .. } => {
collect_expr_types(ta, *value, out);
}
TypedStmtKind::AssignField {
receiver, value, ..
} => {
collect_expr_types(ta, *receiver, out);
collect_expr_types(ta, *value, out);
}
TypedStmtKind::AssignIndex {
receiver,
index,
value,
..
} => {
collect_expr_types(ta, *receiver, out);
collect_expr_types(ta, *index, out);
collect_expr_types(ta, *value, out);
}
TypedStmtKind::Return(Some(e)) | TypedStmtKind::Expr(e) => {
collect_expr_types(ta, *e, out);
}
TypedStmtKind::Return(None) => {}
TypedStmtKind::If {
condition,
then_block,
else_block,
} => {
collect_expr_types(ta, *condition, out);
collect_body_expr_types(ta, *then_block, out);
if let Some(eb) = else_block {
collect_body_expr_types(ta, *eb, out);
}
}
TypedStmtKind::While { condition, body } => {
collect_expr_types(ta, *condition, out);
collect_body_expr_types(ta, *body, out);
}
TypedStmtKind::For {
init,
condition,
update,
body,
} => {
if let Some(i) = init {
collect_body_expr_types(ta, *i, out);
}
if let Some(c) = condition {
collect_expr_types(ta, *c, out);
}
if let Some(u) = update {
collect_body_expr_types(ta, *u, out);
}
collect_body_expr_types(ta, *body, out);
}
TypedStmtKind::ForOf { iter, body, .. } => {
collect_expr_types(ta, *iter, out);
collect_body_expr_types(ta, *body, out);
}
TypedStmtKind::DoWhile { body, condition } => {
collect_body_expr_types(ta, *body, out);
collect_expr_types(ta, *condition, out);
}
TypedStmtKind::Switch {
discriminant,
cases,
default,
..
} => {
collect_expr_types(ta, *discriminant, out);
for comparison in cases
.iter()
.flat_map(crate::TypedSwitchCase::label_comparisons)
{
collect_expr_types(ta, comparison, out);
}
for case in cases {
collect_body_expr_types(ta, case.body, out);
}
if let Some(d) = default {
collect_body_expr_types(ta, *d, out);
}
}
TypedStmtKind::Break | TypedStmtKind::Continue | TypedStmtKind::ReboxLocal { .. } => {}
TypedStmtKind::NarrowRegion { source, body, .. } => {
collect_expr_types(ta, *source, out);
collect_body_expr_types(ta, *body, out);
}
TypedStmtKind::Throw { value } => collect_expr_types(ta, *value, out),
TypedStmtKind::Try {
body,
catches,
finally,
} => {
collect_body_expr_types(ta, *body, out);
for c in catches {
collect_body_expr_types(ta, c.body, out);
}
if let Some(f) = finally {
collect_body_expr_types(ta, *f, out);
}
}
}
}
fn collect_expr_types(ta: &TypedAst, expr_id: ExprId, out: &mut Vec<Type>) {
let expr = ta.try_expr(expr_id).unwrap();
out.push(expr.ty.clone());
match &expr.kind {
crate::TypedExprKind::Binary { lhs, rhs, .. } => {
collect_expr_types(ta, *lhs, out);
collect_expr_types(ta, *rhs, out);
}
crate::TypedExprKind::Unary { operand, .. } => {
collect_expr_types(ta, *operand, out);
}
crate::TypedExprKind::Call { args, .. } | TypedExprKind::McpCall { args, .. } => {
for a in args {
collect_expr_types(ta, *a, out);
}
}
crate::TypedExprKind::CallClosure { callee, args } => {
collect_expr_types(ta, *callee, out);
for a in args {
collect_expr_types(ta, *a, out);
}
}
crate::TypedExprKind::IntrinsicCall { args, .. } => {
for a in args {
collect_expr_types(ta, *a, out);
}
}
crate::TypedExprKind::FieldAccess { receiver, .. } => {
collect_expr_types(ta, *receiver, out);
}
crate::TypedExprKind::IndexAccess { receiver, index } => {
collect_expr_types(ta, *receiver, out);
collect_expr_types(ta, *index, out);
}
crate::TypedExprKind::ObjectLiteral { members, .. } => {
for member in members {
for expression in member.expressions() {
collect_expr_types(ta, expression, out);
}
}
}
crate::TypedExprKind::ArrayLiteral { elements, .. } => {
for e in elements {
collect_expr_types(ta, e.expr_id(), out);
}
}
_ => {}
}
}
fn nth_function(ta: &TypedAst, n: usize) -> &crate::TypedFunction {
&ta.functions[n]
}
#[test]
fn generic_params_erased_to_typevar_after_inference() {
let ta = run_clean(
r#"
function f<T>(x: T): T {
let y: T = x;
return y;
}
"#,
);
let defs = PackageDeclaration::from_typed_ast(&ta);
let f = defs.values.get("f").expect("f registered");
match &f.kind {
ValueKind::Function {
generics,
params,
ret,
..
} => {
assert_eq!(generics, &vec!["T".to_string()]);
assert_eq!(
params,
&vec![Param::new("x", Type::TypeVar("T".to_string()))]
);
assert_eq!(*ret, Type::TypeVar("T".to_string()));
}
other => panic!("expected ValueKind::Function, got {other:?}"),
}
let f = nth_function(&ta, 0);
let typed_params = &f.params;
let typed_ret = f.return_type.clone();
let body = f.body;
for p in typed_params {
assert!(
matches!(p.ty, Type::TypeVar(_)),
"param `{}`: expected TypeVar, got {:?}",
p.name.name,
p.ty,
);
}
assert!(
matches!(typed_ret, Type::TypeVar(_)),
"return: expected TypeVar, got {typed_ret:?}",
);
let mut body_tys = Vec::new();
collect_body_expr_types(&ta, body, &mut body_tys);
let saw_typevar = body_tys.iter().any(|t| matches!(t, Type::TypeVar(_)));
assert!(
saw_typevar,
"body should contain TypeVar after erasure, got {body_tys:?}"
);
let mut gp_ids = Vec::new();
for t in &body_tys {
collect_gps(t, &mut gp_ids);
}
assert!(
gp_ids.is_empty(),
"body should have no GenericParam after erasure, got ids {gp_ids:?}"
);
}
#[test]
fn cross_scope_generic_bodies_have_no_gp_after_erasure() {
let ta = run_clean(
r#"
function inner<U>(y: U): U { return y; }
function outer<T>(x: T): T { return inner(x); }
"#,
);
let defs = PackageDeclaration::from_typed_ast(&ta);
for fn_name in ["inner", "outer"] {
match &defs.values.get(fn_name).unwrap().kind {
ValueKind::Function { params, ret, .. } => {
for p in params {
assert!(
matches!(p.ty, Type::TypeVar(_)),
"{fn_name}'s param should be TypeVar, got {:?}",
p.ty,
);
}
assert!(
matches!(ret, Type::TypeVar(_)),
"{fn_name}'s ret should be TypeVar, got {ret:?}"
);
}
_ => panic!(),
}
}
for n in 0..2 {
let body = nth_function(&ta, n).body;
let mut body_tys = Vec::new();
collect_body_expr_types(&ta, body, &mut body_tys);
let mut gp_ids = Vec::new();
for t in &body_tys {
collect_gps(t, &mut gp_ids);
}
assert!(
gp_ids.is_empty(),
"function #{n}'s body has GenericParam ids {gp_ids:?} after erasure",
);
}
}
#[test]
fn conflict_diagnostic_uses_real_names_not_garbled() {
let (_, diags) = run(r#"
function pair<T>(a: T, b: T): T { return a; }
function main(): void {
pair(1, "x");
}
"#);
assert!(!diags.is_empty(), "expected at least one diagnostic");
let saw_clean = diags.iter().any(|d| {
d.message.contains("`1`") && d.message.contains("`\"x\"`") && !d.message.contains("`T`")
});
assert!(
saw_clean,
"expected clean conflict diagnostic, got: {diags:#?}",
);
}
#[test]
fn cross_scope_gp_assignment_rejects_with_clean_message() {
let (_, diags) = run(r#"
function identity<T>(x: T): T { return x; }
function bar<T, U>(y: U): void {
const x: T = identity(y);
}
"#);
assert!(
!diags.is_empty(),
"expected rejection of cross-GP assignment"
);
let saw_clean = diags.iter().any(|d| {
d.message.contains('T')
&& d.message.contains('U')
&& !d.message.contains("`T`, cannot bind to `T`")
&& !d.message.contains("`T` already bound to `T`")
});
assert!(
saw_clean,
"expected clean cross-GP diagnostic mentioning both T and U, got: {diags:#?}",
);
}
#[test]
fn resolve_all_treats_self_binding_as_unbound() {
use crate::typechecker::type_param_substitution::TypeParamSubstitution;
let mut sub = TypeParamSubstitution::new();
sub.insert("T".to_string(), Type::TypeVar("T".to_string()));
let result = sub
.resolve_all(&["T".to_string()], &crate::type_size::TypeLimits::default())
.unwrap();
assert!(
result.is_err(),
"self-binding T → TypeVar(T) should be reported as unbound; got {result:?}",
);
}
#[test]
fn array_map_infers_method_level_generic_from_closure() {
let (ta, diags) = run(r#"
function main(): void {
const xs = [1, 2, 3].map((x: number): number => x);
}
"#);
assert!(diags.is_empty(), "expected clean typecheck, got: {diags:?}");
let body = ta.functions[0].body;
let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
panic!("expected block body");
};
let TypedStmtKind::Const { ty, .. } = &ta.try_stmt(stmts[0]).unwrap().kind else {
panic!("expected const");
};
assert_eq!(*ty, Type::Array(Box::new(Type::Number)));
}
#[test]
fn array_map_with_explicit_method_type_arg() {
let (ta, diags) = run(r#"
function main(): void {
const xs = [1, 2, 3].map<number>((x: number): number => x);
}
"#);
assert!(diags.is_empty(), "expected clean typecheck, got: {diags:?}");
let body = ta.functions[0].body;
let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
panic!("expected block body");
};
let TypedStmtKind::Const { ty, .. } = &ta.try_stmt(stmts[0]).unwrap().kind else {
panic!("expected const");
};
assert_eq!(*ty, Type::Array(Box::new(Type::Number)));
}
#[test]
fn array_map_explicit_type_arg_arity_mismatch_diagnoses() {
let (_, diags) = run(r#"
function main(): void {
const xs = [1].map<number, string>((x: number): number => x);
}
"#);
assert!(
diags.iter().any(|d| d
.message
.contains("method `map` expects 1 type argument(s), got 2")),
"expected type-arg arity diagnostic, got: {diags:?}",
);
}
#[test]
fn array_map_with_user_typed_closure_returns_inferred_array() {
let (ta, diags) = run(r#"
function main(): void {
const xs = [{x: 1}, {x: 2}].map(
(o: { x: number }): number => o.x
);
}
"#);
assert!(diags.is_empty(), "expected clean typecheck, got: {diags:?}");
let body = ta.functions[0].body;
let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
panic!("expected block body");
};
let TypedStmtKind::Const { ty, .. } = &ta.try_stmt(stmts[0]).unwrap().kind else {
panic!("expected const");
};
assert_eq!(*ty, Type::Array(Box::new(Type::Number)));
}
#[test]
fn user_interface_method_generic_typechecks() {
let (_, diags) = run(r#"
interface Box<T> {
map<U>(fn: (x: T) => U): U;
}
function main(): void {}
"#);
assert!(
diags.is_empty(),
"expected clean typecheck of user method-generic interface, got: {diags:?}",
);
}
#[test]
fn method_generic_shadowing_interface_generic_diagnoses() {
let (_, diags) = run(r#"
interface Foo<T> {
f<T>(): T;
}
function main(): void {}
"#);
assert!(
diags.iter().any(|d| d
.message
.contains("method generic `T` shadows interface generic `T`")),
"expected shadowing diagnostic, got: {diags:?}",
);
}
#[test]
fn array_reduce_infers_u_from_init_arg() {
let (ta, diags) = run(r#"
function main(): void {
let nums: number[] = [1, 2, 3];
let sum = nums.reduce((acc, x) => acc + x, 0);
}
"#);
assert!(
diags.is_empty(),
"expected reduce<U> to infer from init arg, got: {diags:?}",
);
let body = ta.functions[0].body;
let TypedStmtKind::Block(stmts) = &ta.try_stmt(body).unwrap().kind else {
panic!("expected block body");
};
let TypedStmtKind::Let { ty, .. } = &ta.try_stmt(stmts[1]).unwrap().kind else {
panic!("expected let sum");
};
assert_eq!(*ty, Type::Number, "sum should infer as number");
}
#[test]
fn array_reduce_infers_u_from_string_init() {
let (_, diags) = run(r#"
function main(): void {
let words = ["a", "b"].reduce((acc, s) => acc + s, "");
}
"#);
assert!(
diags.is_empty(),
"expected reduce<U> to infer U := string, got: {diags:?}",
);
}
#[test]
fn under_constrained_method_generic_is_unknown() {
let (_, diags) = run(r#"
interface Box<T> {
empty<U>(): U[];
}
function go(b: Box<number>): void {
const xs: unknown[] = b.empty();
}
"#);
assert!(
diags.is_empty(),
"expected `U` to infer as `unknown`, got: {diags:?}"
);
}
#[test]
fn rest_param_accepts_zero_trailing_args() {
let (_, diags) = run(r#"
function sum(...n: number[]): number { return 0; }
function main(): void { let x = sum(); }
"#);
assert!(diags.is_empty(), "expected clean typecheck, got: {diags:?}");
}
#[test]
fn rest_param_accepts_many_trailing_args() {
let (_, diags) = run(r#"
function sum(...n: number[]): number { return 0; }
function main(): void { let x = sum(1, 2, 3); }
"#);
assert!(diags.is_empty(), "expected clean typecheck, got: {diags:?}");
}
#[test]
fn rest_param_rejects_mismatched_trailing_arg() {
let (_, diags) = run(r#"
function sum(...n: number[]): number { return 0; }
function main(): void { let x = sum(1, "x"); }
"#);
assert!(
diags
.iter()
.any(|d| d.message.contains("number") && d.message.contains("string")),
"expected number-vs-string mismatch, got: {diags:?}",
);
}
#[test]
fn generic_rest_param_infers_element_type() {
let (_, diags) = run(r#"
function pack<T>(...xs: T[]): T[] { return xs; }
function main(): void { let n = pack(1, 2, 3); let s = pack("a", "b"); }
"#);
assert!(diags.is_empty(), "expected clean typecheck, got: {diags:?}");
}
#[test]
fn generic_rest_param_rejects_mixed_element_types() {
let (_, diags) = run(r#"
function pack<T>(...xs: T[]): T[] { return xs; }
function main(): void { let x = pack(1, "a"); }
"#);
assert!(
!diags.is_empty(),
"expected conflict diagnostic for mixed types"
);
}
#[test]
fn fixed_plus_rest_accepts_mixed_args() {
let (_, diags) = run(r#"
function tag(label: string, ...vals: number[]): string { return label; }
function main(): void {
let a = tag("x");
let b = tag("x", 1, 2);
}
"#);
assert!(diags.is_empty(), "expected clean typecheck, got: {diags:?}");
}
#[test]
fn fixed_plus_rest_requires_prefix_arg() {
let (_, diags) = run(r#"
function tag(label: string, ...vals: number[]): string { return label; }
function main(): void { let x = tag(); }
"#);
assert!(
diags
.iter()
.any(|d| d.message.contains("expected 1+ argument(s), got 0")),
"expected arity diagnostic with '+' form, got: {diags:?}",
);
}
}