luau-analyzer-sys 0.1.1

A high-performance, embedded Luau type-checking and analysis engine written in Rust. This crate provides bindings to the Luau analyzer, allowing you to integrate static analysis and code intelligence directly into your applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details

#include "Luau/AstQuery.h"
#include "Luau/BuiltinDefinitions.h"
#include "Luau/Error.h"
#include "Luau/Scope.h"
#include "Luau/TypeInfer.h"
#include "Luau/Type.h"

#include "ClassFixture.h"
#include "Fixture.h"

#include "ScopedFlags.h"
#include "doctest.h"

using namespace Luau;

LUAU_FASTFLAG(DebugLuauAssertOnForcedConstraint)

LUAU_FASTFLAG(LuauInstantiateInSubtyping)
LUAU_FASTFLAG(DebugLuauForceOldSolver)
LUAU_FASTINT(LuauTarjanChildLimit)
LUAU_FASTFLAG(LuauFormatUseLastPosition)
LUAU_FASTFLAG(LuauCheckFunctionStatementTypes)
LUAU_FASTFLAG(LuauCaptureRecursiveCallsForTablesAndGlobals2)
LUAU_FASTFLAG(LuauRelateHandlesCoincidentTables)
LUAU_FASTFLAG(LuauOverloadGetsInstantiated2)
LUAU_FASTFLAG(LuauReplacerRespectsReboundGenerics)
LUAU_FASTFLAG(LuauCaptureRecursiveCallsForTablesAndGlobals2)
LUAU_FASTFLAG(LuauForwardPolarityForFunctionTypes)
LUAU_FASTFLAG(LuauReplacerRespectsReboundGenerics)
LUAU_FASTFLAG(LuauKeepExplicitMapForGlobalTypes2)
LUAU_FASTFLAG(LuauBidirectionalInferenceBetterUnionHandling)
LUAU_FASTFLAG(LuauExplicitTypeInstantiationSupport)

TEST_SUITE_BEGIN("TypeInferFunctions");

TEST_CASE_FIXTURE(Fixture, "general_case_table_literal_blocks")
{
    CheckResult result = check(R"(
--!strict
function f(x : {[any]: number})
   return x
end

local Foo = {bar = "$$$"}

f({[Foo.bar] = 0})
)");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "overload_resolution")
{
    CheckResult result = check(R"(
        type A = (number) -> string
        type B = (string) -> number

        local function foo(f: A & B)
            return f(1), f("five")
        end
    )");
    LUAU_REQUIRE_NO_ERRORS(result);
    TypeId t = requireType("foo");
    const FunctionType* fooType = get<FunctionType>(requireType("foo"));
    REQUIRE(fooType != nullptr);

    CHECK(toString(t) == "(((number) -> string) & ((string) -> number)) -> (string, number)");
}

TEST_CASE_FIXTURE(Fixture, "tc_function")
{
    CheckResult result = check("function five() return 5 end");
    LUAU_REQUIRE_NO_ERRORS(result);

    const FunctionType* fiveType = get<FunctionType>(requireType("five"));
    REQUIRE(fiveType != nullptr);
}

TEST_CASE_FIXTURE(Fixture, "check_function_bodies")
{
    CheckResult result = check(R"(
        function myFunction(): number
            local a = 0
            a = true
            return a
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    if (!FFlag::DebugLuauForceOldSolver)
    {
        const TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
        REQUIRE_MESSAGE(tm, "Expected TypeMismatch but got " << result.errors[0]);
        CHECK(toString(tm->wantedType) == "number");
        CHECK(toString(tm->givenType) == "boolean");
    }
    else
    {
        CHECK_EQ(
            result.errors[0],
            (TypeError{
                Location{Position{3, 16}, Position{3, 20}},
                TypeMismatch{
                    getBuiltins()->numberType,
                    getBuiltins()->booleanType,
                }
            })
        );
    }
}

TEST_CASE_FIXTURE(Fixture, "cannot_hoist_interior_defns_into_signature")
{
    // This test verifies that the signature does not have access to types
    // declared within the body. Under DCR, if the function's inner scope
    // encompasses the entire function expression, it would be possible for this
    // to type check (but the solver output is somewhat undefined). This test
    // ensures that this isn't the case.
    CheckResult result = check(R"(
        local function f(x: T)
            type T = number
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    CHECK(
        result.errors[0] == TypeError{
                                Location{{1, 28}, {1, 29}},
                                getMainSourceModule()->name,
                                UnknownSymbol{
                                    "T",
                                    UnknownSymbol::Context::Type,
                                }
                            }
    );
}

TEST_CASE_FIXTURE(Fixture, "infer_return_type")
{
    CheckResult result = check("function take_five() return 5 end");
    LUAU_REQUIRE_NO_ERRORS(result);

    const FunctionType* takeFiveType = get<FunctionType>(requireType("take_five"));
    REQUIRE(takeFiveType != nullptr);

    std::vector<TypeId> retVec = flatten(takeFiveType->retTypes).first;
    REQUIRE(!retVec.empty());

    CHECK("number" == toString(retVec[0]));
}

TEST_CASE_FIXTURE(Fixture, "infer_from_function_return_type")
{
    CheckResult result = check("function take_five() return 5 end    local five = take_five()");
    LUAU_REQUIRE_NO_ERRORS(result);

    CHECK("number" == toString(requireType("five")));
}

TEST_CASE_FIXTURE(Fixture, "infer_that_function_does_not_return_a_table")
{
    CheckResult result = check(R"(
        function take_five()
            return 5
        end

        take_five().prop = 888
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    CHECK_EQ(result.errors[0], (TypeError{Location{Position{5, 8}, Position{5, 24}}, NotATable{getBuiltins()->numberType}}));
}

TEST_CASE_FIXTURE(Fixture, "generalize_table_property")
{
    CheckResult result = check(R"(
        local T = {}

        T.foo = function(x)
            return x
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    TypeId t = requireType("T");
    const TableType* tt = get<TableType>(follow(t));
    REQUIRE(tt);

    const Property& foo = tt->props.at("foo");
    REQUIRE(foo.readTy);
    TypeId fooTy = *foo.readTy;
    CHECK("<a>(a) -> a" == toString(fooTy));
}

TEST_CASE_FIXTURE(Fixture, "vararg_functions_should_allow_calls_of_any_types_and_size")
{
    CheckResult result = check(R"(
        function f(...) end

        f(1)
        f("foo", 2)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "vararg_function_is_quantified")
{
    CheckResult result = check(R"(
        local T = {}
        function T.f(...)
            local result = {}

            for i = 1, select("#", ...) do
                local dictionary = select(i, ...)
                for key, value in pairs(dictionary) do
                    result[key] = value
                end
            end

            return result
        end

        return T
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    auto r = first(getMainModule()->returnType);
    REQUIRE(r);

    TableType* ttv = getMutable<TableType>(*r);
    REQUIRE(ttv);

    REQUIRE(ttv->props.count("f"));

    const Property& f = ttv->props["f"];
    REQUIRE(f.readTy);
    TypeId k = *f.readTy;
    REQUIRE(k);
}

TEST_CASE_FIXTURE(Fixture, "list_only_alternative_overloads_that_match_argument_count")
{
    CheckResult result = check(R"(
        local multiply: ((number)->number) & ((number)->string) & ((number, number)->number)
        multiply("")
    )");

    LUAU_REQUIRE_ERROR_COUNT(2, result);

    if (!FFlag::DebugLuauForceOldSolver)
    {
        MultipleNonviableOverloads* mno = get<MultipleNonviableOverloads>(result.errors[0]);
        REQUIRE_MESSAGE(mno, "Expected MultipleNonviableOverloads but got " << result.errors[0]);
        CHECK_EQ(mno->attemptedArgCount, 1);
    }
    else
    {
        TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
        REQUIRE(tm);
        CHECK_EQ(getBuiltins()->numberType, tm->wantedType);
        CHECK_EQ(getBuiltins()->stringType, tm->givenType);
    }

    ExtraInformation* ei = get<ExtraInformation>(result.errors[1]);
    REQUIRE(ei);

    if (!FFlag::DebugLuauForceOldSolver)
    {
        // TODO CLI-170535: Improve message so we show overloads with matching and non-matching arities
        CHECK("Available overloads: (number) -> number; and (number) -> string" == ei->message);
    }
    else
        CHECK_EQ("Other overloads are also not viable: (number) -> string", ei->message);
}

TEST_CASE_FIXTURE(Fixture, "list_all_overloads_if_no_overload_takes_given_argument_count")
{
    CheckResult result = check(R"(
        local multiply: ((number)->number) & ((number)->string) & ((number, number)->number)
        multiply()
    )");

    LUAU_REQUIRE_ERROR_COUNT(2, result);

    GenericError* ge = get<GenericError>(result.errors[0]);
    REQUIRE(ge);
    CHECK_EQ("No overload for function accepts 0 arguments.", ge->message);

    ExtraInformation* ei = get<ExtraInformation>(result.errors[1]);
    REQUIRE(ei);
    CHECK_EQ("Available overloads: (number) -> number; (number) -> string; and (number, number) -> number", ei->message);
}

TEST_CASE_FIXTURE(Fixture, "dont_give_other_overloads_message_if_only_one_argument_matching_overload_exists")
{
    CheckResult result = check(R"(
        local multiply: ((number)->number) & ((number)->string) & ((number, number)->number)
        multiply(1, "")
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
    REQUIRE(tm);
    CHECK_EQ(getBuiltins()->numberType, tm->wantedType);
    CHECK_EQ(getBuiltins()->stringType, tm->givenType);
}

TEST_CASE_FIXTURE(Fixture, "infer_return_type_from_selected_overload")
{
    CheckResult result = check(R"(
        type T = {method: ((T, number) -> number) & ((number) -> string)}
        local T: T

        local a = T.method(T, 4)
        local b = T.method(5)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    CHECK_EQ("number", toString(requireType("a")));
    CHECK_EQ("string", toString(requireType("b")));
}

TEST_CASE_FIXTURE(Fixture, "too_many_arguments")
{
    // This is not part of the new non-strict specification currently.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
        --!nonstrict

        function g(a: number) end

        g()

    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    auto err = result.errors[0];
    auto acm = get<CountMismatch>(err);
    REQUIRE(acm);

    CHECK_EQ(1, acm->expected);
    CHECK_EQ(0, acm->actual);
}

TEST_CASE_FIXTURE(Fixture, "too_many_arguments_error_location")
{
    CheckResult result = check(R"(
        --!strict

        function myfunction(a: number, b:number) end
        myfunction(1)

        function getmyfunction()
            return myfunction
        end
        getmyfunction()()
    )");

    LUAU_REQUIRE_ERROR_COUNT(2, result);

    {
        TypeError err = result.errors[0];

        // Ensure the location matches the location of the function identifier
        CHECK_EQ(err.location, Location(Position(4, 8), Position(4, 18)));

        auto acm = get<CountMismatch>(err);
        REQUIRE(acm);
        CHECK_EQ(2, acm->expected);
        CHECK_EQ(1, acm->actual);
    }
    {
        TypeError err = result.errors[1];

        // Ensure the location matches the location of the expression returning the function
        CHECK_EQ(err.location, Location(Position(9, 8), Position(9, 23)));

        auto acm = get<CountMismatch>(err);
        REQUIRE(acm);
        CHECK_EQ(2, acm->expected);
        CHECK_EQ(0, acm->actual);
    }
}

TEST_CASE_FIXTURE(Fixture, "recursive_function")
{
    CheckResult result = check(R"(
        function count(n: number)
            if n == 0 then
                return 0
            else
                return count(n - 1)
            end
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "lambda_form_of_local_function_cannot_be_recursive")
{
    CheckResult result = check(R"(
        local f = function() return f() end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
}

TEST_CASE_FIXTURE(Fixture, "recursive_local_function")
{
    CheckResult result = check(R"(
        local function count(n: number)
            if n == 0 then
                return 0
            else
                return count(n - 1)
            end
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

// FIXME: This and the above case get handled very differently.  It's pretty dumb.
// We really should unify the two code paths, probably by deleting AstStatFunction.
TEST_CASE_FIXTURE(Fixture, "another_recursive_local_function")
{
    CheckResult result = check(R"(
        local count
        function count(n: number)
            if n == 0 then
                return 0
            else
                return count(n - 1)
            end
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

// We had a bug where we'd look up the type of a recursive call using the DFG,
// not the bindings tables.  As a result, we would erroneously use the
// generalized type of foo() in this recursive fragment.  This creates a
// constraint cycle that doesn't always work itself out.
//
// The fix is for the DFG node within the scope of foo() to retain the
// ungeneralized type of foo.
TEST_CASE_FIXTURE(BuiltinsFixture, "recursive_calls_must_refer_to_the_ungeneralized_type")
{
    CheckResult result = check(R"(
        function foo()
            string.format('%s: %s', "51", foo())
        end
    )");
}

TEST_CASE_FIXTURE(Fixture, "cyclic_function_type_in_rets")
{
    CheckResult result = check(R"(
        function f()
            return f
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    CHECK_EQ("t1 where t1 = () -> t1", toString(requireType("f")));
}

TEST_CASE_FIXTURE(Fixture, "another_higher_order_function")
{
    CheckResult result = check(R"(
        local Get_des
        function Get_des(func)
            Get_des(func)
        end

        local function f(d)
            d:IsA("BasePart")
            d.Parent:FindFirstChild("Humanoid")
            d:IsA("Decal")
        end
        Get_des(f)

    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "another_other_higher_order_function")
{
    if (!FFlag::DebugLuauForceOldSolver)
    {
        CheckResult result = check(R"(
            local function f(d)
                d:foo()
                d:foo()
            end
        )");

        LUAU_REQUIRE_NO_ERRORS(result);
    }
    else
    {
        CheckResult result = check(R"(
            local d
            d:foo()
            d:foo()
        )");

        LUAU_REQUIRE_NO_ERRORS(result);
    }
}

TEST_CASE_FIXTURE(Fixture, "local_function")
{
    CheckResult result = check(R"(
        function f()
            return 8
        end

        function g()
            local function f()
                return 'hello'
            end
            return f
        end

        local h = g()
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    TypeId h = follow(requireType("h"));

    const FunctionType* ftv = get<FunctionType>(h);
    REQUIRE(ftv != nullptr);

    std::optional<TypeId> rt = first(ftv->retTypes);
    REQUIRE(bool(rt));

    TypeId retType = follow(*rt);
    CHECK_EQ(PrimitiveType::String, getPrimitiveType(retType));
}

TEST_CASE_FIXTURE(Fixture, "func_expr_doesnt_leak_free")
{
    CheckResult result = check(R"(
        local p = function(x) return x end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    const Luau::FunctionType* fn = get<FunctionType>(requireType("p"));
    REQUIRE(fn);
    auto ret = first(fn->retTypes);
    REQUIRE(ret);
    REQUIRE(get<GenericType>(follow(*ret)));
}

TEST_CASE_FIXTURE(Fixture, "first_argument_can_be_optional")
{
    CheckResult result = check(R"(
        local T = {}
        function T.new(a: number?, b: number?, c: number?) return 5 end
        local m = T.new()
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    dumpErrors(result);
}

TEST_CASE_FIXTURE(Fixture, "it_is_ok_not_to_supply_enough_retvals")
{
    CheckResult result = check(R"(
        function get_two() return 5, 6 end

        local a = get_two()
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    dumpErrors(result);
}

TEST_CASE_FIXTURE(Fixture, "duplicate_functions2")
{
    CheckResult result = check(R"(
        function foo() end

        function bar()
            local function foo() end
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(0, result);
}

TEST_CASE_FIXTURE(Fixture, "duplicate_functions_allowed_in_nonstrict")
{
    CheckResult result = check(R"(
        --!nonstrict
        function foo() end

        function foo() end

        function bar()
            local function foo() end
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "duplicate_functions_with_different_signatures_not_allowed_in_nonstrict")
{
    // This is not part of the spec for the new non-strict mode currently.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
        --!nonstrict
        function foo(): number
            return 1
        end
        foo()

        function foo(n: number): number
            return 2
        end
        foo()
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
    REQUIRE(tm);
    CHECK_EQ("() -> number", toString(tm->wantedType));
    CHECK_EQ("(number) -> number", toString(tm->givenType));
}

TEST_CASE_FIXTURE(Fixture, "complicated_return_types_require_an_explicit_annotation")
{
    CheckResult result = check(R"(
        local i = 0
        function most_of_the_natural_numbers(): number?
            if i < 10 then
                i += 1
                return i
            else
                return nil
            end
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    TypeId ty = requireType("most_of_the_natural_numbers");
    const FunctionType* functionType = get<FunctionType>(ty);
    REQUIRE_MESSAGE(functionType, "Expected function but got " << toString(ty));

    std::optional<TypeId> retType = first(functionType->retTypes);
    REQUIRE(retType);
    CHECK(get<UnionType>(*retType));
}

TEST_CASE_FIXTURE(Fixture, "infer_higher_order_function")
{
    CheckResult result = check(R"(
        function apply(f, x)
            return f(x)
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    const FunctionType* ftv = get<FunctionType>(requireType("apply"));
    REQUIRE(ftv != nullptr);

    std::vector<TypeId> argVec = flatten(ftv->argTypes).first;

    REQUIRE_EQ(2, argVec.size());

    const FunctionType* fType = get<FunctionType>(follow(argVec[0]));
    REQUIRE_MESSAGE(fType != nullptr, "Expected a function but got " << toString(argVec[0]));

    std::vector<TypeId> fArgs = flatten(fType->argTypes).first;

    TypeId xType = follow(argVec[1]);

    CHECK_EQ(1, fArgs.size());
    CHECK_EQ(xType, follow(fArgs[0]));
}

TEST_CASE_FIXTURE(Fixture, "higher_order_function_2")
{
    // CLI-114134: this code *probably* wants the egraph in order
    // to work properly. The new solver either falls over or
    // forces so many constraints as to be unreliable.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
        function bottomupmerge(comp, a, b, left, mid, right)
            local i, j = left, mid
            for k = left, right do
                if i < mid and (j > right or not comp(a[j], a[i])) then
                    b[k] = a[i]
                    i = i + 1
                else
                    b[k] = a[j]
                    j = j + 1
                end
            end
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    const FunctionType* ftv = get<FunctionType>(requireType("bottomupmerge"));
    REQUIRE(ftv != nullptr);

    std::vector<TypeId> argVec = flatten(ftv->argTypes).first;

    REQUIRE_EQ(6, argVec.size());

    const FunctionType* fType = get<FunctionType>(follow(argVec[0]));
    REQUIRE(fType != nullptr);
}

TEST_CASE_FIXTURE(Fixture, "higher_order_function_3")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false}, {FFlag::LuauReplacerRespectsReboundGenerics, true}, {FFlag::LuauOverloadGetsInstantiated2, true}
    };

    CheckResult result = check(R"(
        function swap(p)
            local t = p[0]
            p[0] = p[1]
            p[1] = t
            return nil
        end

        function swapTwice(p)
            swap(p)
            swap(p)
            return p
        end

        function swapTwiceOn(t: { number })
            swapTwice(t)
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    // FIXME CLI-180636: Previously, the generic leaking from `swap` caused this
    // to have a "reasonable" looking type. `swapTwice` was impossible to call.
    //
    // We can _probably_ fix this in the
    // future via Unifier3, as we'll be able to observe that the upper bound
    // of `p` in `swapTwice` will be `{ 'a }` and not create two indexer
    // upper bounds.
    CHECK_EQ("<a, b>({a} & {b}) -> {a} & {b}", toString(requireType("swapTwice")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "higher_order_function_4")
{
    // CLI-114134: this code *probably* wants the egraph in order
    // to work properly. The new solver either falls over or
    // forces so many constraints as to be unreliable.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
        function bottomupmerge(comp, a, b, left, mid, right)
            local i, j = left, mid
            for k = left, right do
                if i < mid and (j > right or not comp(a[j], a[i])) then
                    b[k] = a[i]
                    i = i + 1
                else
                    b[k] = a[j]
                    j = j + 1
                end
            end
        end

        function mergesort<T>(arr: {T}, comp: (T, T) -> boolean)
            local work = {}
            for i = 1, #arr do
                work[i] = arr[i]
            end
            local width = 1
            while width < #arr do
                for i = 1, #arr, 2*width do
                    bottomupmerge(comp, arr, work, i, math.min(i+width, #arr), math.min(i+2*width-1, #arr))
                end
                local temp = work
                work = arr
                arr = temp
                width = width * 2
            end
            return arr
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    /*
     * mergesort takes two arguments: an array of some type T and a function that takes two Ts.
     * We must assert that these two types are in fact the same type.
     * In other words, comp(arr[x], arr[y]) is well-typed.
     */

    const FunctionType* ftv = get<FunctionType>(requireType("mergesort"));
    REQUIRE(ftv != nullptr);

    std::vector<TypeId> argVec = flatten(ftv->argTypes).first;

    REQUIRE_EQ(2, argVec.size());

    const TableType* arg0 = get<TableType>(follow(argVec[0]));
    REQUIRE(arg0 != nullptr);
    REQUIRE(bool(arg0->indexer));

    const FunctionType* arg1 = get<FunctionType>(follow(argVec[1]));
    REQUIRE(arg1 != nullptr);
    REQUIRE_EQ(2, size(arg1->argTypes));

    std::vector<TypeId> arg1Args = flatten(arg1->argTypes).first;

    CHECK(follow(arg0->indexer->indexResultType) == follow(arg1Args[0]));
    CHECK(follow(arg0->indexer->indexResultType) == follow(arg1Args[1]));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "mutual_recursion")
{
    CheckResult result = check(R"(
        --!strict

        function newPlayerCharacter()
            startGui() -- Unknown symbol 'startGui'
        end

        local characterAddedConnection: any
        function startGui()
            characterAddedConnection = game:GetService("Players").LocalPlayer.CharacterAdded:connect(newPlayerCharacter)
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "toposort_doesnt_break_mutual_recursion")
{
    CheckResult result = check(R"(
        --!strict
        local x = nil
        function f() g() end
        -- make sure print(x) doesn't get toposorted here, breaking the mutual block
        function g() x = f end
        print(x)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    dumpErrors(result);
}

TEST_CASE_FIXTURE(Fixture, "check_function_before_lambda_that_uses_it")
{
    CheckResult result = check(R"(
        --!nonstrict

        function f()
            return 114
        end

        return function()
            return f():andThen()
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "it_is_ok_to_oversaturate_a_higher_order_function_argument")
{
    CheckResult result = check(R"(
        function onerror() end
        function foo() end
        xpcall(foo, onerror)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "another_indirect_function_case_where_it_is_ok_to_provide_too_many_arguments")
{
    CheckResult result = check(R"(
        local mycb: (number, number) -> ()

        function f() end

        mycb = f
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "report_exiting_without_return_nonstrict")
{
    // new non-strict mode spec does not include this error yet.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
        --!nonstrict

        local function f1(v): number?
            if v then
                return 1
            end
        end

        local function f2(v)
            if v then
                return 1
            end
        end

        local function f3(v): ()
            if v then
                return
            end
        end

        local function f4(v)
            if v then
                return
            end
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    FunctionExitsWithoutReturning* err = get<FunctionExitsWithoutReturning>(result.errors[0]);
    CHECK(err);
}

TEST_CASE_FIXTURE(Fixture, "report_exiting_without_return_strict")
{
    CheckResult result = check(R"(
        --!strict

        local function f1(v): number?
            if v then
                return 1
            end
        end

        local function f2(v)
            if v then
                return 1
            end
        end

        local function f3(v): ()
            if v then
                return
            end
        end

        local function f4(v)
            if v then
                return
            end
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(2, result);
    FunctionExitsWithoutReturning* annotatedErr = get<FunctionExitsWithoutReturning>(result.errors[0]);
    CHECK(annotatedErr);

    FunctionExitsWithoutReturning* inferredErr = get<FunctionExitsWithoutReturning>(result.errors[1]);
    CHECK(inferredErr);
}

TEST_CASE_FIXTURE(Fixture, "calling_function_with_incorrect_argument_type_yields_errors_spanning_argument")
{
    CheckResult result = check(R"(
        function foo(a: number, b: string) end

        foo("Test", 123)
    )");

    LUAU_REQUIRE_ERROR_COUNT(2, result);

    CHECK_EQ(
        result.errors[0],
        (TypeError{
            Location{Position{3, 12}, Position{3, 18}},
            TypeMismatch{
                getBuiltins()->numberType,
                getBuiltins()->stringType,
            }
        })
    );

    CHECK_EQ(
        result.errors[1],
        (TypeError{
            Location{Position{3, 20}, Position{3, 23}},
            TypeMismatch{
                getBuiltins()->stringType,
                getBuiltins()->numberType,
            }
        })
    );
}

TEST_CASE_FIXTURE(BuiltinsFixture, "calling_function_with_anytypepack_doesnt_leak_free_types")
{
    CheckResult result = check(R"(
        --!nonstrict

        function Test(a)
            return 1, ""
        end


        local tab = {}
        table.insert(tab, Test(1));
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    ToStringOptions opts;
    opts.exhaustive = true;
    opts.maxTableLength = 0;

    if (!FFlag::DebugLuauForceOldSolver)
        CHECK_EQ("{string}", toString(requireType("tab"), opts));
    else
        CHECK_EQ("{any}", toString(requireType("tab"), opts));
}

TEST_CASE_FIXTURE(Fixture, "too_many_return_values")
{
    CheckResult result = check(R"(
        --!strict

        function f()
            return 55
        end

        local a, b = f()
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    CountMismatch* acm = get<CountMismatch>(result.errors[0]);
    REQUIRE(acm);
    CHECK_EQ(acm->context, CountMismatch::FunctionResult);
    CHECK_EQ(acm->expected, 1);
    CHECK_EQ(acm->actual, 2);
}

TEST_CASE_FIXTURE(Fixture, "too_many_return_values_in_parentheses")
{
    // FIXME: CLI-116157 variadic and generic type packs seem to be interacting incorrectly.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
        --!strict

        function f()
            return 55
        end

        local a, b = (f())
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    CountMismatch* acm = get<CountMismatch>(result.errors[0]);
    REQUIRE(acm);
    CHECK_EQ(acm->context, CountMismatch::FunctionResult);
    CHECK_EQ(acm->expected, 1);
    CHECK_EQ(acm->actual, 2);
}

TEST_CASE_FIXTURE(Fixture, "too_many_return_values_no_function")
{
    // FIXME: CLI-116157 variadic and generic type packs seem to be interacting incorrectly.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
        --!strict

        local a, b = 55
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    CountMismatch* acm = get<CountMismatch>(result.errors[0]);
    REQUIRE(acm);
    CHECK_EQ(acm->context, CountMismatch::ExprListResult);
    CHECK_EQ(acm->expected, 1);
    CHECK_EQ(acm->actual, 2);
}

TEST_CASE_FIXTURE(Fixture, "ignored_return_values")
{
    CheckResult result = check(R"(
        --!strict

        function f()
            return 55, ""
        end

        local a = f()
    )");

    LUAU_REQUIRE_ERROR_COUNT(0, result);
}

TEST_CASE_FIXTURE(Fixture, "function_does_not_return_enough_values")
{
    CheckResult result = check(R"(
        --!strict

        function f(): (number, string)
            return 55
        end
    )");

    if (!FFlag::DebugLuauForceOldSolver)
    {
        LUAU_REQUIRE_ERROR_COUNT(1, result);

        auto tpm = get<TypePackMismatch>(result.errors[0]);
        REQUIRE(tpm);
        CHECK("number, string" == toString(tpm->wantedTp));
        CHECK("number" == toString(tpm->givenTp));
    }
    else
    {
        LUAU_REQUIRE_ERROR_COUNT(1, result);

        CountMismatch* acm = get<CountMismatch>(result.errors[0]);
        REQUIRE(acm);
        CHECK_EQ(acm->context, CountMismatch::Return);
        CHECK_EQ(acm->expected, 2);
        CHECK_EQ(acm->actual, 1);
    }
}

TEST_CASE_FIXTURE(Fixture, "function_cast_error_uses_correct_language")
{
    CheckResult result = check(R"(
        function foo(a, b): number
            return 0
        end

        local a: (string)->number = foo
        local b: (number, number)->(number, number) = foo

        local c: (string, number)->number = foo -- no error
    )");

    LUAU_REQUIRE_ERROR_COUNT(2, result);

    auto tm1 = get<TypeMismatch>(result.errors[0]);
    REQUIRE(tm1);

    CHECK_EQ("(string) -> number", toString(tm1->wantedType));
    if (!FFlag::DebugLuauForceOldSolver)
        CHECK_EQ("(unknown, unknown) -> number", toString(tm1->givenType));
    else
        CHECK_EQ("(string, *error-type*) -> number", toString(tm1->givenType));

    auto tm2 = get<TypeMismatch>(result.errors[1]);
    REQUIRE(tm2);

    CHECK_EQ("(number, number) -> (number, number)", toString(tm2->wantedType));
    if (!FFlag::DebugLuauForceOldSolver)
        CHECK_EQ("(unknown, unknown) -> number", toString(tm1->givenType));
    else
        CHECK_EQ("(string, *error-type*) -> number", toString(tm2->givenType));
}

TEST_CASE_FIXTURE(Fixture, "no_lossy_function_type")
{
    CheckResult result = check(R"(
        --!strict
        local tbl = {}
        function tbl:abc(a: number, b: number)
            return a
        end
        tbl:abc(1, 2) -- Line 6
        --   | Column 14
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    TypeId type = requireTypeAtPosition(Position(6, 14));
    if (!FFlag::DebugLuauForceOldSolver)
        CHECK_EQ("(unknown, number, number) -> number", toString(type));
    else
        CHECK_EQ("(tbl, number, number) -> number", toString(type));
    auto ftv = get<FunctionType>(follow(type));
    REQUIRE(ftv);
    CHECK(ftv->hasSelf);
}

TEST_CASE_FIXTURE(Fixture, "record_matching_overload")
{
    CheckResult result = check(R"(
        type Overload = ((string) -> string) & ((number) -> number)
        local abc: Overload
        abc(1)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    // AstExprCall is the node that has the overload stored on it.
    // findTypeAtPosition will look at the AstExprLocal, but this is not what
    // we want to look at.
    std::vector<AstNode*> ancestry = findAstAncestryOfPosition(*getMainSourceModule(), Position(3, 10));
    REQUIRE_GE(ancestry.size(), 2);
    AstExpr* parentExpr = ancestry[ancestry.size() - 2]->asExpr();
    REQUIRE(bool(parentExpr));
    REQUIRE(parentExpr->is<AstExprCall>());

    ModulePtr module = getMainModule();
    auto it = module->astOverloadResolvedTypes.find(parentExpr);
    REQUIRE(it);
    CHECK_EQ(toString(*it), "(number) -> number");
}

TEST_CASE_FIXTURE(Fixture, "return_type_by_overload")
{
    CheckResult result = check(R"(
        type Overload = ((string) -> string) & ((number, number) -> number)
        local abc: Overload
        local x = abc(true)
        local y = abc(true,true)
        local z = abc(true,true,true)
    )");

    LUAU_REQUIRE_ERRORS(result);
    CHECK_EQ("string", toString(requireType("x")));
    CHECK_EQ("number", toString(requireType("y")));
    if (!FFlag::DebugLuauForceOldSolver)
        // FIXME CLI-180645: Should this be string|number?
        CHECK_EQ("*error-type*", toString(requireType("z")));
    else
        CHECK_EQ("string", toString(requireType("z")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "infer_anonymous_function_arguments")
{
    // FIXME: CLI-116133 bidirectional type inference needs to push expected types in for higher-order function calls
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    // Simple direct arg to arg propagation
    CheckResult result = check(R"(
type Table = { x: number, y: number }
local function f(a: (Table) -> number) return a({x = 1, y = 2}) end
f(function(a) return a.x + a.y end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    // An optional function is accepted, but since we already provide a function, nil can be ignored
    result = check(R"(
type Table = { x: number, y: number }
local function f(a: ((Table) -> number)?) if a then return a({x = 1, y = 2}) else return 0 end end
f(function(a) return a.x + a.y end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    // Make sure self calls match correct index
    result = check(R"(
type Table = { x: number, y: number }
local x = {}
x.b = {x = 1, y = 2}
function x:f(a: (Table) -> number) return a(self.b) end
x:f(function(a) return a.x + a.y end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    // Mix inferred and explicit argument types
    result = check(R"(
function f(a: (a: number, b: number, c: boolean) -> number) return a(1, 2, true) end
f(function(a: number, b, c) return c and a + b or b - a end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    // Anonymous function has a variadic pack
    result = check(R"(
type Table = { x: number, y: number }
local function f(a: (Table) -> number) return a({x = 1, y = 2}) end
f(function(...) return select(1, ...).z end)
    )");

    LUAU_REQUIRE_ERRORS(result);
    CHECK_EQ("Key 'z' not found in table 'Table'", toString(result.errors[0]));

    // Can't accept more arguments than provided
    result = check(R"(
function f(a: (a: number, b: number) -> number) return a(1, 2) end
f(function(a, b, c, ...) return a + b end)
    )");

    LUAU_REQUIRE_ERRORS(result);

    std::string expected;
    if (FFlag::LuauInstantiateInSubtyping)
    {
        expected = "Expected this to be\n\t"
                   "'(number, number) -> number'"
                   "\nbut got\n\t"
                   "'<a>(number, number, a) -> number'"
                   "\ncaused by:\n"
                   "  Argument count mismatch. Function expects 3 arguments, but only 2 are specified";
    }
    else
    {
        expected = "Expected this to be\n\t"
                   "'(number, number) -> number'"
                   "\nbut got\n\t"
                   "'(number, number, *error-type*) -> number'"
                   "\ncaused by:\n"
                   "  Argument count mismatch. Function expects 3 arguments, but only 2 are specified";
    }

    CHECK_EQ(expected, toString(result.errors[0]));

    // Infer from variadic packs into elements
    result = check(R"(
function f(a: (...number) -> number) return a(1, 2) end
f(function(a, b) return a + b end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    // Infer from variadic packs into variadic packs
    result = check(R"(
type Table = { x: number, y: number }
function f(a: (...Table) -> number) return a({x = 1, y = 2}, {x = 3, y = 4}) end
f(function(a, ...) local b = ... return b.z end)
    )");

    LUAU_REQUIRE_ERRORS(result);
    CHECK_EQ("Key 'z' not found in table 'Table'", toString(result.errors[0]));

    // Return type inference
    result = check(R"(
type Table = { x: number, y: number }
function f(a: (number) -> Table) return a(4) end
f(function(x) return x * 2 end)
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    CHECK_EQ("Expected this to be 'Table', but got 'number'", toString(result.errors[0]));

    // Return type doesn't inference 'nil'
    result = check(R"(
        function f(a: (number) -> nil) return a(4) end
        f(function(x) print(x) end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "infer_generic_function_function_argument")
{
    // FIXME: CLI-116133 bidirectional type inference needs to push expected types in for higher-order function calls
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
local function sum<a>(x: a, y: a, f: (a, a) -> a) return f(x, y) end
return sum(2, 3, function(a, b) return a + b end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    result = check(R"(
local function map<a, b>(arr: {a}, f: (a) -> b) local r = {} for i,v in ipairs(arr) do table.insert(r, f(v)) end return r end
local a = {1, 2, 3}
local r = map(a, function(a) return a + a > 100 end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    REQUIRE_EQ("{boolean}", toString(requireType("r")));

    check(R"(
local function foldl<a, b>(arr: {a}, init: b, f: (b, a) -> b) local r = init for i,v in ipairs(arr) do r = f(r, v) end return r end
local a = {1, 2, 3}
local r = foldl(a, {s=0,c=0}, function(a, b) return {s = a.s + b, c = a.c + 1} end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    REQUIRE_EQ("{| c: number, s: number |}", toString(requireType("r")));
}

TEST_CASE_FIXTURE(Fixture, "infer_generic_function_function_argument_overloaded")
{
    // FIXME: CLI-116133 bidirectional type inference needs to push expected types in for higher-order function calls
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
local function g1<T>(a: T, f: (T) -> T) return f(a) end
local function g2<T>(a: T, b: T, f: (T, T) -> T) return f(a, b) end

local g12: typeof(g1) & typeof(g2)

g12(1, function(x) return x + x end)
g12(1, 2, function(x, y) return x + y end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    result = check(R"(
local function g1<T>(a: T, f: (T) -> T) return f(a) end
local function g2<T>(a: T, b: T, f: (T, T) -> T) return f(a, b) end

local g12: typeof(g1) & typeof(g2)

g12({x=1}, function(x) return {x=-x.x} end)
g12({x=1}, {x=2}, function(x, y) return {x=x.x + y.x} end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "infer_generic_lib_function_function_argument")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauReplacerRespectsReboundGenerics, true},
        {FFlag::LuauOverloadGetsInstantiated2, true},
    };

    CheckResult result = check(R"(
local a = {{x=4}, {x=7}, {x=1}}
table.sort(a, function(x, y) return x.x < y.x end)
    )");

    // FIXME CLI-161355
    LUAU_REQUIRE_ERROR_COUNT(1, result);
    CHECK(get<CannotInferBinaryOperation>(result.errors[0]));
}

TEST_CASE_FIXTURE(Fixture, "variadic_any_is_compatible_with_a_generic_TypePack")
{
    CheckResult result = check(R"(
        --!strict
        local function f(...) return ... end
        local g = function(...) return f(...) end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

// https://github.com/luau-lang/luau/issues/767
TEST_CASE_FIXTURE(BuiltinsFixture, "variadic_any_is_compatible_with_a_generic_TypePack_2")
{
    CheckResult result = check(R"(
        local function somethingThatsAny(...: any)
            print(...)
        end

        local function x<T...>(...: T...)
            somethingThatsAny(...) -- Failed to unify variadic type packs
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "infer_anonymous_function_arguments_outside_call")
{
    CheckResult result = check(R"(
type Table = { x: number, y: number }
local f: (Table) -> number = function(t) return t.x + t.y end

type TableWithFunc = { x: number, y: number, f: (number, number) -> number }
local a: TableWithFunc = { x = 3, y = 4, f = function(a, b) return a + b end }
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "infer_return_value_type")
{
    CheckResult result = check(R"(
local function f(): {string|number}
    return {1, "b", 3}
end

local function g(): (number, {string|number})
    return 4, {1, "b", 3}
end

local function h(): ...{string|number}
    return {4}, {1, "b", 3}, {"s"}
end

local function i(): ...{string|number}
    return {1, "b", 3}, h()
end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "error_detailed_function_mismatch_arg_count")
{
    // FIXME: CLI-116111 test disabled until type path stringification is improved
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
type A = (number, number) -> string
type B = (number) -> string

local a: A
local b: B = a
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    const std::string expected = "Expected this to be\n\t"
                                 "'(number) -> string'"
                                 "\nbut got\n\t"
                                 "'(number, number) -> string'"
                                 "\ncaused by:\n"
                                 "  Argument count mismatch. Function expects 2 arguments, but only 1 is specified";
    CHECK_EQ(expected, toString(result.errors[0]));
}

TEST_CASE_FIXTURE(Fixture, "error_detailed_function_mismatch_arg")
{
    // FIXME: CLI-116111 test disabled until type path stringification is improved
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
type A = (number, number) -> string
type B = (number, string) -> string

local a: A
local b: B = a
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    const std::string expected = "Expected this to be\n\t"
                                 "'(number, string) -> string'"
                                 "\nbut got\n\t"
                                 "'(number, number) -> string'"
                                 "\ncaused by:\n"
                                 "  Argument #2 type is not compatible.\n"
                                 "Expected this to be 'number', but got 'string'";
    CHECK_EQ(expected, toString(result.errors[0]));
}

TEST_CASE_FIXTURE(Fixture, "error_detailed_function_mismatch_ret_count")
{
    // FIXME: CLI-116111 test disabled until type path stringification is improved
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
type A = (number, number) -> (number)
type B = (number, number) -> (number, boolean)

local a: A
local b: B = a
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    const std::string expected = "Expected this to be\n\t"
                                 "'(number, number) -> (number, boolean)'"
                                 "\nbut got\n\t"
                                 "'(number, number) -> number'"
                                 "\ncaused by:\n"
                                 "  Function only returns 1 value, but 2 are required here";
    CHECK_EQ(expected, toString(result.errors[0]));
}

TEST_CASE_FIXTURE(Fixture, "error_detailed_function_mismatch_ret")
{
    // FIXME: CLI-116111 test disabled until type path stringification is improved
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
type A = (number, number) -> string
type B = (number, number) -> number

local a: A
local b: B = a
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    const std::string expected = "Expected this to be\n\t"
                                 "'(number, number) -> number'"
                                 "\nbut got\n\t"
                                 "'(number, number) -> string'"
                                 "\ncaused by:\n"
                                 "  Return type is not compatible.\n"
                                 "Expected this to be 'number', but got 'string'";
    CHECK_EQ(expected, toString(result.errors[0]));
}

TEST_CASE_FIXTURE(Fixture, "error_detailed_function_mismatch_ret_mult")
{
    // FIXME: CLI-116111 test disabled until type path stringification is improved
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
type A = (number, number) -> (number, string)
type B = (number, number) -> (number, boolean)

local a: A
local b: B = a
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    const std::string expected = "Expected this to be\n\t"
                                 "'(number, number) -> (number, boolean)'"
                                 "\nbut got\n\t"
                                 "'(number, number) -> (number, string)'"
                                 "\ncaused by:\n"
                                 "  Return #2 type is not compatible.\n"
                                 "Expected this to be 'boolean', but got 'string'";
    CHECK_EQ(expected, toString(result.errors[0]));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "function_decl_quantify_right_type")
{
    fileResolver.source["game/isAMagicMock"] = R"(
--!nonstrict
return function(value)
    return false
end
    )";

    CheckResult result = check(R"(
--!nonstrict
local MagicMock = {}
MagicMock.is = require(game.isAMagicMock)

function MagicMock.is(value)
    return false
end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "function_decl_non_self_sealed_overwrite")
{
    CheckResult result = check(R"(
        function string.len(): number
            return 1
        end

        local s = string
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    // if 'string' library property was replaced with an internal module type, it will be freed and the next check will crash
    getFrontend().clear();

    CheckResult result2 = check(R"(
        print(string.len('hello'))
    )");

    LUAU_REQUIRE_NO_ERRORS(result2);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "function_decl_non_self_sealed_overwrite_2")
{
    CheckResult result = check(R"(
local t: { f: ((x: number) -> number)? } = {}

function t.f(x)
    print(x + 5)
    return x .. "asd" -- 1st error: we know that return type is a number, not a string
end

t.f = function(x)
    print(x + 5)
    return x .. "asd" -- 2nd error: we know that return type is a number, not a string
end
    )");

    if (!FFlag::DebugLuauForceOldSolver)
    {
        LUAU_CHECK_ERROR_COUNT(2, result);
        LUAU_CHECK_ERROR(result, WhereClauseNeeded); // x2
    }
    else
    {
        LUAU_REQUIRE_ERROR_COUNT(2, result);
        CHECK_EQ(toString(result.errors[0]), R"(Expected this to be 'number', but got 'string')");
        CHECK_EQ(toString(result.errors[1]), R"(Expected this to be 'number', but got 'string')");
    }
}

TEST_CASE_FIXTURE(Fixture, "inferred_higher_order_functions_are_quantified_at_the_right_time2")
{
    CheckResult result = check(R"(
        --!strict

        local function resolveDispatcher()
            return (nil :: any) :: {useContext: (number?) -> any}
        end

        local useContext
        useContext = function(unstable_observedBits: number?)
            resolveDispatcher().useContext(unstable_observedBits)
        end
    )");

    // LUAU_REQUIRE_NO_ERRORS is particularly unhelpful when this test is broken.
    // You get a TypeMismatch error where both types stringify the same.

    CHECK(result.errors.empty());
    if (!result.errors.empty())
    {
        for (const auto& e : result.errors)
            MESSAGE(e.moduleName << " " << toString(e.location) << ": " << toString(e));
    }
}

TEST_CASE_FIXTURE(Fixture, "inferred_higher_order_functions_are_quantified_at_the_right_time3")
{
    // This test regresses in the new solver, but is sort of nonsensical insofar as `foo` is known to be `nil`, so it's "right" to not be able to call
    // it.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
        local foo

        foo():bar(function()
            return foo()
        end)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "function_decl_non_self_unsealed_overwrite")
{
    ScopedFastFlag _{FFlag::LuauCheckFunctionStatementTypes, true};

    CheckResult result = check(R"(
local t = { f = nil :: ((x: number) -> number)? }

function t.f(x: string): string -- 1st error: new function value type is incompatible
    return x .. "asd"
end

t.f = function(x)
    print(x + 5)
    return x .. "asd" -- 2nd error: we know that return type is a number, not a string
end
    )");

    if (!FFlag::DebugLuauForceOldSolver)
    {
        LUAU_CHECK_ERROR_COUNT(2, result);
        LUAU_CHECK_ERROR(result, WhereClauseNeeded);
    }
    else
    {
        LUAU_REQUIRE_ERROR_COUNT(2, result);
        CHECK_EQ(toString(result.errors[0]), R"(Expected this to be
	'((number) -> number)?'
but got
	'(string) -> string'
caused by:
  None of the union options are compatible. For example:
Expected this to be
	'(number) -> number'
but got
	'(string) -> string'
caused by:
  Argument #1 type is not compatible.
Expected this to be 'string', but got 'number')");
        CHECK_EQ(toString(result.errors[1]), R"(Expected this to be 'number', but got 'string')");
    }
}

TEST_CASE_FIXTURE(Fixture, "strict_mode_ok_with_missing_arguments")
{
    CheckResult result = check(R"(
        local function f(x: any) end
        f()
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "function_statement_sealed_table_assignment_through_indexer")
{
    // FIXME: CLI-116122 bug where `t:b` does not check against the type from the indexer annotation on `t`.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
local t: {[string]: () -> number} = {}

function t.a() return 1 end -- OK
function t:b() return 2 end -- not OK
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    CHECK_EQ(
        "Expected this to be\n\t"
        "'() -> number'"
        "\nbut got\n\t"
        "'(*error-type*) -> number'"
        "\ncaused by:\n"
        "  Argument count mismatch. Function expects 1 argument, but none are specified",
        toString(result.errors[0])
    );
}

TEST_CASE_FIXTURE(Fixture, "too_few_arguments_variadic")
{
    CheckResult result = check(R"(
    function test(a: number, b: string, ...)
    end

    test(1)
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    auto err = result.errors[0];
    auto acm = get<CountMismatch>(err);
    REQUIRE(acm);

    CHECK_EQ(2, acm->expected);
    CHECK_EQ(1, acm->actual);
    CHECK_EQ(CountMismatch::Context::Arg, acm->context);
    CHECK(acm->isVariadic);
}

TEST_CASE_FIXTURE(Fixture, "too_few_arguments_variadic_generic")
{
    // FIXME: CLI-116157 variadic and generic type packs seem to be interacting incorrectly.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
function test(a: number, b: string, ...)
    return 1
end

function wrapper<A...>(f: (A...) -> number, ...: A...)
end

wrapper(test)
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    auto err = result.errors[0];
    auto acm = get<CountMismatch>(err);
    REQUIRE(acm);

    CHECK_EQ(3, acm->expected);
    CHECK_EQ(1, acm->actual);
    CHECK_EQ(CountMismatch::Context::Arg, acm->context);
    CHECK(acm->isVariadic);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "too_few_arguments_variadic_generic2")
{
    // FIXME: CLI-116157 variadic and generic type packs seem to be interacting incorrectly.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
function test(a: number, b: string, ...)
    return 1
end

function wrapper<A...>(f: (A...) -> number, ...: A...)
end

pcall(wrapper, test)
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    auto err = result.errors[0];
    auto acm = get<CountMismatch>(err);
    REQUIRE(acm);

    CHECK_EQ(4, acm->expected);
    CHECK_EQ(2, acm->actual);
    CHECK_EQ(CountMismatch::Context::Arg, acm->context);
    CHECK(acm->isVariadic);
}

TEST_CASE_FIXTURE(Fixture, "occurs_check_failure_in_function_return_type")
{
    CheckResult result = check(R"(
        function f()
            return 5, f()
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    CHECK(nullptr != get<OccursCheckFailed>(result.errors[0]));
}

TEST_CASE_FIXTURE(Fixture, "free_is_not_bound_to_unknown")
{
    // This test only makes sense for the old solver
    if (!FFlag::DebugLuauForceOldSolver)
        return;

    CheckResult result = check(R"(
        local function foo(f: (unknown) -> (), x)
            f(x)
        end
    )");

    CHECK_EQ("<a>((unknown) -> (), a) -> ()", toString(requireType("foo")));
}

TEST_CASE_FIXTURE(Fixture, "dont_infer_parameter_types_for_functions_from_their_call_site")
{
    CheckResult result = check(R"(
        local t = {}

        function t.f(x)
            return x
        end

        t.__index = t

        function g(s)
            local q = s.p and s.p.q or nil
            return q and t.f(q) or nil
        end

        local f = t.f
    )");


    CHECK_EQ("<a>(a) -> a", toString(requireType("f")));

    if (!FFlag::DebugLuauForceOldSolver)
    {
        LUAU_CHECK_NO_ERRORS(result);
        // FIXME CLI-162439, the below fails on Linux with the flag on
        // CHECK("<a>({ read p: { read q: a } }) -> (a & ~(false?))?" == toString(requireType("g")));
    }
    else
    {
        LUAU_REQUIRE_NO_ERRORS(result);
        CHECK_EQ("({+ p: {+ q: nil +} +}) -> nil", toString(requireType("g")));
    }
}

TEST_CASE_FIXTURE(Fixture, "dont_mutate_the_underlying_head_of_typepack_when_calling_with_self")
{
    CheckResult result = check(R"(
        local t = {}
        function t:m(x) end
        function f(): never return 5 :: never end
        t:m(f())
        t:m(f())
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "improved_function_arg_mismatch_errors")
{
    CheckResult result = check(R"(
local function foo1(a: number) end
foo1()

local function foo2(a: number, b: string?) end
foo2()

local function foo3(a: number, b: string?, c: any) end -- any is optional
foo3()

string.find()

local t = {}
function t.foo(x: number, y: string?, ...: any) return 1 end
function t:bar(x: number, y: string?) end
t.foo()

t:bar()

local u = { a = t, b = function() return t end }
u.a.foo()
local x = (u.a).foo()

u.b().foo()
    )");

    LUAU_REQUIRE_ERROR_COUNT(9, result);
    if (!FFlag::DebugLuauForceOldSolver)
    {
        // These improvements to the error messages are currently regressed in the new type solver.
        CHECK_EQ(toString(result.errors[0]), "Argument count mismatch. Function expects 1 argument, but none are specified");
        CHECK_EQ(toString(result.errors[1]), "Argument count mismatch. Function expects 1 to 2 arguments, but none are specified");
        CHECK_EQ(toString(result.errors[2]), "Argument count mismatch. Function expects 1 to 3 arguments, but none are specified");
        CHECK_EQ(toString(result.errors[3]), "Argument count mismatch. Function expects 2 to 4 arguments, but none are specified");
        CHECK_EQ(toString(result.errors[4]), "Argument count mismatch. Function expects at least 1 argument, but none are specified");
        CHECK_EQ(toString(result.errors[5]), "Argument count mismatch. Function expects 2 to 3 arguments, but only 1 is specified");
        CHECK_EQ(toString(result.errors[6]), "Argument count mismatch. Function expects at least 1 argument, but none are specified");
        CHECK_EQ(toString(result.errors[7]), "Argument count mismatch. Function expects at least 1 argument, but none are specified");
        CHECK_EQ(toString(result.errors[8]), "Argument count mismatch. Function expects at least 1 argument, but none are specified");
    }
    else
    {
        CHECK_EQ(toString(result.errors[0]), "Argument count mismatch. Function 'foo1' expects 1 argument, but none are specified");
        CHECK_EQ(toString(result.errors[1]), "Argument count mismatch. Function 'foo2' expects 1 to 2 arguments, but none are specified");
        CHECK_EQ(toString(result.errors[2]), "Argument count mismatch. Function 'foo3' expects 1 to 3 arguments, but none are specified");
        CHECK_EQ(toString(result.errors[3]), "Argument count mismatch. Function 'string.find' expects 2 to 4 arguments, but none are specified");
        CHECK_EQ(toString(result.errors[4]), "Argument count mismatch. Function 't.foo' expects at least 1 argument, but none are specified");
        CHECK_EQ(toString(result.errors[5]), "Argument count mismatch. Function 't.bar' expects 2 to 3 arguments, but only 1 is specified");
        CHECK_EQ(toString(result.errors[6]), "Argument count mismatch. Function 'u.a.foo' expects at least 1 argument, but none are specified");
        CHECK_EQ(toString(result.errors[7]), "Argument count mismatch. Function 'u.a.foo' expects at least 1 argument, but none are specified");
        CHECK_EQ(toString(result.errors[8]), "Argument count mismatch. Function expects at least 1 argument, but none are specified");
    }
}

// This might be surprising, but since 'any' became optional, unannotated functions in non-strict 'expect' 0 arguments
TEST_CASE_FIXTURE(BuiltinsFixture, "improved_function_arg_mismatch_error_nonstrict")
{
    // This behavior is not part of the current specification of the new type solver.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
        --!nonstrict
        local function foo(a, b) end
        foo(string.find("hello", "e"))
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    CHECK_EQ(toString(result.errors[0]), "Argument count mismatch. Function 'foo' expects 0 to 2 arguments, but 3 are specified");
}

TEST_CASE_FIXTURE(Fixture, "luau_subtyping_is_np_hard")
{
    // The case that _should_ succeed here (`z = x`) does not currently in the new solver.
    DOES_NOT_PASS_NEW_SOLVER_GUARD();

    CheckResult result = check(R"(
--!strict

-- An example of coding up graph coloring in the Luau type system.
-- This codes a three-node, two color problem.
-- A three-node triangle is uncolorable,
-- but a three-node line is colorable.

type Red = "red"
type Blue = "blue"
type Color = Red | Blue
type Coloring = (Color) -> (Color) -> (Color) -> boolean
type Uncolorable = (Color) -> (Color) -> (Color) -> false

type Line = Coloring
  & ((Red) -> (Red) -> (Color) -> false)
  & ((Blue) -> (Blue) -> (Color) -> false)
  & ((Color) -> (Red) -> (Red) -> false)
  & ((Color) -> (Blue) -> (Blue) -> false)

type Triangle = Line
  & ((Red) -> (Color) -> (Red) -> false)
  & ((Blue) -> (Color) -> (Blue) -> false)

local x : Triangle
local y : Line
local z : Uncolorable
z = x -- OK, so the triangle is uncolorable
z = y -- Not OK, so the line is colorable
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    const std::string expected =
        "Expected this to be\n\t"
        R"('("blue" | "red") -> ("blue" | "red") -> ("blue" | "red") -> false')"
        "\nbut got\n\t"
        R"('(("blue" | "red") -> ("blue" | "red") -> ("blue" | "red") -> boolean) & (("blue" | "red") -> ("blue") -> ("blue") -> false) & (("blue" | "red") -> ("red") -> ("red") -> false) & (("blue") -> ("blue") -> ("blue" | "red") -> false) & (("red") -> ("red") -> ("blue" | "red") -> false)')"
        "; none of the intersection parts are compatible";
    CHECK_EQ(expected, toString(result.errors[0]));
}

TEST_CASE_FIXTURE(Fixture, "function_is_supertype_of_concrete_functions")
{
    registerHiddenTypes(getFrontend());

    CheckResult result = check(R"(
        function foo(f: fun) end

        function a() end
        function id(x) return x end

        foo(a)
        foo(id)
        foo(foo)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "concrete_functions_are_not_supertypes_of_function")
{
    registerHiddenTypes(getFrontend());

    CheckResult result = check(R"(
        local a: fun = function() end

        function one(arg: () -> ()) end
        function two(arg: <T>(T) -> T) end

        one(a)
        two(a)
    )");

    LUAU_REQUIRE_ERROR_COUNT(2, result);

    CHECK(6 == result.errors[0].location.begin.line);
    auto tm1 = get<TypeMismatch>(result.errors[0]);
    REQUIRE(tm1);
    CHECK("() -> ()" == toString(tm1->wantedType));
    CHECK("function" == toString(tm1->givenType));

    CHECK(7 == result.errors[1].location.begin.line);
    auto tm2 = get<TypeMismatch>(result.errors[1]);
    REQUIRE(tm2);
    CHECK("<T>(T) -> T" == toString(tm2->wantedType));
    CHECK("function" == toString(tm2->givenType));
}

TEST_CASE_FIXTURE(Fixture, "other_things_are_not_related_to_function")
{
    registerHiddenTypes(getFrontend());

    CheckResult result = check(R"(
        local a: fun = function() end
        local b: {} = a
        local c: boolean = a
        local d: fun = true
        local e: fun = {}
    )");

    LUAU_REQUIRE_ERROR_COUNT(4, result);

    CHECK(2 == result.errors[0].location.begin.line);
    CHECK(3 == result.errors[1].location.begin.line);
    CHECK(4 == result.errors[2].location.begin.line);
    CHECK(5 == result.errors[3].location.begin.line);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "fuzz_must_follow_in_overload_resolution")
{
    CheckResult result = check(R"(
for _ in function<t0>():(t0)&((()->())&(()->()))
end do
_(_(_,_,_),_)
end
    )");

    LUAU_REQUIRE_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "dont_assert_when_the_tarjan_limit_is_exceeded_during_generalization")
{
    ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false};
    ScopedFastInt sfi{FInt::LuauTarjanChildLimit, 1};

    CheckResult result = check(R"(
        function f(t)
            t.x.y.z = 441
        end
    )");

    LUAU_REQUIRE_ERROR(result, UnificationTooComplex);
}

/* We had a bug under DCR where instantiated type packs had a nullptr scope.
 *
 * This caused an issue with promotion.
 */
TEST_CASE_FIXTURE(Fixture, "instantiated_type_packs_must_have_a_non_null_scope")
{
    CheckResult result = check(R"(
        function pcall<A..., R...>(...: (A...) -> R...): (boolean, R...)
            return nil :: any
        end

        type Dispatch<A> = (A) -> ()

        function mountReducer()
            dispatchAction()
            return nil :: any
        end

        function dispatchAction()
        end

        function useReducer(): Dispatch<any>
            local result, setResult = pcall(mountReducer)
            return setResult
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "inner_frees_become_generic_in_dcr")
{
    if (FFlag::DebugLuauForceOldSolver)
        return;

    CheckResult result = check(R"(
        function f(x)
            local z = x
            return x
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    std::optional<TypeId> ty = findTypeAtPosition(Position{3, 19});
    REQUIRE(ty);
    CHECK(get<GenericType>(follow(*ty)));
}

TEST_CASE_FIXTURE(Fixture, "function_exprs_are_generalized_at_signature_scope_not_enclosing")
{
    CheckResult result = check(R"(
        local foo
        local bar

        -- foo being a function expression is deliberate: the bug we're testing
        -- only existed for function expressions, not for function statements.
        foo = function(a)
            return bar
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    if (!FFlag::DebugLuauForceOldSolver)
        CHECK(toString(requireType("foo")) == "((unknown) -> nil)?");
    else
    {
        // note that b is not in the generic list; it is free, the unconstrained type of `bar`.
        CHECK(toString(requireType("foo")) == "<a>(a) -> 'b");
    }
}

TEST_CASE_FIXTURE(BuiltinsFixture, "param_1_and_2_both_takes_the_same_generic_but_their_arguments_are_incompatible")
{
    ScopedFastFlag sff{FFlag::LuauRelateHandlesCoincidentTables, true};

    CheckResult result = check(R"(
        local function foo<a>(x: a, y: a?)
            return x
        end
        local vec2 = { x = 5, y = 7 }
        local ret: number = foo(vec2, { x = 5 })
    )");

    if (!FFlag::DebugLuauForceOldSolver)
    {
        LUAU_REQUIRE_ERROR_COUNT(1, result);

        auto tm = get<TypeMismatch>(result.errors[0]);
        REQUIRE(tm);
        CHECK("number" == toString(tm->wantedType));
        CHECK("{ x: number } | { x: number, y: number }" == toString(tm->givenType, /* exhausive */ true));
    }
    else
    {
        // In the old solver, this produces a very strange result:
        //
        //   Here, we instantiate `<a>(x: a, y: a?) -> a` with a fresh type `'a` for `a`.
        //   In argument #1, we unify `vec2` with `'a`.
        //     This is ok, so we record an equality constraint `'a` with `vec2`.
        //   In argument #2, we unify `{ x: number }` with `'a?`.
        //     This fails because `'a` has equality constraint with `vec2`,
        //     so `{ x: number } <: vec2?`, which is false.
        //
        // If the unifications were to be committed, then it'd result in the following type error:
        //
        //   Type '{ x: number }' could not be converted into 'vec2?'
        //   caused by:
        //     [...] Table type '{ x: number }' not compatible with type 'vec2' because the former is missing field 'y'
        //
        // However, whenever we check the argument list, if there's an error, we don't commit the unifications, so it actually looks like this:
        //
        //   Type '{ x: number }' could not be converted into 'a?'
        //   caused by:
        //     [...] Table type '{ x: number }' not compatible with type 'vec2' because the former is missing field 'y'
        //
        // Then finally, that generic is left floating free, and since the function returns that generic,
        // that free type is then later bound to `number`, which succeeds and mutates the type graph.
        // This again changes the type error where `a` becomes bound to `number`.
        //
        //   Type '{ x: number }' could not be converted into 'number?'
        //   caused by:
        //     [...] Table type '{ x: number }' not compatible with type 'vec2' because the former is missing field 'y'
        //
        // Uh oh, that type error is extremely confusing for people who doesn't know how that went down.
        // Really, what should happen is we roll each argument incompatibility into a union type, but that needs local type inference.

        LUAU_REQUIRE_ERROR_COUNT(2, result);

        const std::string expected = R"(Expected this to be 'vec2?', but got '{| x: number |}'
caused by:
  None of the union options are compatible. For example:
Table type '{| x: number |}' not compatible with type 'vec2' because the former is missing field 'y')";
        CHECK_EQ(expected, toString(result.errors[0]));
        CHECK_EQ("Expected this to be 'number', but got 'vec2'", toString(result.errors[1]));
    }
}

TEST_CASE_FIXTURE(BuiltinsFixture, "param_1_and_2_both_takes_the_same_generic_but_their_arguments_are_incompatible_2")
{
    CheckResult result = check(R"(
        local function f<a>(x: a, y: a): a
            return if math.random() > 0.5 then x else y
        end

        local z: boolean = f(5, "five")
    )");

    if (!FFlag::DebugLuauForceOldSolver)
    {
        LUAU_REQUIRE_ERROR_COUNT(1, result);

        auto tm = get<TypeMismatch>(result.errors[0]);
        REQUIRE(tm);
        CHECK("boolean" == toString(tm->wantedType));
        CHECK("number | string" == toString(tm->givenType));
    }
    else
    {
        LUAU_REQUIRE_ERROR_COUNT(2, result);

        CHECK_EQ(toString(result.errors[0]), "Expected this to be 'number', but got 'string'");
        CHECK_EQ(toString(result.errors[1]), "Expected this to be 'boolean', but got 'number'");
    }
}

TEST_CASE_FIXTURE(Fixture, "attempt_to_call_an_intersection_of_tables")
{
    CheckResult result = check(R"(
        local function f(t: { x: number } & { y: string })
            t()
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    if (!FFlag::DebugLuauForceOldSolver)
        CHECK_EQ(toString(result.errors[0]), "Cannot call a value of type { x: number } & { y: string }");
    else
        CHECK_EQ(toString(result.errors[0]), "Cannot call a value of type { x: number }");
}

TEST_CASE_FIXTURE(BuiltinsFixture, "attempt_to_call_an_intersection_of_tables_with_call_metamethod")
{
    CheckResult result = check(R"(
        type Callable = typeof(setmetatable({}, {
            __call = function(self, ...) return ... end
        }))

        local function f(t: Callable & { x: number })
            t()
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "generic_packs_are_not_variadic")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauReplacerRespectsReboundGenerics, true},
        {FFlag::LuauOverloadGetsInstantiated2, true},
    };

    CheckResult result = check(R"(
        local function apply<a, b..., c...>(f: (a, b...) -> c..., x: a)
            return f(x)
        end

        local function add(x: number, y: number)
            return x + y
        end

        local function addToSix(x: number)
            return x + 6
        end

        apply(addToSix, 7)
        apply(add, 5)
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    CHECK(Location{{2, 21}, {2, 22}} == result.errors.at(0).location);
    auto err = get<TypePackMismatch>(result.errors[0]);
    // FIXME: This seems incorrect?
    CHECK_EQ("a", toString(err->givenTp));
    CHECK_EQ("b...", toString(err->wantedTp));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "num_is_solved_before_num_or_str")
{
    CheckResult result = check(R"(
        function num()
            return 5
        end

        local function num_or_str()
            if math.random() > 0.5 then
                return num()
            else
                return "some string"
            end
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    CHECK_EQ("Expected this to be 'number', but got 'string'", toString(result.errors[0]));
    CHECK_EQ("() -> number", toString(requireType("num_or_str")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "num_is_solved_after_num_or_str")
{
    CheckResult result = check(R"(
        local function num_or_str()
            if math.random() > 0.5 then
                return num()
            else
                return "some string"
            end
        end

        function num()
            return 5
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    CHECK_EQ("Expected this to be 'number', but got 'string'", toString(result.errors[0]));
    CHECK_EQ("() -> number", toString(requireType("num_or_str")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "apply_of_lambda_with_inferred_and_explicit_types")
{
    CheckResult result = check(R"(
        local function apply(f, x) return f(x) end
        local x = apply(function(x: string): number return 5 end, "hello!")

        local function apply_explicit<A, B...>(f: (A) -> B..., x: A): B... return f(x) end
        local x = apply_explicit(function(x: string): number return 5 end, "hello!")
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "regex_benchmark_string_format_minimization")
{
    CheckResult result = check(R"(
        (nil :: any)(function(n)
            if tonumber(n) then
                n = tonumber(n)
            elseif n ~= nil then
                string.format("invalid argument #4 to 'sub': number expected, got %s", typeof(n))
            end
        end);
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "subgeneric_type_function_super_monomorphic")
{
    CheckResult result = check(R"(
local a: (number, number) -> number = function(a, b) return a - b end

a = function(a, b) return a + b end
)");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "simple_unannotated_mutual_recursion")
{
    // CLI-117118 - TypeInferFunctions.simple_unannotated_mutual_recursion relies on unstable assertions to pass.
    if (!FFlag::DebugLuauForceOldSolver)
        return;
    CheckResult result = check(R"(
function even(n)
    if n == 0 then
        return true
    else
        return odd(n - 1)
    end
end

function odd(n)
    if n == 0 then
        return false
    elseif n == 1 then
        return true
    else
        return even(n - 1)
    end
end
)");

    if (!FFlag::DebugLuauForceOldSolver)
    {
        LUAU_REQUIRE_ERROR_COUNT(5, result);
        // CLI-117117 Constraint solving is incomplete inTypeInferFunctions.simple_unannotated_mutual_recursion
        CHECK(get<ConstraintSolvingIncompleteError>(result.errors[0]));
        // This check is unstable between different machines and different runs of DCR because it depends on string equality between
        // blocked type numbers, which is not guaranteed.
        bool r = toString(result.errors[1]) == "Expected this to be 'boolean', but got '*blocked-tp-1*'; type *blocked-tp-1*.tail() "
                                               "(*blocked-tp-1*) is not a subtype of boolean (boolean)";
        CHECK(r);
        CHECK(
            toString(result.errors[2]) ==
            "Operator '-' could not be applied to operands of types unknown and number; there is no corresponding overload for __sub"
        );
        CHECK(
            toString(result.errors[3]) ==
            "Operator '-' could not be applied to operands of types unknown and number; there is no corresponding overload for __sub"
        );
        CHECK(
            toString(result.errors[4]) ==
            "Operator '-' could not be applied to operands of types unknown and number; there is no corresponding overload for __sub"
        );
    }
    else
    {
        LUAU_REQUIRE_ERROR_COUNT(1, result);
        CHECK(toString(result.errors[0]) == "Unknown type used in - operation; consider adding a type annotation to 'n'");
    }
}

TEST_CASE_FIXTURE(BuiltinsFixture, "simple_lightly_annotated_mutual_recursion")
{
    CheckResult result = check(R"(
function even(n: number)
    if n == 0 then
        return true
    else
        return odd(n - 1)
    end
end

function odd(n: number)
    if n == 0 then
        return false
    elseif n == 1 then
        return true
    else
        return even(n - 1)
    end
end
)");

    LUAU_REQUIRE_NO_ERRORS(result);

    CHECK_EQ("(number) -> boolean", toString(requireType("even")));
    CHECK_EQ("(number) -> boolean", toString(requireType("odd")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "tf_suggest_return_type")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
    };

    // CLI-114134: This test:
    // a) Has a kind of weird result (suggesting `number | false` is not great);
    // b) Is force solving some constraints.
    // We end up with a weird recursive type that, if you roughly look at it, is
    // clearly `number`. Hopefully the egraph will be able to unfold this.

    CheckResult result = check(R"(
        function fib(n)
            return n < 2 and 1 or fib(n-1) + fib(n-2)
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    auto err = get<ExplicitFunctionAnnotationRecommended>(result.errors.back());
    LUAU_ASSERT(err);
    CHECK("false | number" == toString(err->recommendedReturn));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "tf_suggest_arg_type")
{
    if (FFlag::DebugLuauForceOldSolver)
        return;

    CheckResult result = check(R"(
        function fib(n, u)
            return (n or u) and (n < u and n + fib(n,u))
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(2, result);
    CHECK(get<CannotInferBinaryOperation>(result.errors[0]));
    auto err2 = get<ExplicitFunctionAnnotationRecommended>(result.errors[1]);
    LUAU_ASSERT(err2);
    CHECK("number" == toString(err2->recommendedReturn));
    REQUIRE(err2->recommendedArgs.size() == 2);
    CHECK("number" == toString(err2->recommendedArgs[0].second));
    CHECK("number" == toString(err2->recommendedArgs[1].second));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "tf_suggest_arg_type_2")
{
    if (FFlag::DebugLuauForceOldSolver)
        return;

    // Make sure the error types are cloned to module interface
    getFrontend().options.retainFullTypeGraphs = false;

    CheckResult result = check(R"(
        local function escape_fslash(pre)
            return (#pre % 2 == 0 and '\\' or '') .. pre .. '.'
        end
    )");

    LUAU_REQUIRE_ERROR(result, NotATable);
}

TEST_CASE_FIXTURE(Fixture, "local_function_fwd_decl_doesnt_crash")
{
    CheckResult result = check(R"(
        local foo

        local function bar()
            foo()
        end

        function foo()
        end

        bar()
    )");

    // This test verifies that an ICE doesn't occur, so the bulk of the test is
    // just from running check above.
    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "bidirectional_checking_of_callback_property")
{
    CheckResult result = check(R"(
        function print(x: number) end

        type Point = {x: number, y: number}
        local T : {callback: ((Point) -> ())?} = {}

        T.callback = function(p) -- No error here
            print(p.z)           -- error here.  Point has no property z
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    if (!FFlag::DebugLuauForceOldSolver)
    {
        auto tm = get<TypeMismatch>(result.errors[0]);
        REQUIRE(tm);

        CHECK("((Point) -> ())?" == toString(tm->wantedType));
        CHECK("({ read z: number }) -> ()" == toString(tm->givenType));

        Location location = result.errors[0].location;
        CHECK(location.begin.line == 6);
        CHECK(location.end.line == 8);
    }
    else
    {
        CHECK_MESSAGE(get<UnknownProperty>(result.errors[0]), "Expected UnknownProperty but got " << result.errors[0]);

        Location location = result.errors[0].location;
        CHECK(location.begin.line == 7);
        CHECK(location.end.line == 7);
    }
}

TEST_CASE_FIXTURE(ExternTypeFixture, "bidirectional_inference_of_class_methods")
{
    CheckResult result = check(R"(
        local c = ChildClass.New()

        -- Instead of reporting that the lambda is the wrong type, report that we are using its argument improperly.
        c.Touched:Connect(function(other)
            print(other.ThisDoesNotExist)
        end)
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    UnknownProperty* err = get<UnknownProperty>(result.errors[0]);
    REQUIRE(err);

    CHECK("ThisDoesNotExist" == err->key);
    CHECK("BaseClass" == toString(err->table));
}

TEST_CASE_FIXTURE(Fixture, "pass_table_literal_to_function_expecting_optional_prop")
{
    CheckResult result = check(R"(
        type T = {prop: number?}

        function f(t: T) end

        f({prop=5})
        f({})
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "dont_infer_overloaded_functions")
{
    CheckResult result = check(R"(
        function getR6Attachments(model)
            model:FindFirstChild("Right Leg")
            model:FindFirstChild("Left Leg")
            model:FindFirstChild("Torso")
            model:FindFirstChild("Torso")
            model:FindFirstChild("Head")
            model:FindFirstChild("Left Arm")
            model:FindFirstChild("Right Arm")
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    if (!FFlag::DebugLuauForceOldSolver)
        CHECK("(t1) -> () where t1 = { read FindFirstChild: (t1, string) -> (...unknown) }" == toString(requireType("getR6Attachments")));
    else
        CHECK("<a...>(t1) -> () where t1 = {+ FindFirstChild: (t1, string) -> (a...) +}" == toString(requireType("getR6Attachments")));
}

TEST_CASE_FIXTURE(Fixture, "param_y_is_bounded_by_x_of_type_string")
{
    CheckResult result = check(R"(
        local function f(x: string, y)
            x = y
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    CHECK("(string, string) -> ()" == toString(requireType("f")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "function_that_could_return_anything_is_compatible_with_function_that_is_expected_to_return_nothing")
{
    CheckResult result = check(R"(
        -- We infer foo : (g: (number) -> (...unknown)) -> ()
        function foo(g)
            g(0)
        end

        -- a requires a function that returns no values
        function a(f: ((number) -> ()) -> ())
        end

        -- "Returns an unknown number of values" is close enough to "returns no values."
        a(foo)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "self_application_does_not_segfault")
{
    (void)check(R"(
        function f(a)
            f(f)
            return f(), a
        end
    )");

    // We only care that type checking completes without tripping a crash or an assertion.
}

TEST_CASE_FIXTURE(Fixture, "function_definition_in_a_do_block")
{
    CheckResult result = check(R"(
        local f
        do
            function f()
            end
        end
        f()
    )");

    // We are predominantly interested in this test not crashing.
    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "function_definition_in_a_do_block_with_global")
{
    CheckResult result = check(R"(
        function f() print("a") end
        do
            function f()
                print("b")
            end
        end
        f()
    )");

    // We are predominantly interested in this test not crashing.
    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "fuzzer_alias_global_function_doesnt_hit_nil_assert")
{
    CheckResult result = check(R"(
function _()
end
local function l0()
    function _()
    end
end
_ = _
)");
    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "fuzzer_bug_missing_follow_causes_assertion")
{
    CheckResult result = check(R"(
local _ = ({_=function()
return _
end,}),true,_[_()]
for l0=_[_[_[`{function(l0)
end}`]]],_[_.n6[_[_.n6]]],_[_[_.n6[_[_.n6]]]] do
_ += if _ then ""
end
return _
)");
}

TEST_CASE_FIXTURE(Fixture, "cannot_call_union_of_functions")
{
    CheckResult result = check(R"(
         local f: (() -> ()) | (() -> () -> ()) = nil :: any
         f()
     )");

    if (!FFlag::DebugLuauForceOldSolver)
        LUAU_REQUIRE_NO_ERRORS(result);
    else
    {
        LUAU_REQUIRE_ERROR_COUNT(1, result);
        std::string expected = R"(Cannot call a value of the union type:
  | () -> ()
  | () -> () -> ()
We are unable to determine the appropriate result type for such a call.)";
        CHECK(expected == toString(result.errors[0]));
    }
}

TEST_CASE_FIXTURE(Fixture, "fuzzer_missing_follow_in_ast_stat_fun")
{
    (void)check(R"(
        local _ = function<t0...>()
        end ~= _

        while (_) do
            _,_,_,_,_,_,_,_,_,_._,_ = nil
            function _(...):<t0...>()->()
            end
            function _<t0...>(...):any
                _ ..= ...
            end
            _,_,_,_,_,_,_,_,_,_,_ = nil
        end
    )");
}

TEST_CASE_FIXTURE(Fixture, "unifier_should_not_bind_free_types")
{
    CheckResult result = check(R"(
        function foo(player)
            local success,result = player:thing()
            if(success) then
                return "Successfully posted message.";
            elseif(not result) then
                return false;
            else
                return result;
            end
        end
    )");

    // The new solver should ideally be able to do better here, but this is no worse than the old solver.
    LUAU_REQUIRE_ERROR_COUNT(1, result);
    auto tm1 = get<TypeMismatch>(result.errors[0]);
    REQUIRE(tm1);
    CHECK(toString(tm1->wantedType) == "string");
    CHECK(toString(tm1->givenType) == "boolean");
}

TEST_CASE_FIXTURE(Fixture, "captured_local_is_assigned_a_function")
{
    CheckResult result = check(R"(
        local f

        local function g()
            f()
        end

        function f()
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "error_suppression_propagates_through_function_calls")
{
    CheckResult result = check(R"(
        function first(x: any)
            return pairs(x)(x)
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    CHECK("(any) -> (any?, any)" == toString(requireType("first")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "fuzzer_normalizer_out_of_resources")
{
    // This luau code should finish typechecking, not segfault upon dereferencing
    // the normalized type
    CheckResult result = check(R"(
 Module 'l0':
local _ = true,...,_
if ... then
while _:_(_._G) do
do end
_ = _ and _
_ = 0 and {# _,}
local _ = "CCCCCCCCCCCCCCCCCCCCCCCCCCC"
local l0 = require(module0)
end
local function l0()
end
elseif _ then
l0 = _
end
do end
while _ do
_ = if _ then _ elseif _ then _,if _ then _ else _
_ = _()
do end
do end
if _ then
end
end
_ = _,{}

    )");
}

TEST_CASE_FIXTURE(BuiltinsFixture, "overload_resolution_crash_when_argExprs_is_smaller_than_type_args")
{
    CheckResult result = check(R"(
--!strict
local parseError
type Set<T> = {[T]: any}
local function captureDependencies(
	saveToSet: Set<PubTypes.Dependency>,
	callback: (...any) -> any,
	...
)
	local data = table.pack(xpcall(callback, parseError, ...))
    end
)");
}

TEST_CASE_FIXTURE(Fixture, "unpack_depends_on_rhs_pack_to_be_fully_resolved")
{
    CheckResult result = check(R"(
--!strict
local function id(x)
    return x
end
local u,v = id(3), id(id(44))
)");

    CHECK_EQ(getBuiltins()->numberType, requireType("v"));
    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "hidden_variadics_should_not_break_subtyping")
{
    CheckResult result = check(R"(
        --!strict
        type FooType = {
            SetValue: (Value: number) -> ()
        }

        local Foo: FooType = {
            SetValue = function(Value: number)

            end
        }
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "coroutine_wrap_result_call")
{
    CheckResult result = check(R"(
        function foo(a, b)
            coroutine.wrap(a)(b)
        end
    )");

    // New solver still reports an error in this case, but the main goal of the test is to not crash
}

TEST_CASE_FIXTURE(Fixture, "recursive_function_calls_should_not_use_the_generalized_type")
{
    ScopedFastFlag crashOnForce{FFlag::DebugLuauAssertOnForcedConstraint, true};

    CheckResult result = check(R"(
        --!strict

        function random()
            return true -- chosen by fair coin toss
        end

        local f
        f = 5
        function f()
            if random() then f() end
        end
    )");

    if (!FFlag::DebugLuauForceOldSolver)
        LUAU_REQUIRE_NO_ERRORS(result);
    else
        LUAU_REQUIRE_ERRORS(result); // errors without typestate, obviously
}

TEST_CASE_FIXTURE(Fixture, "recursive_function_calls_should_not_use_the_generalized_type_2")
{
    ScopedFastFlag crashOnForce{FFlag::DebugLuauAssertOnForcedConstraint, true};

    CheckResult result = check(R"(
        --!strict

        function random()
            return true -- chosen by fair coin toss
        end

        local function f()
            if random() then f() end
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "fuzz_unwind_mutually_recursive_union_type_func")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    // Previously, this block minted a type like:
    //
    //  t2 where t1 = union<t2, t1> | union<t2, t1> | union<t2, t1> ; t2 = union<t2, t1>
    //
    // ... due to how upvalues contributed to the locally inferred types.
    CheckResult result = check(R"(
        local _ = ...
        function _()
            _ = _
        end
        _[function(...) repeat until _(_[l100]) _ = _ end] += _
    )");
    LUAU_REQUIRE_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "string_format_pack")
{
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function foo(): (string, string, string)
            return "", "", ""
        end
        print(string.format("%s %s %s", foo()))
    )"));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "string_format_pack_variadic")
{
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local foo : () -> (...string) = (nil :: any)
        print(string.format("%s %s %s", foo()))
    )"));
}

TEST_CASE_FIXTURE(Fixture, "table_annotated_explicit_self")
{
    ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false};

    CheckResult results = check(R"(
        type MyObject = {
            fn: (self: MyObject) -> number,
            field: number
        }

        local Foo = {} :: MyObject

        function Foo:fn()
            local _ = self
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, results);
    LUAU_REQUIRE_ERROR(results, FunctionExitsWithoutReturning); // `Foo:fn` should return a `number`
    CHECK_EQ("MyObject", toString(requireTypeAtPosition({9, 24})));
}


TEST_CASE_FIXTURE(Fixture, "oss_1871")
{
    ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false};

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        export type Test = {
            [string]: (string) -> ()
        }

        local TestTbl: Test = {}

        function TestTbl.Hello(Param)
            local _ = Param
        end
    )"));

    CHECK_EQ("string", toString(requireTypeAtPosition({8, 25})));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "io_manager_oop_ish")
{
    ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false};

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        type IIOManager = {
            __index: IIOManager,
            write: (self: IOManager, text: string, label: string?) -> number,
        }

        export type IOManager = setmetatable<{
            buffer: {string},
            memory: { [string]: number }
        }, IIOManager>;

        local IO = {} :: IIOManager
        IO.__index = IO

        function IO:write(text, label)
            local _ = self
            local _ = text
            local _ = label
            return 42
        end

        return IO
    )"));
    CHECK_EQ("IOManager", toString(requireTypeAtPosition({15, 25})));
    CHECK_EQ("string", toString(requireTypeAtPosition({16, 25})));
    CHECK_EQ("string?", toString(requireTypeAtPosition({17, 25})));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "generic_function_statement")
{
    ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false};

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        type Object = {
            foobar: <T>(number, string, T) -> T
        }

        local Obj = {} :: Object
        function Obj.foobar(bing, quxx, dunno)
            local _ = bing
            local _ = quxx
            return dunno
        end
    )"));

    CHECK_EQ("number", toString(requireTypeAtPosition({7, 24})));
    CHECK_EQ("string", toString(requireTypeAtPosition({8, 24})));
    // NOTE: This specifically _isn't_ `T` as defined by `Object.foobar`
    CHECK_EQ("a", toString(requireTypeAtPosition({9, 21})));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "function_calls_should_not_crash")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
    };

    CheckResult result = check(R"(
        return {
            StartAPI = function()
                local pointers = {}
                local API = {}
                local function getRealEnvResult(PointerOrPath)
                    if pointers[PointerOrPath] then
                        return pointers[PointerOrPath]
                    end
                end
                API.OnInvoke = function()
                    local realEnvResult, isResultPointer = getRealEnvResult(FunctionInEnvToRunPath)
                    return realEnvResult(table.unpack(args, 2, args.n))
                    if TableInEnvPath and type(TableInEnvPath) == 'string' then
                        local realEnvResult, isResultPointer = getRealEnvResult(TableInEnvPath)
                        return getmetatable(realEnvResult)
                    end
                    local realEnvResult, isResultPointer = getRealEnvResult(TableInEnvPath)
                    local metaTableInEnv = getmetatable(realEnvResult)
                    local result = metaTableInEnv[FuncToRun](realEnvResult,table.unpack(args, 3, args.n))
                end
            end
        }
    )");

    // no expected behavior here beyond not crashing
}


TEST_CASE_FIXTURE(BuiltinsFixture, "unnecessary_nil_in_lower_bound_of_generic")
{
    CheckResult result = check(
        Mode::Nonstrict,
        R"(
        function isAnArray(value)
            if type(value) == "table" then
                for index, _ in next, value do
                    -- assert index is not nil
                    math.max(0, index)
                end
                return true
            else
                return false
            end
        end
)"
    );

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "call_function_with_nothing_but_nil")
{
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function f(n: number, x: string?, y: string?, z: string?) end

        local function g(n)
            f(n)
        end
    )"));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "oss_1640")
{
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        --!strict
        table.create(1) -- top function call

        local function f(): string
            if true then
                table.create(1) -- middle function call
            end

            return table.concat({})
        end
    )"));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "oss_1854")
{
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        --!strict
        local function bug()
            local counter = 1
            local work = buffer.create(64)
            local function get_block()
                buffer.writeu32(work, 48, counter)
                counter = (counter + 1) % 0x100000000
                return work
            end
        end
    )"));
}

TEST_CASE_FIXTURE(Fixture, "cli_119545_pass_lambda_inside_table")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        --!strict
        type foo1 = { foo: (number) -> () }
        type foo2 = { read foo: (number) -> () }
        local function bar1(foo: foo1) end
        local function bar2(foo: foo2) end

        local baz = { foo = function(number: number) end, }
        bar1(baz)
        bar2(baz)
    )"));
}

TEST_CASE_FIXTURE(Fixture, "oss_2065_bidirectional_inference_function_call")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
    };

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function foo(callback: () -> (() -> ())?)
        end

        local someCondition: boolean = true

        foo(function()
            if someCondition then
                return nil
            end
            return function() end
        end)
    )"));
}

TEST_CASE_FIXTURE(Fixture, "bidirectionally_infer_lambda_with_partially_resolved_generic")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
    };

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function foo<T>(value: T)
            return function<R>(callback: (T) -> R)
            end
        end

        foo(3)(function (data)
            local _ = data
            return 42
        end)
    )"));

    CHECK_EQ("number", toString(requireTypeAtPosition({7, 23})));
}

TEST_CASE_FIXTURE(Fixture, "bidirectional_inference_goes_through_ifelse")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
    };

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        type Input = "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
        local function getInputs(isDragonPunch: boolean): { Input }
            return if isDragonPunch then { "6", "8", "7" } else { "8", "7", "6" }
        end
    )"));
}

TEST_CASE_FIXTURE(Fixture, "overload_one_ok_one_potential")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    auto result = check(R"(
        local f: ((number) -> "one") & ((string) -> "two")

        local g = f(42)
        local h = f("huh")
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    CHECK_EQ("\"one\"", toString(requireType("g")));
    CHECK_EQ("\"two\"", toString(requireType("h")));
}

TEST_CASE_FIXTURE(Fixture, "overload_selection_ambiguous_call")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    auto result = check(R"(
        local f: ((number | string) -> "one") & ((number | boolean) -> "two")
        local g = f(42)
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    auto err = get<AmbiguousFunctionCall>(result.errors[0]);
    REQUIRE(err);
    CHECK_EQ("number", toString(err->arguments));
    CHECK_EQ("((boolean | number) -> \"two\") & ((number | string) -> \"one\")", toString(err->function));
    // FIXME CLI-180645: This probably ought to be `"one" | "two"`
    CHECK_EQ("*error-type*", toString(requireType("g")));
}

TEST_CASE_FIXTURE(Fixture, "overload_selection_pick_better_arity")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    auto result = check(R"(
        local f: ((number) -> "one") & ((number, number) -> "two")
        -- Casting here so that we always hit the case in overload selection
        -- where one part has the correct arity but incorrect argument types,
        -- and the other has the incorrect arity.
        local g = f("s" :: string)
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    auto err = get<TypeMismatch>(result.errors[0]);
    REQUIRE(err);
    CHECK_EQ("number", toString(err->wantedType));
    CHECK_EQ("string", toString(err->givenType));
    CHECK_EQ("\"one\"", toString(requireType("g")));
}

TEST_CASE_FIXTURE(Fixture, "overload_selection_no_compatible_option")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    auto result = check(R"(
        local f: ((number) -> "one") & ((boolean) -> "two")
        local g = f("s" :: string)
    )");

    LUAU_REQUIRE_ERROR_COUNT(2, result);
    // FIXME CLI-180645: This probably ought to be `"one" | "two"`
    CHECK_EQ("*error-type*", toString(requireType("g")));
}

TEST_CASE_FIXTURE(Fixture, "overload_selection_bad_arity")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    auto result = check(R"(
        local function foo<T>(f: ((number, number) -> "one") & T)
            local huh = f(42)
            local _ = huh
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);

    // FIXME CLI-180638: This ought to be "one."
    //
    // We should be able to select the only callable overload here, but when
    // we do, for some reason, we then consider the inferred overload to be
    // a subtype of the available overloads, and select a nonsense overload
    // like `(number) -> "one"`. That being said, prior to the new overload
    // resolver in the new solver, we didn't error on the above code at all.
    CHECK_EQ("*error-type*", toString(requireTypeAtPosition({3, 23})));
}

TEST_CASE_FIXTURE(Fixture, "overload_selection_union_of_functions")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    auto result = check(R"(
        local function foo(f: (() -> (number)) | (() -> (string)))
            return f()
        end

        local g = foo(nil :: any)
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    // FIXME CLI-180824
    //
    // This was the case prior to the new overload resolver, unfortunately,
    // but we should claim that calling a union of functions returns a
    // union of its type packs. At best we'll probably end up doing a pairwise
    // union, which should be sound but not complete.
    CHECK_EQ("number", toString(requireType("g")));
}

TEST_CASE_FIXTURE(Fixture, "overload_selection_needs_to_retry")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    auto results = check(R"(
        type RGB = { r: number, b: number, g: number }
        local BrickColor: ((number) -> RGB) & ((number, number, number) -> RGB) & ((string) -> RGB)
        function Lightning(li, Color)
            li.BrickColor = BrickColor(Color)
        end
    )");

    // FIXME: We do something reasonable and pick the first overload, but this
    // could be undesirable if, say, there's a later constraint that tells us that
    // `Color` in `Lightning` is a `string`.
    LUAU_REQUIRE_NO_ERRORS(results);
    CHECK_EQ("({ BrickColor: RGB }, number) -> ()", toString(requireType("Lightning")));
}

TEST_CASE_FIXTURE(Fixture, "overload_selection_unambiguous_with_constraint")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local f: ((string, number) -> string) & ((number, boolean) -> number)
        local function g(x)
            -- When selecting an overload at this point, we'll reject the
            -- second overload, and claim that this is the only possible
            -- overload with a constraint of `x <: string`.
            f(x, 42)
        end
    )"));

    CHECK_EQ("(string) -> ()", toString(requireType("g")));
}

TEST_CASE_FIXTURE(Fixture, "oss_2118")
{
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local foo: <P>(constructor: (P) -> any) -> (P) -> any = (nil :: any)
        local fn = foo(function (value: { test: true })
            return value.test
        end)
    )"));

    CHECK_EQ("({ test: true }) -> any", toString(requireType("fn")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2125")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        export type function CombineTableAndSetIndexer(a: type, b: type, c: type)
            local t = {}

            for key, value in a:properties() do
                t[key] = value.read
            end

            if b.tag == "table" then
                for key, value in b:properties() do
                    t[key] = value.read
                end
            end

            return types.newtable(t :: any, { index = types.number, readresult = c, writeresult = c })
        end

        type SpecialProperties = {
            test: string?,
        }

        local function component<Properties>(
            constructor: (props: Properties) -> ()
        ): (
            CombineTableAndSetIndexer<SpecialProperties, Properties, any>
        ) -> ()
            return function(props: Properties) end
        end

        local mrrp = component(function(thing: {
            meow: number,
        }) end)

        mrrp({
            meow = 5,
        })
    )"));
}

TEST_CASE_FIXTURE(Fixture, "function_argument_error_suppression")
{
    ScopedFastFlag sff[]{
        {FFlag::DebugLuauForceOldSolver, false},
    };

    CheckResult result = check(R"(
        local functions: {[any]: (any) -> ()} = {}
        functions.func1 = function(value: string) end
        functions.func2 = function(value: boolean) end
        functions.func3 = function(value: number) end
        functions.func4 = function(value: any) end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "bidirectional_lambda_inference_applies_nilable_functions")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
    };

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local listdir: (string, ((string) -> boolean)?) -> { string } = nil :: any
        listdir("my_directory", function (path)
            print(path)
            return true
        end)
    )"));

    CHECK_EQ("string", toString(requireTypeAtPosition({3, 19})));
}

TEST_CASE_FIXTURE(Fixture, "function_statement_with_incorrect_function_type")
{
    ScopedFastFlag _{FFlag::LuauCheckFunctionStatementTypes, true};

    CheckResult result = check(R"(
        local Library: { isnan: (number) -> number } = {} :: any

        function Library.isnan(s: string): boolean
            return s == "NaN"
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    auto err = get<TypeMismatch>(result.errors[0]);
    REQUIRE(err);
    CHECK_EQ("(number) -> number", toString(err->wantedType));
    CHECK_EQ("(string) -> boolean", toString(err->givenType));
}

TEST_CASE_FIXTURE(Fixture, "bidirectional_inference_allow_internal_generics")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
    };

    CheckResult result = check(R"(
        type testsuite = { case: (self: testsuite, <T>(T) -> T) -> () }

        local test1: { suite: (string, (testsuite) -> ()) -> () } = nil :: any

        test1.suite("LuteTestCommand", function(suite)
            suite:case(42)
        end)
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    auto err = get<TypeMismatch>(result.errors[0]);
    CHECK_EQ("<T>(T) -> T", toString(err->wantedType));
    CHECK_EQ("number", toString(err->givenType));
}

TEST_CASE_FIXTURE(Fixture, "oss_2143")
{
    CheckResult result = check(R"(
        local function call<A..., R...>(c: (A...) -> R..., ...: A...): R...
            return c(...)
        end

        local function fn(a: number): { number }
            return nil :: any
        end

        local function fn2<T>(b: { T }, x: (T) -> ())
            return b
        end

        local values = call(fn, 2)

        fn2(values, function(x: number)
        end)

        local a = values[1]
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(Fixture, "apply_example_from_oss")
{
    CheckResult result = check(R"(
        type something = { Something: number }
        type example = { Example: number }
        local function test(a: something): example
            return nil :: any
        end
        local function apply<T..., U...>(func: (T...) -> U..., ...: T...): (boolean, U...)
            return nil :: any
        end
        local b, result = apply(test, {
            Something = 1
        })
    )");

    LUAU_REQUIRE_NO_ERRORS(result);

    CHECK("{ Example: number }" == toString(requireType("result"), {true}));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2109")
{
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function Retry<T..., K...>(
            MaxRetries: number,
            RetryInterval: number,
            Function: (T...) -> (K...),
            ...: T...
        ): K...
            local Results
            local CurrentRetry = 0

            repeat
                Results = {pcall(Function, ...)}

                if not Results[1] then
                    CurrentRetry += 1
                end
            until Results[1] or CurrentRetry == MaxRetries

            return unpack(Results :: any, 2)
        end

        local function Test(a: number, b: number): number
            return a + b
        end

        local a = Retry(5, 1, Test, 5, 10)
    )"));
    CHECK_EQ("number", toString(requireType("a")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "pcall_example")
{
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function makestr(n: number): string
            return tostring(n)
        end

        -- `s` now has type `string` and not `unknown`
        local success, s = pcall(makestr, 42)
    )"));

    CHECK_EQ("string", toString(requireType("s")));
}

TEST_CASE_FIXTURE(ExternTypeFixture, "bidirectional_function_statement_inference_with_extern")
{
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        type HasClass = { f: (ClassWithGenericMethod) -> () }
        local t = {} :: HasClass
        function t.f(cls)
            local _ = cls
            local foobar = cls.identity(42)
            local _ = foobar
        end
    )"));

    CHECK_EQ("ClassWithGenericMethod", toString(requireTypeAtPosition({4, 23})));
    CHECK_EQ("number", toString(requireTypeAtPosition({6, 23})));
}


TEST_CASE_FIXTURE(Fixture, "table_containing_factorial_standalone")
{
    ScopedFastFlag sffs[] = {
        {FFlag::LuauCaptureRecursiveCallsForTablesAndGlobals2, true},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
    };

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local coolmath = {}
        function coolmath.factorial(n: number)
            if n <= 1 then
                return 1
            end
            return coolmath.factorial(n - 1) * n
        end
    )"));
}

TEST_CASE_FIXTURE(Fixture, "table_containing_factorial_assign_later")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauCaptureRecursiveCallsForTablesAndGlobals2, true},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
    };

    CheckResult results = check(R"(
        local coolmath = {}
        function coolmath.factorial(n: number)
            if n <= 1 then
                return 1
            end
            return coolmath.factorial(n - 1) * n
        end

        coolmath.factorial = function (s: string) end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, results);
    auto err = get<TypeMismatch>(results.errors[0]);
    CHECK_EQ("(number) -> number", toString(err->wantedType));
    CHECK_EQ("(string) -> ()", toString(err->givenType));
}

TEST_CASE_FIXTURE(Fixture, "table_containing_factorial_assign_with_correct_typing")
{
    ScopedFastFlag sffs[] = {
        {FFlag::LuauCaptureRecursiveCallsForTablesAndGlobals2, true},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
    };

    CheckResult results = check(R"(
        local coolmath = {}
        function coolmath.factorial(n: number)
            if n <= 1 then
                return 1
            end
            return coolmath.factorial(n - 1) * n
        end

        coolmath.factorial = function (n: number) return n end
        coolmath.factorial = "not a function"
    )");

    // In the future, we should consider disallowing assignment to
    // table members that were initialized as function statements.
    // But for now, we allow assignment as long as the type of the
    // RHS is compatible.
    LUAU_REQUIRE_ERROR_COUNT(1, results);
    auto err = get<TypeMismatch>(results.errors[0]);
    REQUIRE(err);
    CHECK_EQ("(number) -> number", toString(err->wantedType));
    CHECK_EQ("string", toString(err->givenType));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "recursive_static_method_must_refer_to_the_ungeneralized_type")
{
    ScopedFastFlag _{FFlag::LuauCaptureRecursiveCallsForTablesAndGlobals2, true};

    CheckResult result = check(R"(
        local lexer = {}
        local subContent: string = ""
        function lexer.scan(s: string)
            for innerToken, innerContent in lexer.scan(subContent) do
                table.insert(innerToken, innerContent)
            end
            return {}, nil, nil
        end
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2216_recursive_global_function_works_as_expected")
{
    ScopedFastFlag sffs[] = {
        {FFlag::LuauCaptureRecursiveCallsForTablesAndGlobals2, true},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
    };

    CheckResult result = check(R"(
        type tb_any = {[any]:any}
        function flatten(... : tb_any) : tb_any
            local out = {}
            local par = {...}
            for i = 1,#par do
                if par[i] and typeof(par[i]) == "table" then
                    for n,v in par[i] do
                        if typeof(n) == "number" then
                            for m,u in flatten(v) do
                                out[m] = u -- type error
                            end
                        else
                            out[n] = v
                        end
                    end
                end
            end
            return out
        end
    )");

    // Previously this failed to even solve constraints!
    LUAU_REQUIRE_NO_ERRORS(result);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "cli_187542_recursive_call_in_loop")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauCaptureRecursiveCallsForTablesAndGlobals2, true},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
    };

    CheckResult result = check(R"(
        function a(b)
            if true then return b end
            while false do
                b = a(b)
            end

            if true then return b end
        end
    )");

    // This will have some other errors, but all we care about is that
    // this finished solving all constraints without forcing any.
    // FIXME CLI-188000: We infer `a: (never) -> never`, which is incorrect.
    LUAU_REQUIRE_ERROR_COUNT(4, result);
    LUAU_REQUIRE_NO_ERROR(result, ConstraintSolvingIncompleteError);
}

TEST_CASE_FIXTURE(Fixture, "global_function_redefinition")
{
    ScopedFastFlag sffs[] = {{FFlag::LuauCaptureRecursiveCallsForTablesAndGlobals2, true}, {FFlag::DebugLuauAssertOnForcedConstraint, true}};

    CheckResult result = check(R"(
        function fact(n: number)
            return if n < 1 then 1 else n * fact(n - 1)
        end

        fact = "huh"
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, result);
    auto err = get<TypeMismatch>(result.errors[0]);
    CHECK_EQ("(number) -> number", toString(err->wantedType));
    CHECK_EQ("string", toString(err->givenType));
}

TEST_CASE_FIXTURE(Fixture, "oss_2061_modify_visited_generic_ice")
{
    ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false};

    CheckResult results = check(R"(
type actions<T=unknown, A...=...unknown> = { [string]: (state: T, A...) -> (T) }
type disconnect = () -> ()

type producer<state, actions = actions> = {
	get:
		& (() -> state)
		& (<T>(selector: (state) -> T) -> T),
} & actions

type interface = {
	create: <state>(default: state) -> <actions>(actions: actions) -> producer<state, actions>,
}

local a: interface
a.create()
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, results);
    CHECK(get<CountMismatch>(results.errors[0]));
}

TEST_CASE_FIXTURE(Fixture, "unify_type_pack_stack_overflow")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
    };

    CheckResult results = check(R"(
        local function a(): ...string
            return "hello", "world"
        end

        local function g<T...>()
            local function f(... : T...)
            end
            f("what", "is", "going", a())
        end
    )");

    LUAU_REQUIRE_ERROR_COUNT(1, results);
    auto err = get<TypePackMismatch>(results.errors[0]);
    REQUIRE(err);
    CHECK_EQ("T...", toString(err->wantedTp));
    CHECK_EQ("string, string, string, ...string", toString(err->givenTp));
}

TEST_CASE_FIXTURE(Fixture, "global_function_blocked")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::DebugLuauAssertOnForcedConstraint, true},
        {FFlag::LuauCaptureRecursiveCallsForTablesAndGlobals2, true}
    };
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        --!strict
        local addInstanceToState: any = nil
        local inst: any = nil

        function ingestAllInstances(...): ()
            local id: number = addInstanceToState()
            local child: any = nil
            ingestAllInstances(child)
        end

        function handleDmQuery()
            ingestAllInstances()
        end

        return {}

    )"));
}

TEST_CASE_FIXTURE(Fixture, "generic_polarity_of_annotated_code")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauForwardPolarityForFunctionTypes, true},
    };
    // This test is _just_ for checking the polarity of the generic in the
    // annotation.
    check(R"(
        local f: <T>(T) -> T = nil :: any
    )");

    auto ftv = get<FunctionType>(requireType("f"));
    LUAU_ASSERT(ftv);
    auto gen = get<GenericType>(ftv->generics.at(0));
    LUAU_ASSERT(gen && gen->polarity == Polarity::Mixed);
}

TEST_CASE_FIXTURE(BuiltinsFixture, "lute_tasklib_createtask")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauOverloadGetsInstantiated2, true},
        {FFlag::LuauReplacerRespectsReboundGenerics, true},
    };

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function createtask(f, ...)
            local data = {}

            data.co = coroutine.create(function(...)
                local success, result = pcall(f, ...)

                data.success = success
                data.result = result
            end)

            coroutine.resume(data.co, ...)
            return data
        end
    )"));

    // FIXME CLI-192091: This is wrong but it's less wrong than before where we
    // just leaked the generics entirely.
    CHECK_EQ("((...any) -> (unknown, ...unknown), ...any) -> { co: thread, result: unknown, success: boolean }", toString(requireType("createtask")));
}

TEST_CASE_FIXTURE(Fixture, "global_emplacing_steals_type_from_elsewhere")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauKeepExplicitMapForGlobalTypes2, true},
    };

    CheckResult result = check(R"(
        local function f()
            return 42
        end
        local a = f()
        b = a
        local c = b
        function b()
        end
    )");

    CHECK_EQ("number", toString(requireType("a")));
    CHECK_EQ("() -> ()", toString(requireType("b")));
    CHECK_EQ("number", toString(requireType("c")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "are_we_in_the_new_solver")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauReplacerRespectsReboundGenerics, true},
        {FFlag::LuauOverloadGetsInstantiated2, true},
    };

    CheckResult result = check(R"(
        -- This file should fail the old solver
        function add(a, b)
            return a + b
        end
        local vec2 = {}
        function vec2.new(x, y)
            return setmetatable({ x = x or 0, y = y or 0 }, {
                __add = function(v1, v2)
                    return { x = v1.x + v2.x, y = v1.y + v2.y }
                end,
            })
        end
        local a = add(1, 1)
        local b = add(vec2.new(0, 0), vec2.new(1, 1))
    )");

    LUAU_REQUIRE_NO_ERRORS(result);
    CHECK_EQ("number", toString(requireType("a")));
    CHECK_EQ("{ x: number, y: number }", toString(requireType("b")));
}

TEST_CASE_FIXTURE(BuiltinsFixture, "dont_leak_generics_keyof")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauReplacerRespectsReboundGenerics, true},
        {FFlag::LuauOverloadGetsInstantiated2, true},
    };

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function makeOtherThing(template)
            return {
                Stuff = template
            }
        end

        local function makeThing(tbl)
            local returnThis = { Input = makeOtherThing(tbl) }

            function returnThis.Test(key: keyof<typeof(returnThis.Input.Stuff)>) end

            return returnThis
        end

        local thing = makeThing({a=1})
        thing.Test("a")

        local otherthing = makeThing({b = 42, c = 13})
        otherthing.Test("b")
        otherthing.Test("c")
    )"));

    CHECK_EQ("{ Input: { Stuff: { a: number } }, Test: (\"a\") -> () }", toString(requireType("thing")));
    CHECK_EQ("{ Input: { Stuff: { b: number, c: number } }, Test: (\"b\" | \"c\") -> () }", toString(requireType("otherthing")));
}

TEST_CASE_FIXTURE(Fixture, "bidi_inference_functions_complete_ex")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauBidirectionalInferenceBetterUnionHandling, true},
        {FFlag::LuauExplicitTypeInstantiationSupport, true},
    };

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        --!strict
        type Player = {}

        export type RemoteEventWrapper<T...> = {
            connect:( self: RemoteEventWrapper<T...>, callback: ((T...) -> ()) | ((player: Player, T...) -> ()) ) -> () -> (),
        }

        local function useRemoteEvent<T...>(remoteEventName: string, isUnreliable: boolean?): RemoteEventWrapper<T...>
            return nil :: any
        end

        type Payload = {
            name: string,
            time: number,
            data: { [string]: any },
        }

        local payload = useRemoteEvent<<(Payload)>>("initial-payload")

        -- We expect bidirectional inference to kick in here and ensure that
        -- player and payload have non-unknown types.
        payload:connect(function(player, payload)
            local _ = player
            local _ = payload
        end)

        return useRemoteEvent
    )"));

    CHECK_EQ("Player", toString(requireTypeAtPosition({23, 23})));
    CHECK_EQ("Payload", toString(requireTypeAtPosition({24, 23})));
}

// FIXME: CLI-201899: These examples could be more concise.

TEST_CASE_FIXTURE(Fixture, "bidi_inference_union_of_functions_1")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauBidirectionalInferenceBetterUnionHandling, true},
    };

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function f(_: ((string) -> ()) | ((number, number) -> ()))
        end

        f(function (one, two)
            local _ = one
            local _ = two
        end)
    )"));

    CHECK_EQ("number", toString(requireTypeAtPosition({5, 23})));
    CHECK_EQ("number", toString(requireTypeAtPosition({6, 23})));
}

TEST_CASE_FIXTURE(Fixture, "bidi_inference_union_of_functions_2")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauBidirectionalInferenceBetterUnionHandling, true},
    };

    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function f(_: ((string) -> ()) | ((number, number) -> ()))
        end

        f(function (one)
            local _ = one
        end)
    )"));

    CHECK_EQ("string", toString(requireTypeAtPosition({5, 23})));
}

TEST_CASE_FIXTURE(Fixture, "bidi_inference_union_of_functions_3")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauBidirectionalInferenceBetterUnionHandling, true},
    };

    // Weird edge case: pick the "first" option.
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function f(_: ((string) -> ()) | ((number) -> ()))
        end

        f(function (one)
            local _ = one
        end)
    )"));

    CHECK_EQ("string", toString(requireTypeAtPosition({5, 23})));
}


TEST_CASE_FIXTURE(Fixture, "bidi_inference_union_of_functions_4")
{
    ScopedFastFlag sffs[] = {
        {FFlag::DebugLuauForceOldSolver, false},
        {FFlag::LuauBidirectionalInferenceBetterUnionHandling, true},
    };

    // Works with `nil`.
    LUAU_REQUIRE_NO_ERRORS(check(R"(
        local function f(_: ((string) -> ())?)
        end

        f(function (one)
            local _ = one
        end)
    )"));

    CHECK_EQ("string", toString(requireTypeAtPosition({5, 23})));
}


TEST_SUITE_END();