rbx-rsml 1.0.1

A lexer and parser for the RSML language.
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
use std::{
    collections::{HashMap, HashSet},
    ops::{Deref, DerefMut, RangeInclusive},
    path::{Path, PathBuf},
};

use crate::{
    datatype::{Datatype, StaticLookup, evaluate_construct, shorthand_rebind},
    lexer::Token,
    parser::{AstErrors, Construct, Delimited, Node, ParsedRsml},
    range_from_span::RangeFromSpan,
    types::{Diagnostic, Range},
};

use self::luaurc::Luaurc;
use crate::types::LanguageMode;
pub use macro_check::{
    MacroDefinition, MacroKey, MacroRegistry, MacroReturnContext, collect_macro_def_arg_names,
    macro_return_context,
};

use rangemap::RangeInclusiveMap;

mod annotations;
mod derive;
pub mod luaurc;
mod macro_check;
pub(crate) mod multibimap;
pub(crate) mod normalize_path;
mod properties;
mod selectors;
mod tween;
mod type_error;

pub use type_error::*;

pub trait ReportTypeError {
    fn report(&mut self, error: TypeError, range: Range);
}

impl ReportTypeError for AstErrors {
    fn report(&mut self, error: TypeError, range: Range) {
        self.0.push(Diagnostic {
            range,
            severity: error.severity(),
            code: error.to_string(),
            message: error.message(),
            data: error.data(),
        });
    }
}

pub struct Definitions(RangeInclusiveMap<usize, DefinitionKind>);

impl Definitions {
    pub fn new() -> Self {
        Self(RangeInclusiveMap::new())
    }
}

impl Deref for Definitions {
    type Target = RangeInclusiveMap<usize, DefinitionKind>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Definitions {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(PartialEq, Eq, Clone)]
pub enum DefinitionKind {
    Derive {
        path: PathBuf,
    },
    Selector {
        type_definition: Vec<String>,
        hint: String,
    },
    Scope {
        type_definition: Vec<String>,
    },
    Assignment {
        property_name: String,
        type_definition: Vec<String>,
    },
    EnumName,
    EnumVariant {
        enum_name: String,
    },
    Declaration,
    FilteredEnumName {
        enum_name: String,
    },
    Token {
        name: String,
        is_static: bool,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ResolvedTypeKey {
    Token { name: String, is_static: bool },
    Property { start: usize },
}

pub type ResolvedTypes = HashMap<ResolvedTypeKey, Datatype>;

#[derive(Clone, Copy)]
enum LhsKind<'a> {
    Token { name: &'a str, is_static: bool },
    Property { name: &'a str },
}

impl<'a> LhsKind<'a> {
    fn name(&self) -> &'a str {
        match *self {
            LhsKind::Token { name, .. } | LhsKind::Property { name } => name,
        }
    }
}

/// Tokens like `StateSelectorOrEnumPart` and `TagSelectorOrEnumPart` span the
/// leading `:` or `.` sigil alongside the identifier. Diagnostics that point
/// at just the name should skip that single byte prefix.
fn strip_sigil_span(span: (usize, usize)) -> (usize, usize) {
    let (start, end) = span;
    (start.saturating_add(1).min(end), end)
}

impl DefinitionKind {
    fn selector_hint(classes: &Vec<String>) -> String {
        classes.join(" | ")
    }

    pub fn selector(type_definition: Vec<String>) -> Self {
        let hint = Self::selector_hint(&type_definition);
        Self::Selector {
            type_definition,
            hint,
        }
    }
}

pub struct TypecheckedRsml {
    pub errors: AstErrors,
    pub derives: HashMap<PathBuf, RangeInclusive<usize>>,
    pub dependencies: HashSet<PathBuf>,
    pub definitions: Definitions,
    pub resolved_types: ResolvedTypes,
}

pub struct Typechecker<'a> {
    pub parsed: &'a ParsedRsml<'a>,
    macro_registry: MacroRegistry<'a>,
    pub(crate) static_scopes: Vec<HashMap<String, Datatype>>,
    pub(crate) declared_tokens: Vec<HashSet<ResolvedTypeKey>>,
    pub(crate) language_mode: LanguageMode,
}

pub(crate) struct TypecheckerLookup<'a> {
    pub scopes: &'a [HashMap<String, Datatype>],
}

impl<'a> StaticLookup for TypecheckerLookup<'a> {
    fn resolve_static(&self, name: &str) -> Datatype {
        for scope in self.scopes.iter().rev() {
            if let Some(dt) = scope.get(name) {
                return dt.clone();
            }
        }
        Datatype::None
    }

    fn resolve_dynamic(&self, _name: &str) -> Datatype {
        Datatype::None
    }
}

impl<'a> Typechecker<'a> {
    pub async fn new(
        parsed: &'a ParsedRsml<'a>,
        current_path: &Path,
        mut luaurc: Option<&mut Luaurc>,
    ) -> TypecheckedRsml {
        let language_mode = parsed.directives.language_mode.unwrap_or_else(|| {
            luaurc
                .as_deref()
                .map(|luaurc_ref| luaurc_ref.language_mode)
                .unwrap_or_default()
        });

        let mut typechecker: Typechecker<'a> = Self {
            parsed,
            macro_registry: MacroRegistry::new(),
            static_scopes: vec![HashMap::new()],
            declared_tokens: vec![HashSet::new()],
            language_mode,
        };

        // A separate `AstErrors` is needed because the shared one would conflict
        // with borrows of `self` taken further down.
        let mut ast_errors = AstErrors::new();

        let mut derives: HashMap<PathBuf, RangeInclusive<usize>> = HashMap::new();
        let mut definitions = Definitions::new();
        let mut resolved_types: ResolvedTypes = HashMap::new();
        let mut dependencies = HashSet::new();

        for construct in &typechecker.parsed.ast {
            match construct {
                Construct::Derive {
                    body: Some(derive_body),
                    ..
                } => {
                    typechecker
                        .typecheck_derive(
                            derive_body,
                            &mut ast_errors,
                            current_path,
                            luaurc.as_deref_mut(),
                            &mut dependencies,
                            &mut derives,
                        )
                        .await;
                }

                Construct::Tween {
                    body: Some(body), ..
                } => {
                    ast_errors.report(
                        TypeError::NotAllowedInContext {
                            name: construct.name_plural(),
                            context: "the global scope",
                        },
                        Range::from_span(&typechecker.parsed.rope, construct.span()),
                    );
                    typechecker.typecheck_tween(body, &mut ast_errors);
                }

                Construct::Rule { selectors, body } => {
                    typechecker.typecheck_rule(
                        (selectors, body),
                        &vec![],
                        &mut ast_errors,
                        &mut definitions,
                        &mut resolved_types,
                    );
                }

                Construct::Macro {
                    name,
                    args,
                    return_type,
                    body,
                    ..
                } => {
                    if let Some(name_node) = name {
                        if let Token::Identifier(name_str) = name_node.token.value() {
                            let arg_names = collect_macro_def_arg_names(args);
                            let arg_count = arg_names.len();
                            let context = macro_return_context(return_type);
                            let key = MacroKey {
                                name: *name_str,
                                arity: arg_count,
                            };

                            let builtin_collision = !typechecker.parsed.directives.nobuiltins
                                && crate::builtins::BUILTINS.registry.contains_key(&key);

                            let local_collision =
                                typechecker.macro_registry.contains_key(&key);

                            if builtin_collision || local_collision {
                                ast_errors.report(
                                    TypeError::DuplicateMacro {
                                        name: name_str,
                                        arg_count,
                                    },
                                    Range::from_span(&typechecker.parsed.rope, construct.span()),
                                );
                            } else {
                                typechecker.macro_registry.insert(
                                    key,
                                    MacroDefinition {
                                        arg_names,
                                        body: body.as_ref().map(|b| &b.content),
                                        return_context: context,
                                    },
                                );
                            }
                        }
                    }
                    typechecker.typecheck_macro(args, body, &mut ast_errors);
                }

                Construct::MacroCall { name, body, .. } => {
                    typechecker.validate_macro_call(
                        name,
                        body,
                        MacroReturnContext::Construct,
                        &mut ast_errors,
                    );
                }

                Construct::Assignment {
                    left,
                    right: Some(right),
                    ..
                } => {
                    if matches!(left.token.value(), Token::Identifier(_)) {
                        ast_errors.report(
                            TypeError::NotAllowedInContext {
                                name: construct.name_plural(),
                                context: "the global scope",
                            },
                            Range::from_span(&typechecker.parsed.rope, construct.span()),
                        );
                    }
                    typechecker.validate_token_refs(right, &mut ast_errors);
                    typechecker.validate_macro_arg_refs(right, None, &mut ast_errors);
                    typechecker.validate_annotation(right, &mut ast_errors);
                    if let Construct::MacroCall { name, body, .. } = right.as_ref() {
                        typechecker.validate_macro_call(
                            name,
                            body,
                            MacroReturnContext::Datatype,
                            &mut ast_errors,
                        );
                    }
                    typechecker.resolve_token_assignment(left, right, &[], &mut ast_errors, &mut definitions, &mut resolved_types);
                }

                Construct::Priority { .. } => {
                    ast_errors.report(
                        TypeError::NotAllowedInContext {
                            name: construct.name_plural(),
                            context: "the global scope",
                        },
                        Range::from_span(&typechecker.parsed.rope, construct.span()),
                    );
                }

                _ => (),
            }
        }

        typechecker.detect_recursive_macro_calls(&mut ast_errors);

        TypecheckedRsml {
            errors: ast_errors,
            derives,
            dependencies,
            definitions,
            resolved_types,
        }
    }

    pub(crate) fn resolve_token_assignment(
        &mut self,
        left: &Node<'a>,
        right: &Construct<'a>,
        current_classes: &[String],
        ast_errors: &mut AstErrors,
        definitions: &mut Definitions,
        resolved_types: &mut ResolvedTypes,
    ) {
        let lhs_kind = match left.token.value() {
            Token::TokenIdentifier(name) => LhsKind::Token { name: *name, is_static: false },
            Token::StaticTokenIdentifier(name) => LhsKind::Token { name: *name, is_static: true },
            Token::Identifier(name) => LhsKind::Property { name: *name },
            _ => return,
        };

        let name = lhs_kind.name();

        // Validate any enum references on the RHS. If invalid, the LHS type
        // collapses to `unknown`.
        let enum_valid = self.validate_enum_refs(left, right, ast_errors);

        let resolved_type = if !enum_valid {
            Datatype::None
        } else {
            let lookup = TypecheckerLookup { scopes: &self.static_scopes };

            let evaluated = match lhs_kind {
                LhsKind::Token { .. } => {
                    if let Construct::Node { node } = right {
                        if let Token::StateSelectorOrEnumPart(Some(value)) = node.token.value() {
                            Some(Datatype::IncompleteEnumShorthand(value.to_string()))
                        } else {
                            evaluate_construct(right, Some(name), &lookup)
                        }
                    } else {
                        evaluate_construct(right, Some(name), &lookup)
                    }
                }
                LhsKind::Property { .. } => evaluate_construct(right, Some(name), &lookup),
            };

            match lhs_kind {
                LhsKind::Token { is_static, .. } => match evaluated {
                    Some(Datatype::IncompleteEnumShorthand(variant)) => {
                        Datatype::IncompleteEnumShorthand(variant)
                    }
                    Some(d) if is_static => d,
                    Some(d) => d
                        .coerce_to_variant(Some(name))
                        .map(Datatype::Variant)
                        .unwrap_or(Datatype::None),
                    None => Datatype::None,
                },
                LhsKind::Property { .. } => match evaluated {
                    Some(d) => d
                        .coerce_to_variant(Some(name))
                        .map(Datatype::Variant)
                        .unwrap_or(Datatype::None),
                    None => Datatype::None,
                },
            }
        };

        let (start, end) = left.token.span();

        match lhs_kind {
            LhsKind::Token { is_static, .. } => {
                if is_static {
                    if let Some(frame) = self.static_scopes.last_mut() {
                        frame.insert(name.to_string(), resolved_type.clone());
                    }
                }

                let key = ResolvedTypeKey::Token { name: name.to_string(), is_static };
                resolved_types.insert(key.clone(), resolved_type);

                if let Some(frame) = self.declared_tokens.last_mut() {
                    frame.insert(key);
                }

                definitions.insert(
                    start..=end,
                    DefinitionKind::Token { name: name.to_string(), is_static },
                );
            }
            LhsKind::Property { .. } => {
                self.check_property_against_reflection(
                    name,
                    &resolved_type,
                    current_classes,
                    left,
                    right,
                    ast_errors,
                );

                let type_definition = vec![resolved_type.type_name()];
                resolved_types.insert(
                    ResolvedTypeKey::Property { start },
                    resolved_type,
                );
                definitions.insert(
                    start..=end,
                    DefinitionKind::Assignment {
                        property_name: name.to_string(),
                        type_definition,
                    },
                );
            }
        }
    }

    /// Cross-checks a property assignment against the reflection database.
    /// Emits `UnknownProperty` when the property doesn't appear on the selector
    /// classes, and `PropertyTypeMismatch` when the RHS's runtime type doesn't
    /// match the declared type. Skipped when `current_classes` is empty — that
    /// covers global-scope assignments and pseudo-selector bodies
    /// (`UICorner { ... }`) where no Instance class drives the lookup.
    fn check_property_against_reflection(
        &self,
        property_name: &str,
        resolved_type: &Datatype,
        current_classes: &[String],
        left: &Node<'a>,
        right: &Construct<'a>,
        ast_errors: &mut AstErrors,
    ) {
        if current_classes.is_empty() {
            return;
        }

        let Ok(db) = rbx_reflection_database::get() else {
            return;
        };

        let mut descriptors: Vec<Option<&rbx_reflection::PropertyDescriptor>> =
            Vec::with_capacity(current_classes.len());

        let mut missing_classes: Vec<String> = Vec::new();
        let mut present_classes: Vec<String> = Vec::new();

        for class_name in current_classes {
            let descriptor = properties::lookup_property(db, class_name, property_name);

            if descriptor.is_some() {
                present_classes.push(class_name.clone());
            } else {
                missing_classes.push(class_name.clone());
            }

            descriptors.push(descriptor);
        }

        let should_error = match self.language_mode {
            LanguageMode::Strict => !missing_classes.is_empty(),
            LanguageMode::Nonstrict => present_classes.is_empty(),
        };

        if should_error {
            ast_errors.report(
                TypeError::UnknownProperty {
                    name: property_name.to_string(),
                    missing: missing_classes,
                    present: present_classes,
                },
                Range::from_span(&self.parsed.rope, left.token.span()),
            );
            return;
        }

        let Datatype::Variant(value) = resolved_type else {
            return;
        };

        // Multi-class selectors with differing declared types are essentially
        // nonexistent in Roblox — compare against the first class that declares
        // the property.
        let first_descriptor = descriptors
            .iter()
            .find_map(|descriptor| descriptor.as_ref().copied());

        let Some(descriptor) = first_descriptor else {
            return;
        };

        if properties::variant_matches(descriptor, value) {
            return;
        }

        ast_errors.report(
            TypeError::PropertyTypeMismatch {
                name: property_name.to_string(),
                expected: properties::expected_type_label(descriptor),
                got: crate::datatype::variant_type_name(value.ty()).to_string(),
            },
            Range::from_span(&self.parsed.rope, right.span()),
        );
    }

    /// Validates every enum reference on the RHS of an assignment against the
    /// reflection DB. The `left` node supplies the implicit enum name used by
    /// a top-level shorthand form (`:Variant`) — its name is rebinded via
    /// [`shorthand_rebind`] to match runtime evaluator behavior. Returns
    /// `false` when any error was pushed.
    pub(crate) fn validate_enum_refs(
        &self,
        left: &Node<'a>,
        right: &Construct<'a>,
        ast_errors: &mut AstErrors,
    ) -> bool {
        let mut ok = true;

        // Top-level shorthand `:Variant` — derive enum name from the LHS.
        if let Construct::Node { node } = right {
            if let Token::StateSelectorOrEnumPart(Some(variant)) = node.token.value() {
                let lhs_name = match left.token.value() {
                    Token::Identifier(n)
                    | Token::TokenIdentifier(n)
                    | Token::StaticTokenIdentifier(n) => Some(*n),
                    _ => None,
                };

                if let Some(lhs_name) = lhs_name {
                    let enum_name = shorthand_rebind(lhs_name);
                    let variant_span = strip_sigil_span(node.token.span());
                    ok &= self.check_enum_name_and_variant(
                        enum_name,
                        variant,
                        variant_span,
                        variant_span,
                        ast_errors,
                    );
                }

                return ok;
            }
        }

        ok &= self.validate_enum_refs_inner(right, ast_errors);
        ok
    }

    fn validate_enum_refs_inner(
        &self,
        construct: &Construct<'a>,
        ast_errors: &mut AstErrors,
    ) -> bool {
        let mut ok = true;
        match construct {
            Construct::Enum { name: Some(name_node), variant: Some(variant_node), .. } => {
                let enum_name = annotations::enum_identifier(name_node.token.value());
                let variant = annotations::enum_identifier(variant_node.token.value());

                if let Some(enum_name) = enum_name {
                    let name_span = strip_sigil_span(name_node.token.span());
                    let variant_span = strip_sigil_span(variant_node.token.span());
                    ok &= self.check_enum_name_and_variant(
                        enum_name,
                        variant.unwrap_or(""),
                        name_span,
                        variant_span,
                        ast_errors,
                    );
                }
            }
            Construct::MathOperation { left, right, .. } => {
                ok &= self.validate_enum_refs_inner(left, ast_errors);
                if let Some(right) = right {
                    ok &= self.validate_enum_refs_inner(right, ast_errors);
                }
            }
            Construct::UnaryMinus { operand, .. } => {
                ok &= self.validate_enum_refs_inner(operand, ast_errors);
            }
            Construct::Table { body } => {
                ok &= self.validate_enum_refs_delimited(body, ast_errors);
            }
            Construct::AnnotatedTable { body: Some(body), .. } => {
                ok &= self.validate_enum_refs_delimited(body, ast_errors);
            }
            Construct::MacroCall { body: Some(body), .. } => {
                ok &= self.validate_enum_refs_delimited(body, ast_errors);
            }
            _ => {}
        }
        ok
    }

    fn validate_enum_refs_delimited(
        &self,
        delim: &Delimited<'a>,
        ast_errors: &mut AstErrors,
    ) -> bool {
        let Some(content) = delim.content.as_ref() else {
            return true;
        };
        let mut ok = true;
        for item in content {
            ok &= self.validate_enum_refs_inner(item, ast_errors);
        }
        ok
    }

    fn check_enum_name_and_variant(
        &self,
        enum_name: &str,
        variant: &str,
        name_span: (usize, usize),
        variant_span: (usize, usize),
        ast_errors: &mut AstErrors,
    ) -> bool {
        if !annotations::enum_exists(enum_name) {
            ast_errors.report(
                TypeError::UnknownEnum { name: enum_name.to_string() },
                self.parsed.range_from_span(name_span),
            );
            return false;
        }

        if variant.is_empty() {
            return true;
        }

        if !annotations::validate_enum_variant(variant, enum_name) {
            ast_errors.report(
                TypeError::UnknownEnumVariant {
                    enum_name: enum_name.to_string(),
                    variant: variant.to_string(),
                },
                self.parsed.range_from_span(variant_span),
            );
            return false;
        }

        true
    }

    pub(crate) fn validate_token_refs(
        &self,
        construct: &Construct<'a>,
        ast_errors: &mut AstErrors,
    ) {
        match construct {
            Construct::Node { node } => {
                let (name, is_static) = match node.token.value() {
                    Token::TokenIdentifier(n) => (*n, false),
                    Token::StaticTokenIdentifier(n) => (*n, true),
                    _ => return,
                };
                let key = ResolvedTypeKey::Token {
                    name: name.to_string(),
                    is_static,
                };
                let in_scope = self
                    .declared_tokens
                    .iter()
                    .rev()
                    .any(|frame| frame.contains(&key));
                if !in_scope {
                    ast_errors.report(
                        TypeError::UndefinedToken { name, is_static },
                        self.parsed.range_from_span(node.token.span()),
                    );
                }
            }
            Construct::MathOperation { left, right, .. } => {
                self.validate_token_refs(left, ast_errors);
                if let Some(right) = right {
                    self.validate_token_refs(right, ast_errors);
                }
            }
            Construct::UnaryMinus { operand, .. } => {
                self.validate_token_refs(operand, ast_errors);
            }
            Construct::Table { body } => {
                self.validate_token_refs_delimited(body, ast_errors);
            }
            Construct::AnnotatedTable {
                body: Some(body), ..
            } => {
                self.validate_token_refs_delimited(body, ast_errors);
            }
            Construct::MacroCall {
                body: Some(body), ..
            } => {
                self.validate_token_refs_delimited(body, ast_errors);
            }
            _ => {}
        }
    }

    fn validate_token_refs_delimited(
        &self,
        delim: &Delimited<'a>,
        ast_errors: &mut AstErrors,
    ) {
        let Some(content) = delim.content.as_ref() else {
            return;
        };
        for item in content {
            self.validate_token_refs(item, ast_errors);
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::typechecker::*;
    use crate::{lexer::RsmlLexer, parser::RsmlParser};

    use std::path::PathBuf;

    struct TypecheckResult {
        selectors: Vec<(usize, usize, Vec<String>)>,
        scopes: Vec<(usize, usize, Vec<String>)>,
        tokens: Vec<(usize, usize, String, bool, Datatype)>,
        properties: Vec<(usize, usize, String, Datatype)>,
        errors: Vec<String>,
    }

    async fn typecheck(source: &str) -> TypecheckResult {
        typecheck_with_luaurc(source, None).await
    }

    async fn typecheck_with_luaurc(
        source: &str,
        luaurc_contents: Option<&str>,
    ) -> TypecheckResult {
        let lexer = RsmlLexer::new(source);
        let parsed = RsmlParser::new(lexer);
        let dummy_path = PathBuf::from("/test.rsml");

        let mut luaurc = luaurc_contents.map(Luaurc::new);

        let TypecheckedRsml {
            errors: ast_errors,
            derives: _derives,
            definitions,
            dependencies: _dependencies,
            resolved_types,
        } = Typechecker::new(&parsed, &dummy_path, luaurc.as_mut()).await;

        let selectors: Vec<(usize, usize, Vec<String>)> = definitions
            .iter()
            .filter_map(|(range, kind)| {
                if let DefinitionKind::Selector {
                    type_definition, ..
                } = kind
                {
                    Some((*range.start(), *range.end(), type_definition.clone()))
                } else {
                    None
                }
            })
            .collect();

        let scopes: Vec<(usize, usize, Vec<String>)> = definitions
            .iter()
            .filter_map(|(range, kind)| {
                if let DefinitionKind::Scope {
                    type_definition, ..
                } = kind
                {
                    Some((*range.start(), *range.end(), type_definition.clone()))
                } else {
                    None
                }
            })
            .collect();

        let tokens: Vec<(usize, usize, String, bool, Datatype)> = definitions
            .iter()
            .filter_map(|(range, kind)| {
                if let DefinitionKind::Token { name, is_static } = kind {
                    let resolved_type = resolved_types
                        .get(&ResolvedTypeKey::Token {
                            name: name.clone(),
                            is_static: *is_static,
                        })
                        .cloned()
                        .unwrap_or(Datatype::None);
                    Some((
                        *range.start(),
                        *range.end(),
                        name.clone(),
                        *is_static,
                        resolved_type,
                    ))
                } else {
                    None
                }
            })
            .collect();

        let properties: Vec<(usize, usize, String, Datatype)> = definitions
            .iter()
            .filter_map(|(range, kind)| {
                if let DefinitionKind::Assignment { property_name, .. } = kind {
                    let resolved_type = resolved_types
                        .get(&ResolvedTypeKey::Property { start: *range.start() })
                        .cloned()
                        .unwrap_or(Datatype::None);
                    Some((
                        *range.start(),
                        *range.end(),
                        property_name.clone(),
                        resolved_type,
                    ))
                } else {
                    None
                }
            })
            .collect();

        let errors: Vec<String> = ast_errors
            .0
            .iter()
            .map(|diagnostic| diagnostic.message.clone())
            .collect();

        TypecheckResult {
            selectors,
            scopes,
            tokens,
            properties,
            errors,
        }
    }

    #[tokio::test]
    async fn simple_class_selector() {
        let result = typecheck("Frame {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn class_with_pseudo_selector() {
        let result = typecheck("Frame ::UIPadding {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["UIPadding"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn class_with_state_selector() {
        let result = typecheck("Frame :hover {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn comma_separated_selectors() {
        let result = typecheck("Frame, TextButton {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame", "TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn invalid_class_name() {
        let result = typecheck("NotARealClass {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Instance"]);
        assert_eq!(result.errors.len(), 1);
        assert!(result.errors[0].contains("No class named \"NotARealClass\" exists"));
    }

    #[tokio::test]
    async fn invalid_pseudo_not_a_class() {
        let result = typecheck("Frame ::NotAClass {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Instance"]);
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("No class named \"NotAClass\" exists"))
        );
    }

    #[tokio::test]
    async fn invalid_pseudo_not_allowed() {
        let result = typecheck("Frame ::Frame {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("can't be used as a Pseudo instance"))
        );
    }

    #[tokio::test]
    async fn invalid_state_selector() {
        let result = typecheck("Frame :notastate {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("No state named \"notastate\" exists"))
        );
    }

    #[tokio::test]
    async fn nested_class_without_combinator_errors() {
        let result = typecheck("Frame { TextButton {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["TextButton"]);
        assert_eq!(result.errors.len(), 1);
        assert!(result.errors[0].contains("can't be nested"));
    }

    #[tokio::test]
    async fn nested_child_selector() {
        let result = typecheck("Frame { > TextButton {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn nested_pseudo_selector() {
        let result = typecheck("Frame { ::UIPadding {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["UIPadding"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn nested_state_selector() {
        let result = typecheck("Frame { :hover {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["Frame"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn multiple_nesting_levels() {
        let result = typecheck("Frame { TextButton { TextLabel {} } }").await;
        assert_eq!(result.selectors.len(), 3);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["TextButton"]);
        assert_eq!(result.selectors[2].2, vec!["TextLabel"]);
        assert_eq!(result.errors.len(), 2);
        assert!(
            result
                .errors
                .iter()
                .all(|err| err.contains("can't be nested"))
        );
    }

    #[tokio::test]
    async fn nested_child_combinator_with_nesting() {
        let result = typecheck("Frame { > TextButton { > TextLabel {} } }").await;
        assert_eq!(result.selectors.len(), 3);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["TextButton"]);
        assert_eq!(result.selectors[2].2, vec!["TextLabel"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn top_level_child_selector_resolves_to_child() {
        let result = typecheck("Frame > TextButton {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn top_level_child_with_pseudo_resolves_to_pseudo() {
        let result = typecheck("Frame > TextButton ::UIPadding {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["UIPadding"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn top_level_child_with_state_resolves_to_child() {
        let result = typecheck("Frame > TextButton :hover {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn top_level_chain_with_name_selector_coerces_to_instance() {
        let result = typecheck("Frame > TextButton > .Hello {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Instance"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn top_level_child_with_name_selector_coerces_to_instance() {
        let result = typecheck("Frame > .Hello {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Instance"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn nested_child_with_name_selector_coerces_to_instance() {
        let result = typecheck("Frame { > .Hello {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["Instance"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn chain_with_tag_then_comma() {
        let result = typecheck("Frame >> TextButton > .Hello, Frame {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Instance", "Frame"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn tag_selector_then_comma_at_top_level() {
        let result = typecheck(".Hello, TextButton {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Instance", "TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn nested_tag_then_comma() {
        let result = typecheck("Frame { > .Hello, > TextButton {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["Instance", "TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn duplicate_comma_selectors_are_deduplicated() {
        let result = typecheck("Frame, Frame, TextButton {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame", "TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn all_duplicate_selectors() {
        let result = typecheck("Frame, Frame, Frame {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn duplicate_with_combinator() {
        let result = typecheck("Frame > TextButton, Frame > TextButton {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn duplicate_instance_coercion() {
        let result = typecheck(".Hello, .World {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Instance"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn duplicate_with_state_selectors() {
        let result = typecheck("Frame :hover, Frame :press {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn duplicate_pseudo_selectors() {
        let result = typecheck("Frame ::UIPadding, TextButton ::UIPadding {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["UIPadding"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn nested_duplicate_selectors() {
        let result = typecheck("Frame { > TextButton, > TextButton {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn no_dedup_different_types() {
        let result = typecheck("Frame, TextButton {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame", "TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn preserves_order_after_dedup() {
        let result = typecheck("TextButton, Frame, TextButton {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["TextButton", "Frame"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn scope_inserted_for_rule_body() {
        let result = typecheck("Frame {}").await;
        assert_eq!(result.scopes.len(), 1);
        assert_eq!(result.scopes[0].2, vec!["Frame"]);
    }

    #[tokio::test]
    async fn scope_has_union_types() {
        let result = typecheck("Frame, TextButton {}").await;
        assert_eq!(result.scopes.len(), 1);
        assert_eq!(result.scopes[0].2, vec!["Frame", "TextButton"]);
    }

    #[tokio::test]
    async fn nested_scopes_have_correct_types() {
        let result = typecheck("Frame { > TextButton {} }").await;
        // Outer scope gets split by inner scope insertion, so 3 entries:
        // two halves of the outer Frame scope + the inner TextButton scope
        assert!(result.scopes.len() >= 2);
        let scope_types: Vec<&Vec<String>> = result.scopes.iter().map(|s| &s.2).collect();
        assert!(scope_types.contains(&&vec!["Frame".to_string()]));
        assert!(scope_types.contains(&&vec!["TextButton".to_string()]));
    }

    #[tokio::test]
    async fn scope_with_combinator() {
        let result = typecheck("Frame > TextButton {}").await;
        assert_eq!(result.scopes.len(), 1);
        assert_eq!(result.scopes[0].2, vec!["TextButton"]);
    }

    #[tokio::test]
    async fn scope_with_pseudo_selector() {
        let result = typecheck("Frame ::UIPadding {}").await;
        assert_eq!(result.scopes.len(), 1);
        assert_eq!(result.scopes[0].2, vec!["UIPadding"]);
    }

    #[tokio::test]
    async fn top_level_state_selector_resolves_to_instance() {
        let result = typecheck(":hover {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Instance"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn top_level_state_selector_invalid_state() {
        let result = typecheck(":notastate {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Instance"]);
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("No state named \"notastate\" exists"))
        );
    }

    #[tokio::test]
    async fn nested_state_selector_inherits_parent_class() {
        let result = typecheck("Frame { :hover {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["Frame"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn top_level_pseudo_selector_resolves_instance_type() {
        let result = typecheck("::UIPadding {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["UIPadding"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn top_level_pseudo_selector_scope_resolves() {
        let result = typecheck("::UIPadding {}").await;
        assert_eq!(result.scopes.len(), 1);
        assert_eq!(result.scopes[0].2, vec!["UIPadding"]);
    }

    #[tokio::test]
    async fn top_level_pseudo_selector_invalid_class() {
        let result = typecheck("::NotARealClass {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Instance"]);
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("No class named \"NotARealClass\" exists"))
        );
    }

    #[tokio::test]
    async fn top_level_pseudo_selector_not_allowed_class() {
        let result = typecheck("::Frame {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("can't be used as a Pseudo instance"))
        );
    }

    #[tokio::test]
    async fn top_level_pseudo_selectors_with_comma() {
        let result = typecheck("::UIPadding, ::UICorner {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["UIPadding", "UICorner"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn comma_after_state_selector_continues() {
        let result = typecheck("Frame :hover, TextButton :hover {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["Frame", "TextButton"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn comma_after_pseudo_selector_continues() {
        let result = typecheck("Frame ::UIPadding, TextButton ::UICorner {}").await;
        assert_eq!(result.selectors.len(), 1);
        assert_eq!(result.selectors[0].2, vec!["UIPadding", "UICorner"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn nested_comma_after_state_selector_continues() {
        let result = typecheck("Frame { > TextButton :hover, > TextLabel :press {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[1].2, vec!["TextButton", "TextLabel"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn nested_comma_after_pseudo_selector_continues() {
        let result = typecheck("Frame { ::UIPadding, ::UICorner {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[1].2, vec!["UIPadding", "UICorner"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn nested_standalone_pseudo_selector_resolves() {
        let result = typecheck("Frame { ::UIPadding {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[0].2, vec!["Frame"]);
        assert_eq!(result.selectors[1].2, vec!["UIPadding"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn nested_comma_after_state_selector_inherits_parent() {
        let result = typecheck("Frame { :hover, :press {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[1].2, vec!["Frame"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn nested_comma_pseudo_with_class_prefix() {
        let result =
            typecheck("Frame { > TextButton ::UIPadding, > TextLabel ::UICorner {} }").await;
        assert_eq!(result.selectors.len(), 2);
        assert_eq!(result.selectors[1].2, vec!["UIPadding", "UICorner"]);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn macro_arg_nonexistent_errors() {
        let result =
            typecheck("@macro Padding (&x) { ::UIPadding { PaddingTop = &nonexistent; } }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("No macro argument named"))
        );
    }

    #[tokio::test]
    async fn macro_arg_valid_no_error() {
        let result =
            typecheck("@macro MyPadding (&all) { ::UIPadding { PaddingTop = &all; } }").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected macro errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_arg_outside_macro_errors() {
        let result = typecheck("Frame { PaddingTop = &all; }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("No macro argument named \"all\" exists."))
        );
    }

    #[tokio::test]
    async fn macro_call_after_definition_no_error() {
        let result = typecheck("@macro Padding () { ::UIPadding {} }\nPadding!();").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Undefined Macro") || err.contains("Wrong Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected macro errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_call_before_definition_errors() {
        let result = typecheck("MyPadding!();\n@macro MyPadding () { ::UIPadding {} }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("No macro named `MyPadding` has been defined"))
        );
    }

    #[tokio::test]
    async fn macro_call_undefined_errors() {
        let result = typecheck("DoesNotExist!();").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("No macro named `DoesNotExist` has been defined"))
        );
    }

    #[tokio::test]
    async fn macro_call_wrong_arg_count_errors() {
        let result = typecheck("@macro Padding (&all) { ::UIPadding {} }\nPadding!();").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Macro Argument Count"))
        );
    }

    #[tokio::test]
    async fn macro_call_correct_arg_count_no_error() {
        let result = typecheck("@macro Padding (&all) { ::UIPadding {} }\nPadding!(10);").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Wrong Macro Argument Count"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_call_overloaded_correct_arg_count() {
        let result = typecheck(
            "@macro Padding (&all) { ::UIPadding {} }\n@macro Padding (&x, &y) { ::UIPadding {} }\nPadding!(1, 2);"
        ).await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Wrong Macro Argument Count"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_call_overloaded_wrong_arg_count() {
        let result = typecheck(
            "@macro MyPadding (&all) { ::UIPadding {} }\n@macro MyPadding (&x, &y) { ::UIPadding {} }\nMyPadding!(1, 2, 3);"
        ).await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Macro Argument Count"))
        );
    }

    #[tokio::test]
    async fn macro_call_construct_in_datatype_context_errors() {
        let result = typecheck("@macro Foo () { Frame {} }\nFrame { Size = Foo!(); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Macro Context"))
        );
    }

    #[tokio::test]
    async fn macro_call_datatype_in_construct_context_errors() {
        let result = typecheck("@macro Foo () -> Datatype { 10 }\nFoo!();").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Macro Context"))
        );
    }

    #[tokio::test]
    async fn macro_call_datatype_in_datatype_context_no_error() {
        let result =
            typecheck("@macro Foo () -> Datatype { 10 }\nFrame { Size = Foo!(); }").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Wrong Macro Context"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_call_selector_in_selector_context_no_error() {
        let result = typecheck("@macro Sel () -> Selector { Frame }\nSel!() {}").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Wrong Macro Context") || err.contains("Undefined Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_call_selector_in_selector_context_with_comma_no_error() {
        let result = typecheck("@macro Sel () -> Selector { Frame }\nFrame, Sel!() {}").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Wrong Macro Context") || err.contains("Undefined Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_call_construct_in_selector_context_errors() {
        let result = typecheck("@macro Foo () { Frame {} }\nFoo!() {}").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Macro Context"))
        );
    }

    #[tokio::test]
    async fn macro_call_in_rule_body() {
        let result = typecheck("@macro Padding () { ::UIPadding {} }\nFrame { Padding!(); }").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Undefined Macro") || err.contains("Wrong Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_call_no_return_type_defaults_to_construct() {
        let result = typecheck("@macro Foo () { Frame {} }\nFoo!();").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Wrong Macro Context") || err.contains("Undefined Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_call_inside_macro_body() {
        let result =
            typecheck("@macro Inner () { ::UIPadding {} }\n@macro Outer () { Inner!(); }").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Undefined Macro") || err.contains("Wrong Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_call_inside_macro_body_undefined_errors() {
        let result = typecheck("@macro Outer () { NotDefined!(); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("No macro named `NotDefined` has been defined"))
        );
    }

    #[tokio::test]
    async fn macro_duplicate_same_name_same_args_errors() {
        let result =
            typecheck("@macro Test () { Frame {} }\n@macro Test () -> Selector { Frame }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Duplicate Macro"))
        );
    }

    #[tokio::test]
    async fn macro_duplicate_same_name_different_args_no_error() {
        let result =
            typecheck("@macro Test (&a) { Frame {} }\n@macro Test (&a, &b) { Frame {} }").await;
        let duplicate_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Duplicate Macro"))
            .collect();
        assert!(
            duplicate_errors.is_empty(),
            "unexpected errors: {:?}",
            duplicate_errors
        );
    }

    #[tokio::test]
    async fn macro_direct_recursion_emits_error() {
        let result = typecheck("@macro Foo() -> Construct { Foo!(); }\nFrame { Foo!(); }").await;
        let recursive: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Recursive Macro Call"))
            .collect();
        assert_eq!(
            recursive.len(),
            1,
            "expected exactly one recursive-call error, got: {:?}",
            recursive
        );
    }

    #[tokio::test]
    async fn macro_indirect_recursion_emits_error() {
        let result = typecheck(
            "@macro A() -> Construct { B!(); }\n@macro B() -> Construct { A!(); }\nFrame { A!(); }",
        )
        .await;
        let recursive: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Recursive Macro Call"))
            .collect();
        assert_eq!(
            recursive.len(),
            1,
            "expected exactly one recursive-call error on the cycle-closing edge, got: {:?}",
            recursive
        );
    }

    #[tokio::test]
    async fn macro_selector_direct_recursion_emits_error() {
        let result = typecheck("@macro Sel -> Selector { Sel!() }\nSel!() { }").await;
        let recursive: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Recursive Macro Call"))
            .collect();
        assert_eq!(
            recursive.len(),
            1,
            "expected exactly one recursive-call error, got: {:?}",
            recursive
        );
    }

    #[tokio::test]
    async fn macro_overload_cross_arity_not_recursive() {
        let result = typecheck(
            "@macro Foo() -> Construct { Foo!(10px); }\n@macro Foo(&v) -> Construct { ::Inner { X = &v; } }\nFrame { Foo!(); }",
        )
        .await;
        let recursive: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Recursive Macro Call"))
            .collect();
        assert!(
            recursive.is_empty(),
            "cross-arity overload should not report recursion, got: {:?}",
            recursive
        );
    }

    #[tokio::test]
    async fn macro_call_selector_no_args_no_error() {
        let result = typecheck("@macro Foo -> Selector { }\nFoo!() {}").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Wrong Macro Context") || err.contains("Undefined Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn macro_call_selector_no_args_with_comma_no_error() {
        let result = typecheck("@macro Foo -> Selector { }\nFoo!(), Frame {}").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Wrong Macro Context") || err.contains("Undefined Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn builtin_padding_one_arg_no_error() {
        let result = typecheck("Frame { Padding!(10); }").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Undefined Macro") || err.contains("Wrong Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn builtin_padding_two_args_no_error() {
        let result = typecheck("Frame { Padding!(10, 20); }").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Undefined Macro") || err.contains("Wrong Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn builtin_padding_three_args_no_error() {
        let result = typecheck("Frame { Padding!(10, 20, 30); }").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Undefined Macro") || err.contains("Wrong Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn builtin_padding_four_args_no_error() {
        let result = typecheck("Frame { Padding!(10, 20, 30, 40); }").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Undefined Macro") || err.contains("Wrong Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn builtin_corner_radius_no_error() {
        let result = typecheck("Frame { CornerRadius!(8); }").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Undefined Macro") || err.contains("Wrong Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn builtin_scale_no_error() {
        let result = typecheck("Frame { Scale!(1.5); }").await;
        let macro_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Undefined Macro") || err.contains("Wrong Macro"))
            .collect();
        assert!(
            macro_errors.is_empty(),
            "unexpected errors: {:?}",
            macro_errors
        );
    }

    #[tokio::test]
    async fn builtin_padding_zero_args_errors() {
        let result = typecheck("Frame { Padding!(); }").await;
        let err = result
            .errors
            .iter()
            .find(|err| err.contains("Wrong Macro Argument Count"))
            .expect("expected wrong arg count error");
        assert!(
            err.contains("1, 2, 3, or 4 arguments"),
            "expected Oxford-comma arg list, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn builtin_padding_five_args_errors() {
        let result = typecheck("Frame { Padding!(10, 20, 30, 40, 50); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Macro Argument Count")),
            "expected arg count error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn builtin_corner_radius_wrong_arg_count_errors() {
        let result = typecheck("Frame { CornerRadius!(); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Macro Argument Count")
                    && err.contains("CornerRadius")),
            "expected arg count error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn builtin_user_redefine_padding_duplicate_errors() {
        let result = typecheck("@macro Padding (&all) { ::UIPadding {} }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Duplicate Macro") && err.contains("Padding")),
            "expected duplicate macro error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn builtin_padding_in_assignment_context_errors() {
        let result = typecheck("Frame { Size = Padding!(10); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Macro Context")),
            "expected wrong context error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn builtin_padding_in_selector_context_errors() {
        let result = typecheck("Padding!(10) {}").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Macro Context")),
            "expected wrong context error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn builtin_undefined_macro_still_errors() {
        let result = typecheck("Frame { NotABuiltin!(10); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("No macro named `NotABuiltin` has been defined")),
            "expected undefined macro error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_unknown_name_errors() {
        let result = typecheck("Frame { Size = notareal(1, 2); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Unknown Annotation") && err.contains("notareal")),
            "expected unknown annotation error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_valid_udim2_no_error() {
        let result = typecheck("Frame { Size = udim2(1, 0, 1, 0); }").await;
        let annotation_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Annotation"))
            .collect();
        assert!(
            annotation_errors.is_empty(),
            "unexpected errors: {:?}",
            annotation_errors
        );
    }

    #[tokio::test]
    async fn annotation_valid_vec3_no_error() {
        let result = typecheck("Frame { Position = vec3(1, 2, 3); }").await;
        let annotation_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Annotation"))
            .collect();
        assert!(
            annotation_errors.is_empty(),
            "unexpected errors: {:?}",
            annotation_errors
        );
    }

    #[tokio::test]
    async fn annotation_too_many_args_errors() {
        let result = typecheck("Frame { Size = vec2(1, 2, 3); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Annotation Argument Count")),
            "expected arg count error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_too_few_args_errors() {
        let result = typecheck("Frame { Size = lerp(); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Annotation Argument Count")),
            "expected arg count error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_wrong_arg_type_errors() {
        let result = typecheck("Frame { Size = vec2(\"hello\", \"world\"); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Annotation Argument Type")),
            "expected arg type error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_variadic_colorseq_many_args() {
        let result = typecheck("Frame { Color = colorseq(#ff0000, #00ff00, #0000ff); }").await;
        let annotation_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Annotation"))
            .collect();
        assert!(
            annotation_errors.is_empty(),
            "unexpected errors: {:?}",
            annotation_errors
        );
    }

    #[tokio::test]
    async fn annotation_variadic_colorseq_empty_errors() {
        let result = typecheck("Frame { Color = colorseq(); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Annotation Argument Count")),
            "expected arg count error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_nested_annotation_validated() {
        let result = typecheck("Frame { Size = udim2(vec2(1, 2, 3), 0); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Annotation Argument Count")),
            "expected nested vec2 arg count error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_case_insensitive_matching() {
        let result = typecheck("Frame { Size = UDim2(1, 0, 1, 0); }").await;
        let annotation_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Annotation"))
            .collect();
        assert!(
            annotation_errors.is_empty(),
            "unexpected errors: {:?}",
            annotation_errors
        );
    }

    #[tokio::test]
    async fn annotation_zero_args_errors() {
        let result = typecheck("Frame { Color = brickcolor(); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Annotation Argument Count")),
            "expected arg count error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_color3_accepts_color_arg() {
        let result = typecheck("Frame { BackgroundColor3 = color3(#ff0000); }").await;
        let annotation_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Annotation"))
            .collect();
        assert!(
            annotation_errors.is_empty(),
            "unexpected errors: {:?}",
            annotation_errors
        );
    }

    #[tokio::test]
    async fn annotation_color3_three_numbers() {
        let result = typecheck("Frame { BackgroundColor3 = color3(1, 0, 0); }").await;
        let annotation_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Annotation"))
            .collect();
        assert!(
            annotation_errors.is_empty(),
            "unexpected errors: {:?}",
            annotation_errors
        );
    }

    #[tokio::test]
    async fn annotation_udim2_with_percent_scale() {
        let result = typecheck("Frame { Size = udim2(50%, 50%); }").await;
        let annotation_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Annotation"))
            .collect();
        assert!(
            annotation_errors.is_empty(),
            "unexpected errors: {:?}",
            annotation_errors
        );
    }

    #[tokio::test]
    async fn annotation_font_with_enum() {
        let result =
            typecheck("Frame { FontFace = font(\"rbxasset://fonts/arial.ttf\", Enum.FontWeight.Bold); }")
                .await;
        let annotation_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Annotation"))
            .collect();
        assert!(
            annotation_errors.is_empty(),
            "unexpected errors: {:?}",
            annotation_errors
        );
    }

    #[tokio::test]
    async fn annotation_at_top_level_is_validated() {
        let result = typecheck("$Size = vec2(1, 2, 3);").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Annotation Argument Count")),
            "expected arg count error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_in_macro_body_is_validated() {
        let result =
            typecheck("@macro Foo () { Frame { Size = vec2(1, 2, 3); } }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Wrong Annotation Argument Count")),
            "expected arg count error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_token_arg_errors() {
        let result = typecheck("Frame { Size = udim2($Width, 0, 1, 0); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Tokens are not allowed in tuple annotations")),
            "expected token-in-annotation error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_token_nested_inside_math_errors() {
        let result = typecheck("Frame { Size = udim2($Width + 10, 0, 1, 0); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Tokens are not allowed in tuple annotations")),
            "expected token-in-annotation error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_static_token_arg_allowed() {
        let result = typecheck("Frame { Size = udim2($!Width, 0, 1, 0); }").await;
        let token_errors: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Tokens are not allowed"))
            .collect();
        assert!(
            token_errors.is_empty(),
            "unexpected static-token error: {:?}",
            token_errors
        );
    }

    fn annotation_arg_type_errors(result: &TypecheckResult) -> Vec<&String> {
        result
            .errors
            .iter()
            .filter(|err| err.contains("must be"))
            .collect()
    }

    #[tokio::test]
    async fn annotation_static_token_measurement_valid() {
        let result = typecheck("$!W = 100; Frame { Size = udim2($!W, 0%); }").await;
        let errs = annotation_arg_type_errors(&result);
        assert!(errs.is_empty(), "unexpected arg-type errors: {:?}", errs);
    }

    #[tokio::test]
    async fn annotation_static_token_scale_measurement_valid() {
        let result = typecheck("$!Hello = 50%; Frame { Hello = udim2(50%, $!Hello); }").await;
        let errs = annotation_arg_type_errors(&result);
        assert!(errs.is_empty(), "unexpected arg-type errors: {:?}", errs);
    }

    #[tokio::test]
    async fn annotation_static_token_number_valid() {
        let result = typecheck("$!N = 10; Frame { Size = vec3($!N, $!N, $!N); }").await;
        let errs = annotation_arg_type_errors(&result);
        assert!(errs.is_empty(), "unexpected arg-type errors: {:?}", errs);
    }

    #[tokio::test]
    async fn annotation_static_token_color_valid() {
        let result =
            typecheck("$!C = #ff0000; Frame { BackgroundColor3 = color3($!C); }").await;
        let errs = annotation_arg_type_errors(&result);
        assert!(errs.is_empty(), "unexpected arg-type errors: {:?}", errs);
    }

    #[tokio::test]
    async fn annotation_static_token_oklab_color_valid() {
        let result =
            typecheck("$!C = tw:red:500; Frame { BackgroundColor3 = color3($!C); }").await;
        let errs = annotation_arg_type_errors(&result);
        assert!(errs.is_empty(), "unexpected arg-type errors: {:?}", errs);
    }

    #[tokio::test]
    async fn annotation_static_token_wrong_type_errors() {
        let result = typecheck("$!S = \"hi\"; Frame { Size = udim2($!S, 0%); }").await;
        let errs = annotation_arg_type_errors(&result);
        assert!(
            !errs.is_empty(),
            "expected a Wrong Annotation Argument Type error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_static_token_unresolved_permissive() {
        let result = typecheck("Frame { Size = udim2($!Unknown, 0%); }").await;
        let errs = annotation_arg_type_errors(&result);
        let token_errs: Vec<_> = result
            .errors
            .iter()
            .filter(|err| err.contains("Tokens are not allowed"))
            .collect();
        assert!(errs.is_empty(), "unexpected arg-type errors: {:?}", errs);
        assert!(token_errs.is_empty(), "unexpected token errors: {:?}", token_errs);
    }

    #[tokio::test]
    async fn annotation_regular_token_still_errors() {
        let result = typecheck("$W = 10; Frame { Size = udim2($W, 0, 1, 0); }").await;
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Tokens are not allowed")),
            "expected token-in-annotation error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn annotation_static_token_in_math_permissive() {
        let result = typecheck("$!W = 10; Frame { Size = udim2($!W + 5, 0%); }").await;
        let errs = annotation_arg_type_errors(&result);
        assert!(errs.is_empty(), "unexpected arg-type errors: {:?}", errs);
    }

    #[tokio::test]
    async fn annotation_static_token_enum_valid() {
        let result = typecheck(
            "$!B = Enum.FontWeight.Bold; Frame { FontFace = font(\"rbxasset://fonts/arial.ttf\", $!B); }",
        )
        .await;
        let errs = annotation_arg_type_errors(&result);
        assert!(errs.is_empty(), "unexpected arg-type errors: {:?}", errs);
    }

    #[tokio::test]
    async fn annotation_static_token_enum_wrong_type_errors() {
        let result =
            typecheck("$!B = Enum.FontWeight.Bold; Frame { Size = udim2($!B, 0%); }").await;
        let errs = annotation_arg_type_errors(&result);
        assert!(
            !errs.is_empty(),
            "expected a Wrong Annotation Argument Type error, got: {:?}",
            result.errors
        );
    }

    fn find_token<'a>(
        result: &'a TypecheckResult,
        name: &str,
        is_static: bool,
    ) -> &'a Datatype {
        result
            .tokens
            .iter()
            .find(|(_, _, n, s, _)| n == name && *s == is_static)
            .map(|(_, _, _, _, dt)| dt)
            .unwrap_or_else(|| {
                panic!(
                    "no token `{}` (static={}) found; tokens={:?}",
                    name,
                    is_static,
                    result.tokens.iter().map(|(_, _, n, s, _)| (n, s)).collect::<Vec<_>>()
                )
            })
    }

    fn find_property<'a>(result: &'a TypecheckResult, name: &str) -> &'a Datatype {
        result
            .properties
            .iter()
            .find(|(_, _, n, _)| n == name)
            .map(|(_, _, _, dt)| dt)
            .unwrap_or_else(|| {
                panic!(
                    "no property `{}` found; properties={:?}",
                    name,
                    result.properties.iter().map(|(_, _, n, _)| n).collect::<Vec<_>>()
                )
            })
    }

    #[tokio::test]
    async fn token_number_type() {
        let result = typecheck("$X = 10;").await;
        let dt = find_token(&result, "X", false);
        assert!(
            matches!(dt, Datatype::Variant(rbx_types::Variant::Float64(n)) if *n == 10.0),
            "got {:?}",
            dt
        );
    }

    #[tokio::test]
    async fn token_color_hex_coerces_for_regular() {
        let result = typecheck("$X = #ff0000;").await;
        let dt = find_token(&result, "X", false);
        assert!(
            matches!(dt, Datatype::Variant(rbx_types::Variant::Color3(_))),
            "got {:?}",
            dt
        );
    }

    #[tokio::test]
    async fn token_color_tailwind_coerces_to_color3() {
        let result = typecheck("$X = tw:red:500;").await;
        let dt = find_token(&result, "X", false);
        assert!(
            matches!(dt, Datatype::Variant(rbx_types::Variant::Color3(_))),
            "got {:?}",
            dt
        );
    }

    #[tokio::test]
    async fn static_token_keeps_oklab() {
        let result = typecheck("$!X = tw:red:500;").await;
        let dt = find_token(&result, "X", true);
        assert!(matches!(dt, Datatype::Oklab(_)), "got {:?}", dt);
    }

    #[tokio::test]
    async fn token_udim2() {
        let result = typecheck("$X = udim2(1, 0, 1, 0);").await;
        let dt = find_token(&result, "X", false);
        assert!(
            matches!(dt, Datatype::Variant(rbx_types::Variant::UDim2(_))),
            "got {:?}",
            dt
        );
    }

    #[tokio::test]
    async fn token_string() {
        let result = typecheck("$X = \"hi\";").await;
        let dt = find_token(&result, "X", false);
        assert!(
            matches!(dt, Datatype::Variant(rbx_types::Variant::String(s)) if s == "hi"),
            "got {:?}",
            dt
        );
    }

    #[tokio::test]
    async fn static_token_cross_ref() {
        let result = typecheck("$!A = 10; $!B = $!A;").await;
        let a = find_token(&result, "A", true);
        let b = find_token(&result, "B", true);
        assert!(
            matches!(a, Datatype::Variant(rbx_types::Variant::Float64(n)) if *n == 10.0),
            "got A={:?}",
            a
        );
        assert!(
            matches!(b, Datatype::Variant(rbx_types::Variant::Float64(n)) if *n == 10.0),
            "got B={:?}",
            b
        );
    }

    #[tokio::test]
    async fn static_token_math() {
        let result = typecheck("$!A = 10; $!B = $!A + 5;").await;
        let b = find_token(&result, "B", true);
        assert!(
            matches!(b, Datatype::Variant(rbx_types::Variant::Float64(n)) if *n == 15.0),
            "got {:?}",
            b
        );
    }

    #[tokio::test]
    async fn token_inside_rule_body() {
        let result = typecheck("Frame { $X = 10; }").await;
        let dt = find_token(&result, "X", false);
        assert!(
            matches!(dt, Datatype::Variant(rbx_types::Variant::Float64(n)) if *n == 10.0),
            "got {:?}",
            dt
        );
    }

    #[tokio::test]
    async fn static_token_parent_scope_lookup() {
        let result = typecheck("$!A = 10; Frame { $!B = $!A; }").await;
        let b = find_token(&result, "B", true);
        assert!(
            matches!(b, Datatype::Variant(rbx_types::Variant::Float64(n)) if *n == 10.0),
            "got {:?}",
            b
        );
    }

    #[tokio::test]
    async fn regular_token_ref_is_unknown() {
        let result = typecheck("$A = 10; $B = $A;").await;
        let b = find_token(&result, "B", false);
        assert!(matches!(b, Datatype::None), "got {:?}", b);
    }

    #[tokio::test]
    async fn token_invalid_rhs() {
        let result = typecheck("$X = ;").await;
        if let Some((_, _, _, _, dt)) = result
            .tokens
            .iter()
            .find(|(_, _, n, s, _)| n == "X" && !*s)
        {
            assert!(matches!(dt, Datatype::None), "got {:?}", dt);
        }
    }

    #[tokio::test]
    async fn token_enum_shorthand_dynamic_unknown_enum() {
        let result = typecheck("$X = :Hello;").await;
        let dt = find_token(&result, "X", false);
        assert!(matches!(dt, Datatype::None), "got {:?}", dt);
        assert!(
            result.errors.iter().any(|err| err.contains("Unknown Enum")),
            "expected Unknown Enum error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn token_enum_shorthand_static_unknown_enum() {
        let result = typecheck("$!X = :Hello;").await;
        let dt = find_token(&result, "X", true);
        assert!(matches!(dt, Datatype::None), "got {:?}", dt);
        assert!(
            result.errors.iter().any(|err| err.contains("Unknown Enum")),
            "expected Unknown Enum error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn token_full_enum_valid_dynamic() {
        let result = typecheck("$X = Enum.Material.Plastic;").await;
        let dt = find_token(&result, "X", false);
        assert!(
            matches!(
                dt,
                Datatype::Variant(rbx_types::Variant::EnumItem(item)) if item.ty == "Material"
            ),
            "got {:?}",
            dt
        );
    }

    #[tokio::test]
    async fn token_full_enum_valid_static() {
        let result = typecheck("$!X = Enum.Material.Plastic;").await;
        let dt = find_token(&result, "X", true);
        assert!(
            matches!(
                dt,
                Datatype::Variant(rbx_types::Variant::EnumItem(item)) if item.ty == "Material"
            ),
            "got {:?}",
            dt
        );
    }

    #[tokio::test]
    async fn token_full_enum_unresolvable_dynamic() {
        let result = typecheck("$X = Enum.NotReal.xyz;").await;
        let dt = find_token(&result, "X", false);
        assert!(matches!(dt, Datatype::None), "got {:?}", dt);
        assert!(
            result.errors.iter().any(|err| err.contains("Unknown Enum")),
            "expected Unknown Enum error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn token_full_enum_unresolvable_static() {
        let result = typecheck("$!X = Enum.NotReal.xyz;").await;
        let dt = find_token(&result, "X", true);
        assert!(matches!(dt, Datatype::None), "got {:?}", dt);
        assert!(
            result.errors.iter().any(|err| err.contains("Unknown Enum")),
            "expected Unknown Enum error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn token_boolean_dynamic() {
        let result = typecheck("$X = true;").await;
        let dt = find_token(&result, "X", false);
        assert!(
            matches!(dt, Datatype::Variant(rbx_types::Variant::Bool(true))),
            "got {:?}",
            dt
        );
    }

    #[tokio::test]
    async fn static_token_oklch_not_coerced() {
        let result = typecheck("$!X = oklch(0.5, 0.1, 180);").await;
        let dt = find_token(&result, "X", true);
        assert!(matches!(dt, Datatype::Oklch(_)), "got {:?}", dt);
    }

    fn has_undefined_token_error(result: &TypecheckResult) -> bool {
        result.errors.iter().any(|err| err.contains("Undefined Token"))
    }

    #[tokio::test]
    async fn undefined_dynamic_token_direct() {
        let result = typecheck("$A = $nope;").await;
        assert!(
            has_undefined_token_error(&result),
            "expected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn undefined_static_token_direct() {
        let result = typecheck("$!A = $!nope;").await;
        assert!(
            has_undefined_token_error(&result),
            "expected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn undefined_token_in_property_assignment() {
        let result = typecheck("Frame { Size = $nope; }").await;
        assert!(
            has_undefined_token_error(&result),
            "expected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn undefined_token_in_annotated_tuple() {
        let result = typecheck("Frame { Size = udim2(0%, $!Hello, 0%, 0%); }").await;
        assert!(
            has_undefined_token_error(&result),
            "expected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn undefined_token_in_math() {
        let result = typecheck("$!A = 10; $!B = $!A + $!nope;").await;
        assert!(
            has_undefined_token_error(&result),
            "expected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn undefined_token_in_table() {
        let result = typecheck("$A = { $nope };").await;
        assert!(
            has_undefined_token_error(&result),
            "expected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn same_statement_self_ref_errors() {
        let result = typecheck("$A = $A;").await;
        assert!(
            has_undefined_token_error(&result),
            "expected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn dynamic_and_static_distinct_keys() {
        let result = typecheck("$A = 10; $B = $!A;").await;
        assert!(
            has_undefined_token_error(&result),
            "expected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn defined_static_token_no_error() {
        let result = typecheck("$!A = 10; $!B = $!A;").await;
        assert!(
            !has_undefined_token_error(&result),
            "unexpected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn defined_dynamic_token_no_error() {
        let result = typecheck("$A = 10; Frame { Size = $A; }").await;
        assert!(
            !has_undefined_token_error(&result),
            "unexpected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn nested_rule_inherits_outer_token() {
        let result = typecheck("$!A = 10; Frame { $!B = $!A; }").await;
        assert!(
            !has_undefined_token_error(&result),
            "unexpected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn inner_shadow_resolves_to_outer_in_same_rhs() {
        let result = typecheck("$!A = 10; Frame { $!A = $!A; }").await;
        assert!(
            !has_undefined_token_error(&result),
            "unexpected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn declared_unknown_static_token_errors_in_annotation_arg() {
        let result =
            typecheck("$!Hello = Enum.Hello.world; Frame { Size = udim2(50%, $!Hello); }").await;
        let errs = annotation_arg_type_errors(&result);
        assert!(
            !errs.is_empty(),
            "expected a Wrong Annotation Argument Type error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn same_scope_redeclaration_still_declared() {
        let result = typecheck("$A = 10; $A = 20; Frame { Size = $A; }").await;
        assert!(
            !has_undefined_token_error(&result),
            "unexpected Undefined Token error, got: {:?}",
            result.errors
        );
    }

    fn has_unknown_enum_error(result: &TypecheckResult) -> bool {
        result.errors.iter().any(|err| err.contains("Unknown Enum"))
    }

    #[tokio::test]
    async fn property_shorthand_unknown_enum_name() {
        let result = typecheck("Frame { Hello = :World; }").await;
        assert!(
            has_unknown_enum_error(&result),
            "expected Unknown Enum error, got: {:?}",
            result.errors
        );
        let dt = find_property(&result, "Hello");
        assert!(matches!(dt, Datatype::None), "got {:?}", dt);
    }

    #[tokio::test]
    async fn property_full_enum_unknown_name() {
        let result = typecheck("Frame { Foo = Enum.Hello.World; }").await;
        assert!(
            has_unknown_enum_error(&result),
            "expected Unknown Enum error, got: {:?}",
            result.errors
        );
        let dt = find_property(&result, "Foo");
        assert!(matches!(dt, Datatype::None), "got {:?}", dt);
    }

    #[tokio::test]
    async fn token_full_enum_unknown_variant() {
        let result = typecheck("$X = Enum.Material.NotAVariant;").await;
        let dt = find_token(&result, "X", false);
        assert!(matches!(dt, Datatype::None), "got {:?}", dt);
        assert!(
            result
                .errors
                .iter()
                .any(|err| err.contains("Unknown Enum Variant")),
            "expected Unknown Enum Variant error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn property_full_enum_valid() {
        let result = typecheck("Frame { Material = Enum.Material.Plastic; }").await;
        assert!(
            !has_unknown_enum_error(&result),
            "unexpected Unknown Enum error, got: {:?}",
            result.errors
        );
        let dt = find_property(&result, "Material");
        assert!(
            matches!(
                dt,
                Datatype::Variant(rbx_types::Variant::EnumItem(item)) if item.ty == "Material"
            ),
            "got {:?}",
            dt
        );
    }

    fn has_unknown_property_error(result: &TypecheckResult) -> bool {
        result
            .errors
            .iter()
            .any(|err| err.contains("Unknown Property"))
    }

    fn has_property_type_mismatch_error(result: &TypecheckResult) -> bool {
        result
            .errors
            .iter()
            .any(|err| err.contains("Property Type Mismatch"))
    }

    #[tokio::test]
    async fn property_matching_reflection_type_no_error() {
        let result = typecheck("Frame { Position = UDim2.new(0, 0, 0, 0); }").await;
        assert!(
            !has_unknown_property_error(&result) && !has_property_type_mismatch_error(&result),
            "unexpected property diagnostics, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn property_type_mismatch_emits_error() {
        let result = typecheck("Frame { Position = \"hello\"; }").await;
        assert!(
            has_property_type_mismatch_error(&result),
            "expected Property Type Mismatch error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn unknown_property_emits_error() {
        let result = typecheck("Frame { Bogus = 1; }").await;
        assert!(
            has_unknown_property_error(&result),
            "expected Unknown Property error, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn multi_class_nonstrict_accepts_partial_property() {
        let result = typecheck("TextButton, Frame { Text = \"hi\"; }").await;
        assert!(
            !has_unknown_property_error(&result),
            "unexpected Unknown Property error in nonstrict mode, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn multi_class_strict_directive_rejects_partial_property() {
        let result = typecheck("--!strict\nTextButton, Frame { Text = \"hi\"; }").await;
        assert!(
            has_unknown_property_error(&result),
            "expected Unknown Property error in strict mode, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn luaurc_strict_rejects_partial_property() {
        let result = typecheck_with_luaurc(
            "TextButton, Frame { Text = \"hi\"; }",
            Some(r#"{ "languageMode": "strict" }"#),
        )
        .await;
        assert!(
            has_unknown_property_error(&result),
            "expected Unknown Property error from luaurc strict mode, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn directive_nonstrict_overrides_luaurc_strict() {
        let result = typecheck_with_luaurc(
            "--!nonstrict\nTextButton, Frame { Text = \"hi\"; }",
            Some(r#"{ "languageMode": "strict" }"#),
        )
        .await;
        assert!(
            !has_unknown_property_error(&result),
            "unexpected Unknown Property error when directive overrides luaurc, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn luaurc_unknown_mode_treated_as_nonstrict() {
        let result = typecheck_with_luaurc(
            "TextButton, Frame { Text = \"hi\"; }",
            Some(r#"{ "languageMode": "nocheck" }"#),
        )
        .await;
        assert!(
            !has_unknown_property_error(&result),
            "unexpected Unknown Property error for unknown luaurc mode, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn multi_class_unknown_everywhere_errors_in_nonstrict() {
        let result = typecheck("TextButton, Frame { Bogus = 1; }").await;
        assert!(
            has_unknown_property_error(&result),
            "expected Unknown Property error when property missing on every class, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn multi_class_shared_property_no_error() {
        let result =
            typecheck("Frame, TextLabel { BackgroundColor3 = Color3.new(1, 1, 1); }").await;
        assert!(
            !has_unknown_property_error(&result) && !has_property_type_mismatch_error(&result),
            "unexpected property diagnostics for shared property, got: {:?}",
            result.errors
        );
    }

    #[tokio::test]
    async fn pseudo_selector_skips_property_check() {
        let result = typecheck("UICorner { CornerRadius = UDim.new(0, 8); }").await;
        assert!(
            !has_unknown_property_error(&result) && !has_property_type_mismatch_error(&result),
            "unexpected property diagnostics in pseudo-selector body, got: {:?}",
            result.errors
        );
    }
}