spade-ast-lowering 0.13.0

Helper crate for https://spade-lang.org/
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
mod attributes;
pub mod builtins;
pub mod error;
pub mod global_symbols;
mod impls;
pub mod pipelines;
pub mod testutil;
mod type_level_if;
pub mod types;

use attributes::LocAttributeExt;
use global_symbols::visit_meta_type;
use impls::visit_impl;
use num::{BigInt, Zero};
use pipelines::PipelineContext;
use recursive::recursive;
use spade_diagnostics::codespan::Span;
use spade_diagnostics::diagnostic::SuggestionParts;
use spade_diagnostics::{diag_bail, Diagnostic};
use spade_types::meta_types::MetaType;
use tracing::{event, Level};
use type_level_if::expand_type_level_if;

use crate::attributes::AttributeListExt;
pub use crate::impls::ensure_unique_anonymous_traits;
use crate::pipelines::maybe_perform_pipelining_tasks;
use crate::types::{IsPort, IsSelf};
use ast::{Binding, CallKind, ParameterList};
use hir::expression::{BinaryOperator, IntLiteralKind};
use hir::param_util::ArgumentError;
use hir::symbol_table::DeclarationState;
use hir::symbol_table::{LookupError, SymbolTable, Thing, TypeSymbol};
use hir::{ConstGeneric, ExecutableItem, PatternKind, TraitName, WalTrace};
use spade_ast::{self as ast, Attribute, Expression, TypeParam, WhereClause};
pub use spade_common::id_tracker;
use spade_common::id_tracker::{ExprIdTracker, ImplIdTracker};
use spade_common::location_info::{FullSpan, Loc, WithLocation};
use spade_common::name::{Identifier, Path};
use spade_hir::{self as hir, ItemList, Module, TraitSpec, TypeExpression, TypeSpec};
use std::collections::HashSet;

use error::Result;

pub struct Context {
    pub symtab: SymbolTable,
    pub item_list: ItemList,
    pub idtracker: ExprIdTracker,
    pub impl_idtracker: ImplIdTracker,
    pub pipeline_ctx: Option<PipelineContext>,
    pub self_ctx: SelfContext,
}

trait LocExt<T> {
    fn try_visit<V, U>(&self, visitor: V, context: &mut Context) -> Result<Loc<U>>
    where
        V: Fn(&T, &mut Context) -> Result<U>;
}

impl<T> LocExt<T> for Loc<T> {
    fn try_visit<V, U>(&self, visitor: V, context: &mut Context) -> Result<Loc<U>>
    where
        V: Fn(&T, &mut Context) -> Result<U>,
    {
        self.map_ref(|t| visitor(t, context)).map_err(|e, _| e)
    }
}

/// Visit an AST type parameter, converting it to a HIR type parameter and adding it
/// to the symbol table
#[tracing::instrument(skip_all, fields(name=%param.name()))]
pub fn visit_type_param(param: &ast::TypeParam, ctx: &mut Context) -> Result<hir::TypeParam> {
    match &param {
        ast::TypeParam::TypeName {
            name: ident,
            traits,
        } => {
            let trait_bounds: Vec<Loc<TraitSpec>> = traits
                .iter()
                .map(|t| visit_trait_spec(t, &TypeSpecKind::TraitBound, ctx))
                .collect::<Result<_>>()?;

            let name_id = ctx.symtab.add_type(
                Path::ident(ident.clone()),
                TypeSymbol::GenericArg {
                    traits: trait_bounds.clone(),
                }
                .at_loc(ident),
            );

            Ok(hir::TypeParam {
                ident: ident.clone(),
                name_id,
                trait_bounds,
                meta: MetaType::Type,
            })
        }
        ast::TypeParam::TypeWithMeta { meta, name } => {
            let meta = visit_meta_type(meta)?;
            let name_id = ctx.symtab.add_type(
                Path::ident(name.clone()),
                TypeSymbol::GenericMeta(meta.clone()).at_loc(name),
            );

            Ok(hir::TypeParam {
                ident: name.clone(),
                name_id,
                trait_bounds: vec![],
                meta,
            })
        }
    }
}

/// Visit an AST type parameter, converting it to a HIR type parameter. The name is not
/// added to the symbol table as this function is re-used for both global symbol collection
/// and normal HIR lowering.
#[tracing::instrument(skip_all, fields(name=%param.name()))]
pub fn re_visit_type_param(param: &ast::TypeParam, ctx: &Context) -> Result<hir::TypeParam> {
    match &param {
        ast::TypeParam::TypeName {
            name: ident,
            traits: _,
        } => {
            let path = Path::ident(ident.clone()).at_loc(ident);
            let (name_id, tsym) = ctx.symtab.lookup_type_symbol(&path)?;

            let trait_bounds = match &tsym.inner {
                TypeSymbol::GenericArg { traits } => traits.clone(),
                _ => return Err(Diagnostic::bug(
                    ident,
                    format!(
                        "Trait bound on {ident} on non-generic argument, which should've been caught by the first pass"
                    ),
                ))
            };

            Ok(hir::TypeParam {
                ident: ident.clone(),
                name_id,
                trait_bounds,
                meta: MetaType::Type,
            })
        }
        ast::TypeParam::TypeWithMeta { meta, name } => {
            let path = Path::ident(name.clone()).at_loc(name);
            let name_id = ctx.symtab.lookup_type_symbol(&path)?.0;
            Ok(hir::TypeParam {
                ident: name.clone(),
                name_id,
                trait_bounds: vec![],
                meta: visit_meta_type(meta)?,
            })
        }
    }
}

/// The context in which a type expression occurs. This controls what hir::TypeExpressions an
/// ast::TypeExpression can be lowered to
pub enum TypeSpecKind {
    Argument,
    OutputType,
    EnumMember,
    StructMember,
    ImplTrait,
    ImplTarget,
    BindingType,
    Turbofish,
    PipelineDepth,
    TraitBound,
    TypeLevelIf,
}

#[recursive]
pub fn visit_type_expression(
    expr: &ast::TypeExpression,
    kind: &TypeSpecKind,
    ctx: &mut Context,
) -> Result<hir::TypeExpression> {
    match expr {
        ast::TypeExpression::TypeSpec(spec) => {
            let inner = visit_type_spec(spec, kind, ctx)?;
            // Look up the type. For now, we'll panic if we don't find a concrete type
            Ok(hir::TypeExpression::TypeSpec(inner.inner))
        }
        ast::TypeExpression::Integer(val) => Ok(hir::TypeExpression::Integer(val.clone())),
        ast::TypeExpression::ConstGeneric(expr) => {
            let default_error = |message, primary| {
                Err(Diagnostic::error(
                    expr.as_ref(),
                    format!("{message} cannot have const generics in their type"),
                )
                .primary_label(format!("Const generic in {primary}")))
            };
            match kind {
                TypeSpecKind::ImplTrait => default_error("Implemented traits", "implemented trait"),
                TypeSpecKind::ImplTarget => default_error("Impl targets", "impl target"),
                TypeSpecKind::EnumMember => default_error("Enum members", "enum member"),
                TypeSpecKind::StructMember => default_error("Struct members", "struct member"),
                TypeSpecKind::TraitBound => {
                    default_error("Traits used in trait bounds", "trait bound")
                }
                TypeSpecKind::Argument
                | TypeSpecKind::OutputType
                | TypeSpecKind::Turbofish
                | TypeSpecKind::TypeLevelIf
                | TypeSpecKind::BindingType
                | TypeSpecKind::PipelineDepth => {
                    visit_const_generic(expr.as_ref(), ctx).map(hir::TypeExpression::ConstGeneric)
                }
            }
        }
    }
}

pub fn visit_type_spec(
    t: &Loc<ast::TypeSpec>,
    kind: &TypeSpecKind,
    ctx: &mut Context,
) -> Result<Loc<hir::TypeSpec>> {
    let trait_loc = if let SelfContext::TraitDefinition(TraitName::Named(name)) = &ctx.self_ctx {
        name.loc()
    } else {
        ().nowhere()
    };

    if matches!(ctx.self_ctx, SelfContext::TraitDefinition(_)) && t.is_self()? {
        return Ok(hir::TypeSpec::TraitSelf(().at_loc(&trait_loc)).at_loc(t));
    };

    let result = match &t.inner {
        ast::TypeSpec::Named(path, params) => {
            // Lookup the referenced type
            let (base_id, base_t) = ctx.symtab.lookup_type_symbol(path)?;

            // Check if the type is a declared type or a generic argument.
            match &base_t.inner {
                TypeSymbol::Declared(generic_args, _) => {
                    // We'll defer checking the validity of generic args to the type checker,
                    // but we still have to visit them now
                    let visited_params = params
                        // We can't flatten "through" Option<Loc<Vec<...>>>, so map it away.
                        .as_ref()
                        .map(|o| &o.inner)
                        .into_iter()
                        .flatten()
                        .map(|p| p.try_map_ref(|p| visit_type_expression(p, kind, ctx)))
                        .collect::<Result<Vec<_>>>()?;

                    if generic_args.len() != visited_params.len() {
                        Err(Diagnostic::error(
                            params
                                .as_ref()
                                .map(|p| ().at_loc(p))
                                .unwrap_or(().at_loc(t)),
                            "Wrong number of generic type parameters",
                        )
                        .primary_label(format!(
                            "Expected {} type parameter{}",
                            generic_args.len(),
                            if generic_args.len() != 1 { "s" } else { "" }
                        ))
                        .secondary_label(
                            if !generic_args.is_empty() {
                                ().between_locs(
                                    &generic_args[0],
                                    &generic_args[generic_args.len() - 1],
                                )
                            } else {
                                ().at_loc(&base_t)
                            },
                            format!(
                                "Because this has {} type parameter{}",
                                generic_args.len(),
                                if generic_args.len() != 1 { "s" } else { "" }
                            ),
                        ))
                    } else {
                        Ok(hir::TypeSpec::Declared(
                            base_id.at_loc(path),
                            visited_params,
                        ))
                    }
                }
                TypeSymbol::GenericArg { traits: _ } | TypeSymbol::GenericMeta(_) => {
                    // If this typename refers to a generic argument we need to make
                    // sure that no generic arguments are passed, as generic names
                    // can't have generic parameters

                    if let Some(params) = params {
                        Err(
                            Diagnostic::error(params, "Generic arguments given for a generic type")
                                .primary_label("Generic arguments not allowed here")
                                .secondary_label(base_t, format!("{path} is a generic type")),
                        )
                    } else {
                        Ok(hir::TypeSpec::Generic(base_id.at_loc(path)))
                    }
                }
                TypeSymbol::Alias(expr) => match &expr.inner {
                    TypeExpression::TypeSpec(spec) => Ok(spec.clone()),
                    TypeExpression::Integer(_) | TypeExpression::ConstGeneric(_) => {
                        Err(Diagnostic::error(
                            t,
                            "Type aliases to integers and const generics are currently unsupported",
                        )
                        .primary_label("Alias to non-type")
                        .secondary_label(expr, "Type alias points here"))
                    }
                },
            }
        }
        ast::TypeSpec::Array { inner, size } => {
            let inner = match visit_type_expression(inner, kind, ctx)? {
                hir::TypeExpression::TypeSpec(t) => Box::new(t.at_loc(inner)),
                _ => {
                    return Err(Diagnostic::error(
                        inner.as_ref(),
                        "Arrays elements must be types, not type level integers",
                    )
                    .primary_label("Non-type array element"))
                }
            };
            let size = Box::new(visit_type_expression(size, kind, ctx)?.at_loc(size));

            Ok(hir::TypeSpec::Array { inner, size })
        }
        ast::TypeSpec::Tuple(inner) => {
            let inner = inner
                .iter()
                .map(|p| match visit_type_expression(p, kind, ctx)? {
                    hir::TypeExpression::TypeSpec(t) => Ok(t.at_loc(p)),
                    _ => {
                        return Err(Diagnostic::error(
                            p,
                            "Tuple elements must be types, not type level integers",
                        )
                        .primary_label("Tuples cannot contain non-types"))
                    }
                })
                .collect::<Result<Vec<_>>>()?;

            // Check if this tuple is a port by checking if any of the contained types
            // are ports. If they are, retain the first one to use as a witness for this fact
            // for error reporting
            let transitive_port_witness = inner
                .iter()
                .map(|p| {
                    if p.is_port(ctx)? {
                        Ok(Some(p))
                    } else {
                        Ok(None)
                    }
                })
                .collect::<Result<Vec<_>>>()?
                .into_iter()
                .find_map(|x| x);

            if let Some(witness) = transitive_port_witness {
                // Since this type has 1 port, all members must be ports
                for ty in &inner {
                    if !ty.is_port(ctx)? {
                        return Err(Diagnostic::error(
                            ty,
                            "Cannot mix ports and non-ports in a tuple",
                        )
                        .primary_label("This is not a port")
                        .secondary_label(witness, "This is a port")
                        .note("A tuple must either contain only ports or no ports"));
                    }
                }
            }

            Ok(hir::TypeSpec::Tuple(inner))
        }
        ast::TypeSpec::Wire(inner) => {
            let inner = match visit_type_expression(inner, kind, ctx)? {
                hir::TypeExpression::TypeSpec(t) => t.at_loc(inner),
                _ => {
                    return Err(Diagnostic::error(
                        inner.as_ref(),
                        "Wire inner types must be types, not type level integers",
                    )
                    .primary_label("Wires cannot contain non-types"))
                }
            };

            if inner.is_port(&ctx)? {
                return Err(Diagnostic::from(error::WireOfPort {
                    full_type: t.loc(),
                    inner_type: inner.loc(),
                }));
            }

            Ok(hir::TypeSpec::Wire(Box::new(inner)))
        }
        ast::TypeSpec::Inverted(inner) => {
            let inner = match visit_type_expression(inner, kind, ctx)? {
                hir::TypeExpression::TypeSpec(t) => t.at_loc(inner),
                _ => {
                    return Err(Diagnostic::error(
                        inner.as_ref(),
                        "Inverted inner types must be types, not type level integers",
                    )
                    .primary_label("Non-type cannot be inverted"))
                }
            };

            if !inner.is_port(ctx)? {
                Err(Diagnostic::error(t, "A non-port type can not be inverted")
                    .primary_label("Inverting non-port")
                    .secondary_label(inner, "This is not a port"))
            } else {
                Ok(hir::TypeSpec::Inverted(Box::new(inner)))
            }
        }
        ast::TypeSpec::Wildcard => {
            let default_error = |message, primary| {
                Err(
                    Diagnostic::error(t, format!("{message} cannot have wildcards in their type"))
                        .primary_label(format!("Wildcard in {primary}")),
                )
            };
            match kind {
                TypeSpecKind::Argument => default_error("Argument types", "argument type"),
                TypeSpecKind::OutputType => default_error("Return types", "return type"),
                TypeSpecKind::ImplTrait => default_error("Implemented traits", "implemented trait"),
                TypeSpecKind::ImplTarget => default_error("Impl targets", "impl target"),
                TypeSpecKind::EnumMember => default_error("Enum members", "enum member"),
                TypeSpecKind::StructMember => default_error("Struct members", "struct member"),
                TypeSpecKind::PipelineDepth => default_error("Pipeline depth", "pipeline depth"),
                TypeSpecKind::TraitBound => {
                    default_error("Traits used in trait bound", "trait bound")
                }
                TypeSpecKind::TypeLevelIf | TypeSpecKind::Turbofish | TypeSpecKind::BindingType => {
                    Ok(hir::TypeSpec::Wildcard(t.loc()))
                }
            }
        }
    };

    Ok(result?.at_loc(t))
}

#[derive(Debug, Clone, PartialEq)]
pub enum SelfContext {
    /// `self` currently does not refer to anything
    FreeStanding,
    /// `self` refers to `TypeSpec` in an impl block for that type
    ImplBlock(Loc<hir::TypeSpec>),
    /// `self` refers to a trait implementor
    TraitDefinition(TraitName),
}

fn visit_parameter_list(
    l: &Loc<ParameterList>,
    ctx: &mut Context,
    no_mangle_all: Option<Loc<()>>,
) -> Result<Loc<hir::ParameterList>> {
    let mut arg_names: HashSet<Loc<Identifier>> = HashSet::new();
    let mut result = vec![];

    if let SelfContext::ImplBlock(_) = ctx.self_ctx {
        if l.self_.is_none() {
            // Suggest insertion after the first paren
            let mut diag = Diagnostic::error(l, "Method must take 'self' as the first parameter")
                .primary_label("Missing self");

            let suggest_msg = "Consider adding self";
            diag = if l.args.is_empty() {
                diag.span_suggest_replace(suggest_msg, l, "(self)")
            } else {
                diag.span_suggest_insert_before(suggest_msg, &l.args[0].1, "self, ")
            };
            return Err(diag);
        }
    }

    if let Some(self_loc) = l.self_ {
        match &ctx.self_ctx {
            SelfContext::FreeStanding => {
                return Err(Diagnostic::error(
                    self_loc,
                    "'self' cannot be used in free standing units",
                )
                .primary_label("not allowed here"))
            }
            SelfContext::ImplBlock(spec) => result.push(hir::Parameter {
                no_mangle: None,
                name: Identifier(String::from("self")).at_loc(&self_loc),
                ty: spec.clone(),
            }),
            // When visiting trait definitions, we don't need to add self to the
            // symtab at all since we won't be visiting unit bodies here.
            // NOTE: This will be incorrect if we add default impls for traits
            SelfContext::TraitDefinition(_) => result.push(hir::Parameter {
                no_mangle: None,
                name: Identifier(String::from("self")).at_loc(&self_loc),
                ty: hir::TypeSpec::TraitSelf(self_loc).at_loc(&self_loc),
            }),
        }
    }

    for (attrs, name, input_type) in &l.args {
        if let Some(prev) = arg_names.get(name) {
            return Err(
                Diagnostic::error(name, "Multiple arguments with the same name")
                    .primary_label(format!("{name} later declared here"))
                    .secondary_label(prev, format!("{name} previously declared here")),
            );
        }
        arg_names.insert(name.clone());
        let t = visit_type_spec(input_type, &TypeSpecKind::Argument, ctx)?;

        let mut attrs = attrs.clone();
        let no_mangle = attrs
            .consume_no_mangle()
            .map(|ident| ident.loc())
            .or(no_mangle_all);
        attrs.report_unused("a parameter")?;

        result.push(hir::Parameter {
            name: name.clone(),
            ty: t,
            no_mangle,
        });
    }
    Ok(hir::ParameterList(result).at_loc(l))
}

/// Builds a diagnostic for a `#[no_mangle(all)]`-marked unit with a non-unit output type.
fn build_no_mangle_all_output_diagnostic(
    head: &ast::UnitHead,
    output_type: &Loc<TypeSpec>,
    body_for_diagnostics: Option<&Loc<Expression>>,
) -> Diagnostic {
    let suffix_length = head
        .inputs
        .args
        .iter()
        .filter_map(|(_, name, _)| {
            if name.0.contains("out") {
                Some(name.0.len())
            } else {
                None
            }
        })
        .max()
        .unwrap_or(2)
        - 2;
    let suggested_name = format!("out{}", "_".repeat(suffix_length));
    let output_is_wire = output_type.to_string().starts_with("&");
    let suggested_type = format!(
        "inv {}{}",
        if output_is_wire {
            // ports shouldn't have duplicate & (thanks Astrid)
            ""
        } else {
            "&"
        },
        output_type
    );

    let mut diagnostic = Diagnostic::error(output_type, "Cannot apply `#[no_mangle(all)]`")
        .primary_label("Output types are always mangled");

    let output_arrow_span = &head.output_type.as_ref().unwrap().0.span;
    let output_type_full_span: FullSpan = output_type.into();
    let mut first_suggestion = SuggestionParts::new().part(
        (
            Span::new(output_arrow_span.start(), output_type_full_span.0.end()),
            output_type_full_span.1,
        ),
        "",
    );
    if head.inputs.args.is_empty() {
        let (span, file) = (head.inputs.span, head.inputs.file_id);
        first_suggestion = first_suggestion.part(
            (span, file),
            format!("({}: {})", suggested_name, suggested_type),
        );
    } else {
        let last_parameter = &head.inputs.args.last().unwrap().2;
        let (span, file) = (last_parameter.span, last_parameter.file_id);
        first_suggestion.push_part(
            (Span::new(span.end(), span.end()), file),
            format!(", {}: {}", suggested_name, suggested_type),
        );
    }

    diagnostic.push_span_suggest_multipart(
        "Consider replacing the output with an inverted input",
        first_suggestion,
    );

    // add the set suggestion for non-externs
    if let Some(block) = body_for_diagnostics {
        let block = block.assume_block();
        if let Some(result) = block.result.as_ref() {
            if output_is_wire {
                diagnostic = diagnostic.span_suggest_remove("Remember to `set` the inverted input instead of ending the block with an output", result);
            } else {
                let (span, file) = (result.span, result.file_id);
                diagnostic.push_span_suggest_multipart(
                    "...and `set` the inverted input to the return value",
                    SuggestionParts::new()
                        .part(
                            (Span::new(span.start(), span.start()), file),
                            format!("set {} = ", suggested_name),
                        )
                        .part((Span::new(span.end(), span.end()), file), ";"),
                );
            }
        }
    }

    diagnostic
}

/// Visit the head of an entity to generate an entity head
#[tracing::instrument(skip_all, fields(name=%head.name))]
pub fn unit_head(
    head: &ast::UnitHead,
    scope_type_params: &Option<Loc<Vec<Loc<TypeParam>>>>,
    scope_where_clauses: &[Loc<hir::WhereClause>],
    ctx: &mut Context,
    body_for_diagnostics: Option<&Loc<Expression>>,
) -> Result<hir::UnitHead> {
    ctx.symtab.new_scope();

    let scope_type_params = scope_type_params
        .as_ref()
        .map(Loc::strip_ref)
        .into_iter()
        .flatten()
        .map(|loc| loc.try_map_ref(|p| re_visit_type_param(p, ctx)))
        .collect::<Result<Vec<Loc<hir::TypeParam>>>>()?;

    let unit_type_params = head
        .type_params
        .as_ref()
        .map(Loc::strip_ref)
        .into_iter()
        .flatten()
        .map(|loc| loc.try_map_ref(|p| visit_type_param(p, ctx)))
        .collect::<Result<Vec<Loc<hir::TypeParam>>>>()?;

    let unit_where_clauses = visit_where_clauses(&head.where_clauses, ctx);

    let output_type = if let Some(output_type) = &head.output_type {
        Some(visit_type_spec(
            &output_type.1,
            &TypeSpecKind::OutputType,
            ctx,
        )?)
    } else {
        None
    };

    let no_mangle_all = head
        .attributes
        .0
        .iter()
        .find(|attribute| matches!(attribute.inner, Attribute::NoMangle { all: true }))
        .map(|attribute| ().at_loc(attribute));

    // we only care if we're trying to no_mangle_all a type with a non-unit output type
    if no_mangle_all.is_some()
        && output_type
            .as_ref()
            .map(|output_type| {
                !(matches!(&**output_type, TypeSpec::Tuple(inner) if inner.is_empty()))
            })
            .unwrap_or(false)
    {
        return Err(build_no_mangle_all_output_diagnostic(
            head,
            output_type.as_ref().unwrap(),
            body_for_diagnostics,
        ));
    }

    let inputs = visit_parameter_list(&head.inputs, ctx, no_mangle_all)?;

    // Check for ports in functions
    // We need to have the scope open to check this, but we also need to close
    // the scope if we fail here, so we'll store port_error in a variable
    let mut port_error = Ok(());

    if let ast::UnitKind::Function = head.unit_kind.inner {
        for (_, _, ty) in &head.inputs.args {
            if matches!(ctx.self_ctx, SelfContext::TraitDefinition(_)) && ty.is_self()? {
                continue;
            };

            if visit_type_spec(ty, &TypeSpecKind::Argument, ctx)?.is_port(&ctx)? {
                port_error = Err(Diagnostic::error(ty, "Port argument in function")
                    .primary_label("This is a port")
                    .note("Only entities and pipelines can take ports as arguments")
                    .span_suggest_replace(
                        "Consider making this an entity",
                        &head.unit_kind,
                        "entity",
                    ))
            }
        }
    }

    let unit_kind: Result<_> = head.unit_kind.try_map_ref(|k| {
        let inner = match k {
            ast::UnitKind::Function => hir::UnitKind::Function(hir::FunctionKind::Fn),
            ast::UnitKind::Entity => hir::UnitKind::Entity,
            ast::UnitKind::Pipeline(depth) => hir::UnitKind::Pipeline {
                depth: depth
                    .try_map_ref(|t| visit_type_expression(t, &TypeSpecKind::PipelineDepth, ctx))?,
                depth_typeexpr_id: ctx.idtracker.next(),
            },
        };
        Ok(inner)
    });

    ctx.symtab.close_scope();
    port_error?;
    let where_clauses = unit_where_clauses?
        .iter()
        .chain(scope_where_clauses.iter())
        .cloned()
        .collect();

    Ok(hir::UnitHead {
        name: head.name.clone(),
        inputs,
        output_type,
        unit_type_params,
        scope_type_params,
        unit_kind: unit_kind?,
        where_clauses,
        documentation: head.attributes.merge_docs(),
    })
}

pub fn visit_const_generic(
    t: &Loc<ast::Expression>,
    ctx: &mut Context,
) -> Result<Loc<ConstGeneric>> {
    let kind = match &t.inner {
        ast::Expression::Identifier(name) => {
            let (name, sym) = ctx.symtab.lookup_type_symbol(name)?;
            match &sym.inner {
                TypeSymbol::Declared(_, _) => {
                    return Err(Diagnostic::error(t, format!(
                            "{name} is not a type level integer but is used in a const generic expression."
                        ),
                    )
                        .primary_label(format!("Expected type level integer"))
                    .secondary_label(&sym, format!("{name} is defined here")))
                }
                TypeSymbol::GenericArg { traits: _ }=> {
                    return Err(Diagnostic::error(
                        t,
                        format!(
                            "{name} is not a type level integer but is used in a const generic expression."
                        ))
                        .primary_label("Expected type level integer")
                        .secondary_label(&sym, format!("{name} is defined here"))
                        .span_suggest_insert_before(
                            "Try making the generic an integer",
                        &sym,
                        "#int ",
                    )
                    .span_suggest_insert_before(
                        "or an unsigned integer",
                            &sym,
                            "#uint ",
                        ))
                }
                TypeSymbol::GenericMeta(_) => {
                    ConstGeneric::Name(name.at_loc(t))
                },
                TypeSymbol::Alias(a) => {
                    return Err(Diagnostic::error(t, "Type aliases are not supported in const generics").primary_label("Type alias in const generic")
                    .secondary_label(a, "Alias defined here"))
                }
            }
        }
        ast::Expression::IntLiteral(val) => ConstGeneric::Const(val.clone().as_signed()),
        ast::Expression::BinaryOperator(lhs, op, rhs) => {
            let lhs = visit_const_generic(lhs, ctx)?;
            let rhs = visit_const_generic(rhs, ctx)?;

            match &op.inner {
                ast::BinaryOperator::Add => ConstGeneric::Add(Box::new(lhs), Box::new(rhs)),
                ast::BinaryOperator::Sub => ConstGeneric::Sub(Box::new(lhs), Box::new(rhs)),
                ast::BinaryOperator::Mul => ConstGeneric::Mul(Box::new(lhs), Box::new(rhs)),
                ast::BinaryOperator::Equals => ConstGeneric::Eq(Box::new(lhs), Box::new(rhs)),
                ast::BinaryOperator::NotEquals => ConstGeneric::NotEq(Box::new(lhs), Box::new(rhs)),
                ast::BinaryOperator::Div => ConstGeneric::Div(Box::new(lhs), Box::new(rhs)),
                ast::BinaryOperator::Mod => ConstGeneric::Mod(Box::new(lhs), Box::new(rhs)),
                other => {
                    return Err(Diagnostic::error(
                        op,
                        format!("Operator `{other}` is not supported in a type expression"),
                    )
                    .primary_label("Not supported in a type expression"))
                }
            }
        }
        ast::Expression::UnaryOperator(op, operand) => {
            let operand = visit_const_generic(operand, ctx)?;

            match &op.inner {
                ast::UnaryOperator::Sub => ConstGeneric::Sub(
                    Box::new(ConstGeneric::Const(BigInt::zero()).at_loc(&operand)),
                    Box::new(operand),
                ),
                other => {
                    return Err(Diagnostic::error(
                        t,
                        format!("Operator `{other}` is not supported in a type expression"),
                    )
                    .primary_label("Not supported in a type expression"))
                }
            }
        }
        ast::Expression::Call {
            kind: CallKind::Function,
            callee,
            args,
            turbofish: None,
        } => match callee.as_strs().as_slice() {
            ["uint_bits_to_fit"] => match &args.inner {
                ast::ArgumentList::Positional(a) => {
                    if a.len() != 1 {
                        return Err(Diagnostic::error(
                            args,
                            format!("This function takes one argument, {} provided", a.len()),
                        )
                        .primary_label("Expected 1 argument"));
                    } else {
                        let arg = visit_const_generic(&a[0], ctx)?;

                        ConstGeneric::UintBitsToFit(Box::new(arg))
                    }
                }
                ast::ArgumentList::Named(_) => {
                    return Err(Diagnostic::error(
                        t,
                        "Passing arguments by name is unsupported in type expressions",
                    )
                    .primary_label("Arguments passed by name in type expression"))
                }
            },
            _ => {
                return Err(Diagnostic::error(
                    callee,
                    format!("{callee} cannot be evaluated in a type expression"),
                )
                .primary_label("Not supported in a type expression"))
            }
        },
        _ => {
            return Err(Diagnostic::error(
                t,
                format!("This expression is not supported in a type expression"),
            )
            .primary_label("Not supported in a type expression"))
        }
    };

    Ok(kind.at_loc(t))
}

pub fn visit_where_clauses(
    where_clauses: &[WhereClause],
    ctx: &mut Context,
) -> Result<Vec<Loc<hir::WhereClause>>> {
    let mut visited_where_clauses: Vec<Loc<hir::WhereClause>> = vec![];
    for where_clause in where_clauses {
        match where_clause {
            WhereClause::GenericInt { target, expression } => {
                let make_diag = |primary| {
                    Diagnostic::error(
                        target,
                        format!("Expected `{}` to be a type level integer", target),
                    )
                    .primary_label(primary)
                    .secondary_label(expression, "This is an integer constraint")
                };
                let (name_id, sym) = match ctx.symtab.lookup_type_symbol(target) {
                    Ok(res) => res,
                    Err(LookupError::NotATypeSymbol(_, thing)) => {
                        return Err(make_diag(format!("`{target}` is not a type level integer"))
                            .secondary_label(
                                thing.loc(),
                                format!("`{}` is a {} declared here", target, thing.kind_string()),
                            ))
                    }
                    Err(e) => return Err(e.into()),
                };
                match &sym.inner {
                    TypeSymbol::GenericMeta(_) => {
                        let clause = hir::WhereClause::Int {
                            target: name_id.at_loc(target),
                            constraint: visit_const_generic(expression, ctx)?,
                        }
                        .between_locs(target, expression);

                        visited_where_clauses.push(clause);
                    }
                    TypeSymbol::GenericArg { .. } => {
                        return Err(
                            make_diag("Generic type in generic integer constraint".into())
                                .secondary_label(
                                    sym.clone(),
                                    format!("`{target}` is a generic type"),
                                )
                                .span_suggest_insert_before(
                                    "Try making the generic an integer",
                                    &sym,
                                    "#int ",
                                )
                                .span_suggest_insert_before(
                                    "or an unsigned integer",
                                    &sym,
                                    "#uint ",
                                ),
                        );
                    }
                    TypeSymbol::Declared { .. } => {
                        return Err(make_diag(
                            "Declared type in generic integer constraint".into(),
                        )
                        .secondary_label(sym, format!("`{target}` is a type declared here")));
                    }
                    TypeSymbol::Alias(a) => {
                        return Err(Diagnostic::error(
                                &sym, "Type aliases are not supported in where clauses"
                            )
                            .primary_label("Type alias in where clause")
                            .secondary_label(a, "Alias defined here")
                            .note(
                                "This is a soft limitation in the compiler. If you need this feature, open an issue at https://gitlab.com/spade-lang/spade/"
                            )
                        )
                    }
                }
            }
            WhereClause::TraitBounds { target, traits } => {
                let make_diag = |primary| {
                    Diagnostic::error(
                        target,
                        format!("Expected `{}` to be a generic type", target),
                    )
                    .primary_label(primary)
                };
                let (name_id, sym) = match ctx.symtab.lookup_type_symbol(where_clause.target()) {
                    Ok(res) => res,
                    Err(LookupError::NotATypeSymbol(path, thing)) => {
                        return Err(make_diag(format!("`{target}` is not a type symbol"))
                            .secondary_label(
                                path,
                                format!("`{}` is {} declared here", target, thing.kind_string()),
                            ));
                    }
                    Err(e) => return Err(e.into()),
                };
                match &sym.inner {
                    TypeSymbol::GenericArg { .. } | TypeSymbol::GenericMeta(MetaType::Type) => {
                        let traits = traits
                            .iter()
                            .map(|t| visit_trait_spec(t, &TypeSpecKind::TraitBound, ctx))
                            .collect::<Result<Vec<_>>>()?;

                        ctx.symtab.add_traits_to_generic(&name_id, traits.clone())?;

                        visited_where_clauses.push(
                            hir::WhereClause::Type {
                                target: name_id.at_loc(target),
                                traits,
                            }
                            .at_loc(target),
                        );
                    }
                    TypeSymbol::GenericMeta(_) => {
                        return Err(make_diag("Generic int in trait bound".into())
                            .secondary_label(sym, format!("{target} is a generic int")));
                    }
                    TypeSymbol::Declared { .. } => {
                        return Err(make_diag("Declared type in trait bound".into())
                            .secondary_label(sym, format!("{target} is a type declared here")));
                    }
                    TypeSymbol::Alias(a) => {
                        return Err(Diagnostic::error(
                                &sym, "Type aliases are not supported in where clauses"
                            )
                            .primary_label("Type alias in where clause")
                            .secondary_label(a, "Alias defined here")
                            .note(
                                "This is a soft limitation in the compiler. If you need this feature, open an issue at https://gitlab.com/spade-lang/spade/"
                            )
                        )
                    }
                };
            }
        }
    }
    Ok(visited_where_clauses)
}

/// The `extra_path` parameter allows specifying an extra path prepended to
/// the name of the entity. This is used by impl blocks to append a unique namespace
#[tracing::instrument(skip_all, fields(%unit.head.name, %unit.head.unit_kind))]
pub fn visit_unit(
    extra_path: Option<Path>,
    unit: &Loc<ast::Unit>,
    scope_type_params: &Option<Loc<Vec<Loc<ast::TypeParam>>>>,
    ctx: &mut Context,
) -> Result<hir::Item> {
    let ast::Unit {
        head:
            ast::UnitHead {
                extern_token: _,
                name,
                attributes,
                inputs: _,
                output_type: _,
                unit_kind: _,
                type_params,
                where_clauses: _,
            },
        body,
    } = &unit.inner;

    ctx.symtab.new_scope();

    let path = extra_path
        .unwrap_or(Path(vec![]))
        .join(Path(vec![name.clone()]))
        .at_loc(&name.loc());

    let (id, head) = ctx
        .symtab
        .lookup_unit(&path)
        .map_err(|_| {
            ctx.symtab.print_symbols();
            println!("Failed to find {path} in symtab")
        })
        .expect("Attempting to lower an entity that has not been added to the symtab previously");

    let mut unit_name = if type_params.is_some() || scope_type_params.is_some() {
        hir::UnitName::WithID(id.clone().at_loc(name))
    } else {
        hir::UnitName::FullPath(id.clone().at_loc(name))
    };

    let mut wal_suffix = None;

    let attributes = attributes.lower(&mut |attr: &Loc<ast::Attribute>| match &attr.inner {
        ast::Attribute::Optimize { passes } => Ok(Some(hir::Attribute::Optimize {
            passes: passes.clone(),
        })),
        ast::Attribute::NoMangle { .. } => {
            if let Some(generic_list) = type_params {
                // if it's a verilog extern (so `body.is_none()`), then we allow generics insofar
                // as they are numbers (checked later on)
                if body.is_some() {
                    Err(
                        Diagnostic::error(attr, "no_mangle is not allowed on generic units")
                            .primary_label("no_mangle not allowed here")
                            .secondary_label(generic_list, "Because this unit is generic"),
                    )
                } else {
                    // yucky code duplication
                    unit_name = hir::UnitName::Unmangled(name.0.clone(), id.clone().at_loc(name));
                    Ok(None)
                }
            } else if let Some(generic_list) = scope_type_params {
                Err(Diagnostic::error(
                    attr,
                    "no_mangle is not allowed on units inside generic impls",
                )
                .primary_label("no_mangle not allowed here")
                .secondary_label(generic_list, "Because this impl is generic"))
            } else {
                unit_name = hir::UnitName::Unmangled(name.0.clone(), id.clone().at_loc(name));
                Ok(None)
            }
        }
        ast::Attribute::WalSuffix { suffix } => {
            if body.is_none() {
                return Err(
                    Diagnostic::error(attr, "wal_suffix is not allowed on `extern` units")
                        .primary_label("Not allowed on `extern` units")
                        .secondary_label(unit.head.extern_token.unwrap(), "This unit is `extern`"),
                );
            }

            wal_suffix = Some(suffix.clone());
            Ok(None)
        }
        ast::Attribute::Documentation { .. } => Ok(None),
        _ => Err(attr.report_unused("a unit")),
    })?;

    // If this is a extern entity
    if body.is_none() {
        return Ok(hir::Item::ExternUnit(unit_name, head));
    }

    // Add the inputs to the symtab
    let inputs = head
        .inputs
        .0
        .iter()
        .map(
            |hir::Parameter {
                 name: ident,
                 ty,
                 no_mangle: _,
             }| {
                (
                    ctx.symtab.add_local_variable(ident.clone()).at_loc(ident),
                    ty.clone(),
                )
            },
        )
        .collect::<Vec<_>>();

    // Add the type params to the symtab to make them visible in the body
    for param in head.get_type_params() {
        let hir::TypeParam {
            ident,
            name_id,
            trait_bounds: _,
            meta: _,
        } = param.inner;
        ctx.symtab.re_add_type(ident, name_id)
    }

    ctx.pipeline_ctx = maybe_perform_pipelining_tasks(unit, &head, ctx)?;

    let mut body = body.as_ref().unwrap().try_visit(visit_expression, ctx)?;

    // Add wal_suffixes for the signals if requested. This creates new statements
    // which we'll add to the end of the body
    if let Some(suffix) = wal_suffix {
        match &mut body.kind {
            hir::ExprKind::Block(block) => {
                block.statements.append(
                    &mut inputs
                        .iter()
                        .map(|(name, _)| {
                            hir::Statement::WalSuffixed {
                                suffix: suffix.inner.clone(),
                                target: name.clone(),
                            }
                            .at_loc(&suffix)
                        })
                        .collect(),
                );
            }
            _ => diag_bail!(body, "Unit body was not block"),
        }
    }

    check_for_undefined(ctx)?;

    ctx.symtab.close_scope();

    Ok(hir::Item::Unit(expand_type_level_if(
        hir::Unit {
            name: unit_name,
            head: head.clone().inner,
            attributes,
            inputs,
            body,
        }
        .at_loc(unit),
        ctx,
    )?))
}

#[tracing::instrument(skip_all, fields(name=?trait_spec.path))]
pub fn visit_trait_spec(
    trait_spec: &Loc<ast::TraitSpec>,
    type_spec_kind: &TypeSpecKind,
    ctx: &mut Context,
) -> Result<Loc<hir::TraitSpec>> {
    let (name_id, loc) = match ctx.symtab.lookup_trait(&trait_spec.inner.path) {
        Ok(res) => res,
        Err(LookupError::IsAType(path)) => {
            let (_, loc) = ctx.symtab.lookup_type_symbol(&path)?;
            return Err(Diagnostic::error(
                path.clone(),
                format!("Unexpected type {}, expected a trait", path.inner),
            )
            .primary_label("Unexpected type")
            .secondary_label(loc, format!("Type {} defined here", path.inner)));
        }
        Err(err) => return Err(err.into()),
    };
    let name = TraitName::Named(name_id.at_loc(&loc));
    let type_params = match &trait_spec.inner.type_params {
        Some(params) => Some(params.try_map_ref(|params| {
            params
                .iter()
                .map(|param| param.try_map_ref(|te| visit_type_expression(te, type_spec_kind, ctx)))
                .collect::<Result<_>>()
        })?),
        None => None,
    };
    Ok(hir::TraitSpec { name, type_params }.at_loc(trait_spec))
}

#[tracing::instrument(skip_all, fields(name=?item.name()))]
pub fn visit_item(item: &ast::Item, ctx: &mut Context) -> Result<Vec<hir::Item>> {
    match item {
        ast::Item::Unit(u) => Ok(vec![visit_unit(None, u, &None, ctx)?]),
        ast::Item::TraitDef(_) => {
            // Global symbol lowering already visits traits
            event!(Level::INFO, "Trait definition");
            Ok(vec![])
        }
        ast::Item::Type(_) => {
            // Global symbol lowering already visits type declarations
            event!(Level::INFO, "Type definition");
            Ok(vec![])
        }
        ast::Item::ImplBlock(block) => visit_impl(block, ctx),
        ast::Item::ExternalMod(_) => Ok(vec![]),
        ast::Item::Module(m) => {
            ctx.symtab.push_namespace(m.name.clone());
            let result = visit_module(m, ctx);
            ctx.symtab.pop_namespace();
            result.map(|_| vec![])
        }
        // We can leave the forbidden slice empty, because even after resolving to itself for the first time, it will add itself as forbidden for the next time
        ast::Item::Use(s) => match ctx.symtab.lookup_id(&s.path, &[]) {
            Ok(_) => Ok(vec![]),
            Err(lookup_error) => Err(lookup_error.into()),
        },
    }
}

#[tracing::instrument(skip_all, fields(module.name = %module.name.inner))]
pub fn visit_module(module: &ast::Module, ctx: &mut Context) -> Result<()> {
    let path = &ctx
        .symtab
        .current_namespace()
        .clone()
        .at_loc(&module.name.loc());
    let id = ctx
        .symtab
        .lookup_id(path, &[])
        .map_err(|_| {
            ctx.symtab.print_symbols();
            println!("Failed to find {path} in symtab")
        })
        .expect("Attempting to lower a module that has not been added to the symtab previously");

    let documentation = module.body.documentation.join("\n");

    ctx.item_list.modules.insert(
        id.clone(),
        Module {
            name: id.at_loc(&module.name),
            documentation,
        },
    );

    visit_module_body(&module.body, ctx)
}

#[tracing::instrument(skip_all)]
pub fn visit_module_body(body: &ast::ModuleBody, ctx: &mut Context) -> Result<()> {
    for i in &body.members {
        for item in visit_item(i, ctx)? {
            match item {
                hir::Item::Unit(u) => ctx
                    .item_list
                    .add_executable(u.name.name_id().clone(), ExecutableItem::Unit(u))?,

                hir::Item::ExternUnit(name, head) => ctx.item_list.add_executable(
                    name.name_id().clone(),
                    ExecutableItem::ExternUnit(name, head),
                )?,
            }
        }
    }

    Ok(())
}

fn try_lookup_enum_variant(path: &Loc<Path>, ctx: &mut Context) -> Result<hir::PatternKind> {
    let (name_id, variant) = ctx.symtab.lookup_enum_variant(path)?;
    if variant.inner.params.argument_num() == 0 {
        Ok(hir::PatternKind::Type(name_id.at_loc(path), vec![]))
    } else {
        let expected = variant.inner.params.argument_num();
        Err(Diagnostic::from(error::PatternListLengthMismatch {
            expected,
            got: 0,
            at: path.loc(),
            for_what: Some("enum variant".to_string()),
        })
        // FIXME: actual names of variant arguments?
        .span_suggest_insert_after(
            "help: Add arguments here",
            path.loc(),
            format!(
                "({})",
                std::iter::repeat("_")
                    .take(expected)
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        ))
    }
}

pub fn visit_pattern(p: &ast::Pattern, ctx: &mut Context) -> Result<hir::Pattern> {
    let kind = match &p {
        ast::Pattern::Integer(val) => hir::PatternKind::Integer(val.clone().as_signed()),
        ast::Pattern::Bool(val) => hir::PatternKind::Bool(*val),
        ast::Pattern::Path(path) => {
            match (try_lookup_enum_variant(path, ctx), path.inner.0.as_slice()) {
                (Ok(kind), _) => kind,
                (_, [ident]) => {
                    // Check if this is declaring a variable
                    let (name_id, pre_declared) =
                        if let Some(state) = ctx.symtab.get_declaration(ident) {
                            match state.inner {
                                DeclarationState::Undefined(id) => {
                                    ctx.symtab
                                        .mark_declaration_defined(ident.clone(), ident.loc());
                                    (id, true)
                                }
                                DeclarationState::Undecleared(id) => {
                                    ctx.symtab.add_thing_with_name_id(
                                        id.clone(),
                                        Thing::Variable(ident.clone()),
                                    );
                                    ctx.symtab
                                        .mark_declaration_defined(ident.clone(), ident.loc());
                                    (id, true)
                                }
                                DeclarationState::Defined(previous) => {
                                    return Err(Diagnostic::error(
                                        ident,
                                        format!("{ident} was already defined"),
                                    )
                                    .secondary_label(previous, "First defined here")
                                    .primary_label("Later defined here")
                                    .secondary_label(state.loc(), format!("{ident} declared here"))
                                    .note("Declared variables can only be defined once"));
                                }
                            }
                        } else {
                            (
                                ctx.symtab.add_thing(
                                    Path::ident(ident.clone()),
                                    Thing::Variable(ident.clone()),
                                ),
                                false,
                            )
                        };

                    hir::PatternKind::Name {
                        name: name_id.at_loc(ident),
                        pre_declared,
                    }
                }
                (_, []) => unreachable!(),
                (Err(e), _) => return Err(e),
            }
        }
        ast::Pattern::Tuple(pattern) => {
            let inner = pattern
                .iter()
                .map(|p| p.try_map_ref(|p| visit_pattern(p, ctx)))
                .collect::<Result<_>>()?;
            hir::PatternKind::Tuple(inner)
        }
        ast::Pattern::Array(patterns) => {
            let inner = patterns
                .iter()
                .map(|p| p.try_map_ref(|p| visit_pattern(p, ctx)))
                .collect::<Result<_>>()?;
            hir::PatternKind::Array(inner)
        }
        ast::Pattern::Type(path, args) => {
            // Look up the name to see if it's an enum variant.
            let (name_id, p) = ctx.symtab.lookup_patternable_type(path)?;
            match &args.inner {
                ast::ArgumentPattern::Named(patterns) => {
                    let mut bound = HashSet::<Loc<Identifier>>::new();
                    let mut unbound = p
                        .params
                        .0
                        .iter()
                        .map(
                            |hir::Parameter {
                                 name: ident,
                                 ty: _,
                                 no_mangle: _,
                             }| ident.inner.clone(),
                        )
                        .collect::<HashSet<_>>();

                    let mut patterns = patterns
                        .iter()
                        .map(|(target, pattern)| {
                            let ast_pattern = pattern.as_ref().cloned().unwrap_or_else(|| {
                                ast::Pattern::Path(Path(vec![target.clone()]).at_loc(target))
                                    .at_loc(target)
                            });
                            let new_pattern = visit_pattern(&ast_pattern, ctx)?;
                            // Check if this is a new binding
                            if let Some(prev) = bound.get(target) {
                                return Err(Diagnostic::from(
                                    ArgumentError::DuplicateNamedBindings {
                                        new: target.clone(),
                                        prev_loc: prev.loc(),
                                    },
                                ));
                            }
                            bound.insert(target.clone());
                            if unbound.take(target).is_none() {
                                return Err(Diagnostic::from(ArgumentError::NoSuchArgument {
                                    name: target.clone(),
                                }));
                            }

                            let kind = match pattern {
                                Some(_) => hir::ArgumentKind::Named,
                                None => hir::ArgumentKind::ShortNamed,
                            };

                            Ok(hir::PatternArgument {
                                target: target.clone(),
                                value: new_pattern.at_loc(&ast_pattern),
                                kind,
                            })
                        })
                        .collect::<Result<Vec<_>>>()?;

                    if !unbound.is_empty() {
                        return Err(Diagnostic::from(ArgumentError::MissingArguments {
                            missing: unbound.into_iter().collect(),
                            at: args.loc(),
                        }));
                    }

                    patterns.sort_by_cached_key(|arg| p.params.arg_index(&arg.target).unwrap());

                    hir::PatternKind::Type(name_id.at_loc(path), patterns)
                }
                ast::ArgumentPattern::Positional(patterns) => {
                    // Ensure we have the correct amount of arguments
                    if p.params.argument_num() != patterns.len() {
                        return Err(Diagnostic::from(error::PatternListLengthMismatch {
                            expected: p.params.argument_num(),
                            got: patterns.len(),
                            at: args.loc(),
                            for_what: None,
                        }));
                    }

                    let patterns = patterns
                        .iter()
                        .zip(p.params.0.iter())
                        .map(|(p, arg)| {
                            let pat = p.try_map_ref(|p| visit_pattern(p, ctx))?;
                            Ok(hir::PatternArgument {
                                target: arg.name.clone(),
                                value: pat,
                                kind: hir::ArgumentKind::Positional,
                            })
                        })
                        .collect::<Result<Vec<_>>>()?;

                    hir::PatternKind::Type(name_id.at_loc(path), patterns)
                }
            }
        }
    };
    Ok(kind.with_id(ctx.idtracker.next()))
}

fn visit_statement(s: &Loc<ast::Statement>, ctx: &mut Context) -> Result<Vec<Loc<hir::Statement>>> {
    match &s.inner {
        ast::Statement::Declaration(names) => {
            let names = names
                .iter()
                .map(|name| {
                    ctx.symtab
                        .add_declaration(name.clone())
                        .map(|decl| decl.at_loc(name))
                })
                .collect::<Result<Vec<_>>>()?;

            Ok(vec![hir::Statement::Declaration(names).at_loc(s)])
        }
        ast::Statement::Binding(Binding {
            pattern,
            ty,
            value,
            attrs,
        }) => {
            let mut stmts = vec![];

            let hir_type = if let Some(t) = ty {
                Some(visit_type_spec(t, &TypeSpecKind::BindingType, ctx)?)
            } else {
                None
            };

            let value = value.try_visit(visit_expression, ctx)?;

            let pattern = pattern.try_visit(visit_pattern, ctx)?;

            let mut wal_trace = None;
            attrs.lower(&mut |attr| match &attr.inner {
                ast::Attribute::WalTrace { clk, rst } => {
                    wal_trace = Some(
                        WalTrace {
                            clk: clk
                                .as_ref()
                                .map(|x| x.try_map_ref(|x| visit_expression(x, ctx)))
                                .transpose()?,
                            rst: rst
                                .as_ref()
                                .map(|x| x.try_map_ref(|x| visit_expression(x, ctx)))
                                .transpose()?,
                        }
                        .at_loc(attr),
                    );
                    Ok(None)
                }
                ast::Attribute::WalSuffix { suffix } => {
                    // All names in the pattern should have the suffix applied to them
                    for name in pattern.get_names() {
                        stmts.push(
                            hir::Statement::WalSuffixed {
                                suffix: suffix.inner.clone(),
                                target: name.clone(),
                            }
                            .at_loc(suffix),
                        );
                    }
                    Ok(None)
                }
                ast::Attribute::NoMangle { .. }
                | ast::Attribute::Fsm { .. }
                | ast::Attribute::Optimize { .. }
                | ast::Attribute::Documentation { .. }
                | ast::Attribute::WalTraceable { .. } => Err(attr.report_unused("let binding")),
            })?;

            stmts.push(
                hir::Statement::Binding(hir::Binding {
                    pattern,
                    ty: hir_type,
                    value,
                    wal_trace,
                })
                .at_loc(s),
            );
            Ok(stmts)
        }
        ast::Statement::Expression(expr) => {
            let value = expr.try_visit(visit_expression, ctx)?;
            Ok(vec![hir::Statement::Expression(value).at_loc(expr)])
        }
        ast::Statement::Register(inner) => visit_register(inner, ctx),
        ast::Statement::PipelineRegMarker(count, cond) => {
            let cond = match cond {
                Some(cond) => Some(cond.try_map_ref(|c| visit_expression(c, ctx))?),
                None => None,
            };

            let extra = match (count, cond) {
                (None, None) => None,
                (Some(count), None) => Some(hir::PipelineRegMarkerExtra::Count {
                    count: count.try_map_ref(|c| {
                        visit_type_expression(c, &TypeSpecKind::PipelineDepth, ctx)
                    })?,
                    count_typeexpr_id: ctx.idtracker.next(),
                }),
                (None, Some(cond)) => Some(hir::PipelineRegMarkerExtra::Condition(cond)),
                (Some(count), Some(cond)) => {
                    return Err(Diagnostic::error(
                        count,
                        "Multiple registers with conditions can not be defined",
                    )
                    .primary_label("Multiple registers not allowed")
                    .secondary_label(cond, "Condition specified here")
                    .help("Consider splitting into two reg statements"));
                }
            };

            Ok(vec![hir::Statement::PipelineRegMarker(extra).at_loc(s)])
        }
        ast::Statement::Label(name) => {
            // NOTE: pipeline labels are lowered in visit_pipeline
            let (name, sym) = ctx
                .symtab
                .lookup_type_symbol(&Path::ident(name.clone()).at_loc(name))?;
            Ok(vec![hir::Statement::Label(name.at_loc(&sym)).at_loc(s)])
        }
        ast::Statement::Assert(expr) => {
            let expr = expr.try_visit(visit_expression, ctx)?;

            Ok(vec![hir::Statement::Assert(expr).at_loc(s)])
        }
        ast::Statement::Set { target, value } => {
            let target = target.try_visit(visit_expression, ctx)?;
            let value = value.try_visit(visit_expression, ctx)?;

            Ok(vec![hir::Statement::Set { target, value }.at_loc(s)])
        }
    }
}

#[tracing::instrument(skip_all)]
fn visit_argument_list(
    arguments: &ast::ArgumentList,
    ctx: &mut Context,
) -> Result<hir::ArgumentList<hir::Expression>> {
    match arguments {
        ast::ArgumentList::Positional(args) => {
            let inner = args
                .iter()
                .map(|arg| arg.try_visit(visit_expression, ctx))
                .collect::<Result<_>>()?;

            Ok(hir::ArgumentList::Positional(inner))
        }
        ast::ArgumentList::Named(args) => {
            let inner = args
                .iter()
                .map(|arg| match arg {
                    ast::NamedArgument::Full(name, expr) => {
                        Ok(hir::expression::NamedArgument::Full(
                            name.clone(),
                            expr.try_visit(visit_expression, ctx)?,
                        ))
                    }
                    ast::NamedArgument::Short(name) => {
                        let expr =
                            ast::Expression::Identifier(Path(vec![name.clone()]).at_loc(name))
                                .at_loc(name);

                        Ok(hir::expression::NamedArgument::Short(
                            name.clone(),
                            expr.try_visit(visit_expression, ctx)?,
                        ))
                    }
                })
                .collect::<Result<_>>()?;

            Ok(hir::ArgumentList::Named(inner))
        }
    }
}

pub fn visit_call_kind(
    kind: &ast::CallKind,
    ctx: &mut Context,
) -> Result<hir::expression::CallKind> {
    Ok(match kind {
        ast::CallKind::Function => hir::expression::CallKind::Function,
        ast::CallKind::Entity(loc) => hir::expression::CallKind::Entity(*loc),
        ast::CallKind::Pipeline(loc, depth) => {
            let depth = depth
                .try_map_ref(|e| visit_type_expression(e, &TypeSpecKind::PipelineDepth, ctx))?;
            hir::expression::CallKind::Pipeline {
                inst_loc: *loc,
                depth,
                depth_typeexpr_id: ctx.idtracker.next(),
            }
        }
    })
}

pub fn visit_turbofish(
    t: &Loc<ast::TurbofishInner>,
    ctx: &mut Context,
) -> Result<Loc<hir::ArgumentList<TypeExpression>>> {
    t.try_map_ref(|args| match args {
        ast::TurbofishInner::Named(fishes) => fishes
            .iter()
            .map(|fish| match &fish.inner {
                ast::NamedTurbofish::Short(name) => {
                    let arg = ast::TypeExpression::TypeSpec(Box::new(
                        ast::TypeSpec::Named(Path(vec![name.clone()]).at_loc(name), None)
                            .at_loc(name),
                    ));

                    let arg =
                        visit_type_expression(&arg, &TypeSpecKind::Turbofish, ctx)?.at_loc(name);
                    Ok(hir::expression::NamedArgument::Short(name.clone(), arg))
                }
                ast::NamedTurbofish::Full(name, arg) => {
                    let arg =
                        visit_type_expression(arg, &TypeSpecKind::Turbofish, ctx)?.at_loc(arg);
                    Ok(hir::expression::NamedArgument::Full(name.clone(), arg))
                }
            })
            .collect::<Result<Vec<_>>>()
            .map(|params| hir::ArgumentList::Named(params)),
        ast::TurbofishInner::Positional(args) => args
            .iter()
            .map(|arg| {
                arg.try_map_ref(|arg| visit_type_expression(arg, &TypeSpecKind::Turbofish, ctx))
            })
            .collect::<Result<_>>()
            .map(hir::ArgumentList::Positional),
    })
}

#[recursive]
#[tracing::instrument(skip_all, fields(kind=e.variant_str()))]
pub fn visit_expression(e: &ast::Expression, ctx: &mut Context) -> Result<hir::Expression> {
    let new_id = ctx.idtracker.next();

    match e {
        ast::Expression::IntLiteral(val) => {
            let kind = match val {
                ast::IntLiteral::Unsized(_) => IntLiteralKind::Unsized,
                ast::IntLiteral::Signed { val: _, size } => IntLiteralKind::Signed(size.clone()),
                ast::IntLiteral::Unsigned { val: _, size } => {
                    IntLiteralKind::Unsigned(size.clone())
                }
            };
            Ok(hir::ExprKind::IntLiteral(val.clone().as_signed(), kind))
        }
        ast::Expression::BoolLiteral(val) => Ok(hir::ExprKind::BoolLiteral(*val)),
        ast::Expression::BitLiteral(lit) => {
            let result = match lit {
                ast::BitLiteral::Low => hir::expression::BitLiteral::Low,
                ast::BitLiteral::High => hir::expression::BitLiteral::High,
                ast::BitLiteral::HighImp => hir::expression::BitLiteral::HighImp,
            };
            Ok(hir::ExprKind::BitLiteral(result))
        }
        ast::Expression::CreatePorts => Ok(hir::ExprKind::CreatePorts),
        ast::Expression::BinaryOperator(lhs, tok, rhs) => {
            let lhs = lhs.try_visit(visit_expression, ctx)?;
            let rhs = rhs.try_visit(visit_expression, ctx)?;

            let operator = |op: BinaryOperator| {
                hir::ExprKind::BinaryOperator(Box::new(lhs), op.at_loc(tok), Box::new(rhs))
            };

            match tok.inner {
                ast::BinaryOperator::Add => Ok(operator(BinaryOperator::Add)),
                ast::BinaryOperator::Sub => Ok(operator(BinaryOperator::Sub)),
                ast::BinaryOperator::Mul => Ok(operator(BinaryOperator::Mul)),
                ast::BinaryOperator::Div => Ok(operator(BinaryOperator::Div)),
                ast::BinaryOperator::Mod => Ok(operator(BinaryOperator::Mod)),
                ast::BinaryOperator::Equals => Ok(operator(BinaryOperator::Eq)),
                ast::BinaryOperator::NotEquals => Ok(operator(BinaryOperator::NotEq)),
                ast::BinaryOperator::Gt => Ok(operator(BinaryOperator::Gt)),
                ast::BinaryOperator::Lt => Ok(operator(BinaryOperator::Lt)),
                ast::BinaryOperator::Ge => Ok(operator(BinaryOperator::Ge)),
                ast::BinaryOperator::Le => Ok(operator(BinaryOperator::Le)),
                ast::BinaryOperator::LeftShift => Ok(operator(BinaryOperator::LeftShift)),
                ast::BinaryOperator::RightShift => Ok(operator(BinaryOperator::RightShift)),
                ast::BinaryOperator::ArithmeticRightShift => {
                    Ok(operator(BinaryOperator::ArithmeticRightShift))
                }
                ast::BinaryOperator::LogicalAnd => Ok(operator(BinaryOperator::LogicalAnd)),
                ast::BinaryOperator::LogicalOr => Ok(operator(BinaryOperator::LogicalOr)),
                ast::BinaryOperator::LogicalXor => Ok(operator(BinaryOperator::LogicalXor)),
                ast::BinaryOperator::BitwiseOr => Ok(operator(BinaryOperator::BitwiseOr)),
                ast::BinaryOperator::BitwiseAnd => Ok(operator(BinaryOperator::BitwiseAnd)),
                ast::BinaryOperator::BitwiseXor => Ok(operator(BinaryOperator::BitwiseXor)),
            }
        }
        ast::Expression::UnaryOperator(operator, operand) => {
            let operand = operand.try_visit(visit_expression, ctx)?;

            let unop = |op: hir::expression::UnaryOperator| {
                hir::ExprKind::UnaryOperator(op.at_loc(operator), Box::new(operand))
            };
            match operator.inner {
                ast::UnaryOperator::Sub => Ok(unop(hir::expression::UnaryOperator::Sub)),
                ast::UnaryOperator::Not => Ok(unop(hir::expression::UnaryOperator::Not)),
                ast::UnaryOperator::BitwiseNot => {
                    Ok(unop(hir::expression::UnaryOperator::BitwiseNot))
                }
                ast::UnaryOperator::Dereference => {
                    Ok(unop(hir::expression::UnaryOperator::Dereference))
                }
                ast::UnaryOperator::Reference => {
                    Ok(unop(hir::expression::UnaryOperator::Reference))
                }
            }
        }
        ast::Expression::TupleLiteral(exprs) => {
            let exprs = exprs
                .iter()
                .map(|e| e.try_map_ref(|e| visit_expression(e, ctx)))
                .collect::<Result<Vec<_>>>()?;
            Ok(hir::ExprKind::TupleLiteral(exprs))
        }
        ast::Expression::ArrayLiteral(exprs) => {
            let exprs = exprs
                .iter()
                .map(|e| e.try_map_ref(|e| visit_expression(e, ctx)))
                .collect::<Result<Vec<_>>>()?;
            Ok(hir::ExprKind::ArrayLiteral(exprs))
        }
        ast::Expression::ArrayShorthandLiteral(expr, amount) => {
            Ok(hir::ExprKind::ArrayShorthandLiteral(
                Box::new(visit_expression(expr, ctx)?.at_loc(expr)),
                visit_const_generic(amount, ctx)?.map(|c| c.with_id(ctx.idtracker.next())),
            ))
        }
        ast::Expression::Index(target, index) => {
            let target = target.try_visit(visit_expression, ctx)?;
            let index = index.try_visit(visit_expression, ctx)?;
            Ok(hir::ExprKind::Index(Box::new(target), Box::new(index)))
        }
        ast::Expression::RangeIndex { target, start, end } => {
            let target = target.try_visit(visit_expression, ctx)?;
            Ok(hir::ExprKind::RangeIndex {
                target: Box::new(target),
                start: visit_const_generic(start, ctx)?.map(|c| c.with_id(ctx.idtracker.next())),
                end: visit_const_generic(end, ctx)?.map(|c| c.with_id(ctx.idtracker.next())),
            })
        }
        ast::Expression::TupleIndex(tuple, index) => Ok(hir::ExprKind::TupleIndex(
            Box::new(tuple.try_visit(visit_expression, ctx)?),
            *index,
        )),
        ast::Expression::FieldAccess(target, field) => Ok(hir::ExprKind::FieldAccess(
            Box::new(target.try_visit(visit_expression, ctx)?),
            field.clone(),
        )),
        ast::Expression::MethodCall {
            kind,
            target,
            name,
            args,
            turbofish,
        } => {
            let target = target.try_visit(visit_expression, ctx)?;
            Ok(hir::ExprKind::MethodCall {
                target: Box::new(target),
                name: name.clone(),
                args: args.try_map_ref(|args| visit_argument_list(args, ctx))?,
                call_kind: visit_call_kind(kind, ctx)?,
                turbofish: turbofish
                    .as_ref()
                    .map(|t| visit_turbofish(t, ctx))
                    .transpose()?,
            })
        }
        ast::Expression::If(cond, ontrue, onfalse) => {
            let cond = cond.try_visit(visit_expression, ctx)?;
            let ontrue = ontrue.try_visit(visit_expression, ctx)?;
            let onfalse = onfalse.try_visit(visit_expression, ctx)?;

            Ok(hir::ExprKind::If(
                Box::new(cond),
                Box::new(ontrue),
                Box::new(onfalse),
            ))
        }
        ast::Expression::TypeLevelIf(cond, ontrue, onfalse) => {
            let cond = visit_const_generic(cond, ctx)?;
            let ontrue = ontrue.try_visit(visit_expression, ctx)?;
            let onfalse = onfalse.try_visit(visit_expression, ctx)?;

            Ok(hir::ExprKind::TypeLevelIf(
                cond.map(|cond| cond.with_id(ctx.idtracker.next())),
                Box::new(ontrue),
                Box::new(onfalse),
            ))
        }
        ast::Expression::Match(expression, branches) => {
            let e = expression.try_visit(visit_expression, ctx)?;

            if branches.is_empty() {
                return Err(Diagnostic::error(branches, "Match body has no arms")
                    .primary_label("This match body has no arms"));
            }

            let b = branches
                .iter()
                .map(|(pattern, result)| {
                    ctx.symtab.new_scope();
                    let p = pattern.try_visit(visit_pattern, ctx)?;
                    let r = result.try_visit(visit_expression, ctx)?;
                    ctx.symtab.close_scope();
                    Ok((p, r))
                })
                .collect::<Result<Vec<_>>>()?;

            Ok(hir::ExprKind::Match(Box::new(e), b))
        }
        ast::Expression::Block(block) => {
            Ok(hir::ExprKind::Block(Box::new(visit_block(block, ctx)?)))
        }
        ast::Expression::Call {
            kind,
            callee,
            args,
            turbofish,
        } => {
            let (name_id, _) = ctx.symtab.lookup_unit(callee)?;
            let args = visit_argument_list(args, ctx)?.at_loc(args);

            let kind = visit_call_kind(kind, ctx)?;

            let turbofish = turbofish
                .as_ref()
                .map(|t| visit_turbofish(t, ctx))
                .transpose()?;

            Ok(hir::ExprKind::Call {
                kind,
                callee: name_id.at_loc(callee),
                args,
                turbofish,
            })
        }
        ast::Expression::Identifier(path) => {
            // If the identifier isn't a valid variable, report as "expected value".
            match ctx.symtab.lookup_variable(path) {
                Ok(id) => Ok(hir::ExprKind::Identifier(id)),
                Err(LookupError::IsAType(_)) => {
                    let ty = ctx.symtab.lookup_type_symbol(path)?;
                    let (name, ty) = &ty;
                    match ty.inner {
                        TypeSymbol::GenericMeta(
                            MetaType::Int | MetaType::Uint | MetaType::Number,
                        ) => Ok(hir::ExprKind::TypeLevelInteger(name.clone())),
                        TypeSymbol::GenericMeta(_) | TypeSymbol::GenericArg { traits: _ } => {
                            Err(Diagnostic::error(
                                path,
                                format!("Generic type {name} is a type but it is used as a value"),
                            )
                            .primary_label(format!("{name} is a type"))
                            .secondary_label(ty, format!("{name} is declared here"))
                            .span_suggest_insert_before(
                                format!("Consider making `{name}` a type level integer"),
                                ty,
                                "#int ",
                            )
                            .span_suggest_insert_before(
                                format!("or a type level uint"),
                                ty,
                                "#uint ",
                            ))
                        }
                        TypeSymbol::Declared(_, _) | TypeSymbol::Alias(_) => Err(
                            Diagnostic::error(path, format!("Type {name} is used as a value"))
                                .primary_label(format!("{name} is a type")),
                        ),
                    }
                }
                Err(LookupError::NotAVariable(path, ref was @ Thing::EnumVariant(_)))
                | Err(LookupError::NotAVariable(
                    path,
                    ref was @ Thing::Alias {
                        path: _,
                        in_namespace: _,
                    },
                )) => {
                    let (name_id, variant) = match ctx.symtab.lookup_enum_variant(&path) {
                        Ok(res) => res,
                        Err(_) => return Err(LookupError::NotAValue(path, was.clone()).into()),
                    };
                    if variant.params.0.is_empty() {
                        // NOTE: This loc is a little bit approximate because it is unlikely
                        // that any error will reference the empty argument list.
                        let callee = name_id.at_loc(&path);
                        let args = hir::ArgumentList::Positional(vec![]).at_loc(&path);
                        Ok(hir::ExprKind::Call {
                            kind: hir::expression::CallKind::Function,
                            callee,
                            args,
                            turbofish: None,
                        })
                    } else {
                        Err(LookupError::NotAValue(path, was.clone()).into())
                    }
                }
                Err(LookupError::NotAVariable(path, was)) => {
                    Err(LookupError::NotAValue(path, was).into())
                }
                Err(err) => Err(err.into()),
            }
        }
        ast::Expression::PipelineReference {
            stage_kw_and_reference_loc,
            stage,
            name,
        } => {
            let stage = match stage {
                ast::PipelineStageReference::Relative(offset) => {
                    hir::expression::PipelineRefKind::Relative(offset.try_map_ref(|t| {
                        visit_type_expression(t, &TypeSpecKind::PipelineDepth, ctx)
                    })?)
                }
                ast::PipelineStageReference::Absolute(name) => {
                    hir::expression::PipelineRefKind::Absolute(
                        ctx.symtab
                            .lookup_type_symbol(&Path::ident(name.clone()).at_loc(name))?
                            .0
                            .at_loc(name),
                    )
                }
            }
            .at_loc(stage_kw_and_reference_loc);

            let pipeline_ctx = ctx
                .pipeline_ctx
                .as_ref()
                .expect("Expected to have a pipeline context");

            let path = Path(vec![name.clone()]).at_loc(name);
            let (name_id, declares_name) = match ctx.symtab.try_lookup_variable(&path)? {
                Some(id) => (id.at_loc(name), false),
                None => {
                    let pipeline_offset = ctx.symtab.current_scope() - pipeline_ctx.scope;
                    let undecleared_lookup = ctx.symtab.declarations[pipeline_ctx.scope].get(name);

                    if let Some(DeclarationState::Undecleared(name_id)) = undecleared_lookup {
                        (name_id.clone().at_loc(name), false)
                    } else {
                        let name_id = ctx
                            .symtab
                            .add_undecleared_at_offset(pipeline_offset, name.clone());
                        (name_id.at_loc(name), true)
                    }
                }
            };

            Ok(hir::ExprKind::PipelineRef {
                stage,
                name: name_id,
                declares_name,
                depth_typeexpr_id: ctx.idtracker.next(),
            })
        }
        ast::Expression::StageReady => Ok(hir::ExprKind::StageReady),
        ast::Expression::StageValid => Ok(hir::ExprKind::StageValid),
    }
    .map(|kind| kind.with_id(new_id))
}

fn check_for_undefined(ctx: &Context) -> Result<()> {
    match ctx.symtab.get_undefined_declarations().first() {
        Some((undefined, DeclarationState::Undefined(_))) => {
            Err(
                Diagnostic::error(undefined, "Declared variable is not defined")
                    .primary_label("This variable is declared but not defined")
                    // FIXME: Suggest removing the declaration (with a diagnostic suggestion) only if the variable is unused.
                    .help(format!("Define {undefined} with a let or reg binding"))
                    .help("Or, remove the declaration if the variable is unused"),
            )
        }
        Some((undecleared, DeclarationState::Undecleared(_))) => Err(Diagnostic::error(
            undecleared,
            "Could not find referenced variable",
        )
        .primary_label("This variable could not be found")),
        _ => Ok(()),
    }
}

fn visit_block(b: &ast::Block, ctx: &mut Context) -> Result<hir::Block> {
    ctx.symtab.new_scope();
    let statements = b
        .statements
        .iter()
        .map(|statement| visit_statement(statement, ctx))
        .collect::<Result<Vec<_>>>()?
        .into_iter()
        .flatten()
        .collect::<Vec<_>>();

    let result = b
        .result
        .as_ref()
        .map(|o| o.try_visit(visit_expression, ctx))
        .transpose()?;

    check_for_undefined(ctx)?;

    ctx.symtab.close_scope();

    Ok(hir::Block { statements, result })
}

fn visit_register(reg: &Loc<ast::Register>, ctx: &mut Context) -> Result<Vec<Loc<hir::Statement>>> {
    let (reg, loc) = reg.split_loc_ref();

    let pattern = reg.pattern.try_visit(visit_pattern, ctx)?;

    let clock = reg.clock.try_visit(visit_expression, ctx)?;

    let reset = if let Some((trig, value)) = &reg.reset {
        Some((
            trig.try_visit(visit_expression, ctx)?,
            value.try_visit(visit_expression, ctx)?,
        ))
    } else {
        None
    };

    let initial = reg
        .initial
        .as_ref()
        .map(|i| i.try_visit(visit_expression, ctx))
        .transpose()?;

    let value = reg.value.try_visit(visit_expression, ctx)?;

    let value_type = if let Some(value_type) = &reg.value_type {
        Some(visit_type_spec(
            value_type,
            &TypeSpecKind::BindingType,
            ctx,
        )?)
    } else {
        None
    };

    let mut stmts = vec![];

    let attributes = reg.attributes.lower(&mut |attr| match &attr.inner {
        ast::Attribute::Fsm { state } => {
            let name_id = if let Some(state) = state {
                ctx.symtab
                    .lookup_variable(&Path(vec![state.clone()]).at_loc(state))?
            } else if let PatternKind::Name { name, .. } = &pattern.inner.kind {
                name.inner.clone()
            } else {
                return Err(Diagnostic::error(
                    attr,
                    "#[fsm] without explicit name on non-name pattern",
                )
                .secondary_label(&pattern, "This is a pattern")
                .span_suggest(
                    "Consider specifying the name of the s ignal containing the state",
                    attr,
                    "#[fsm(<name>)]",
                ));
            };

            Ok(Some(hir::Attribute::Fsm { state: name_id }))
        }
        ast::Attribute::WalSuffix { suffix } => {
            // All names in the pattern should have the suffix applied to them
            for name in pattern.get_names() {
                stmts.push(
                    hir::Statement::WalSuffixed {
                        suffix: suffix.inner.clone(),
                        target: name.clone(),
                    }
                    .at_loc(suffix),
                );
            }
            Ok(None)
        }
        _ => Err(attr.report_unused("a register")),
    })?;

    stmts.push(
        hir::Statement::Register(hir::Register {
            pattern,
            clock,
            reset,
            initial,
            value,
            value_type,
            attributes,
        })
        .at_loc(&loc),
    );

    Ok(stmts)
}

#[cfg(test)]
mod entity_visiting {
    use super::*;

    use hir::{hparams, UnitName};
    use spade_ast::testutil::{ast_ident, ast_path};
    use spade_common::name::testutil::name_id;
    use spade_common::{location_info::WithLocation, name::Identifier};

    use crate::testutil::test_context;
    use pretty_assertions::assert_eq;

    #[test]
    fn entity_visits_work() {
        let input = ast::Unit {
            head: ast::UnitHead {
                extern_token: None,
                name: Identifier("test".to_string()).nowhere(),
                inputs: ParameterList::without_self(vec![(
                    ast_ident("a"),
                    ast::TypeSpec::Tuple(Vec::new()).nowhere(),
                )])
                .nowhere(),
                output_type: None,
                type_params: None,
                attributes: ast::AttributeList(vec![]),
                unit_kind: ast::UnitKind::Entity.nowhere(),
                where_clauses: vec![],
            },
            body: Some(
                ast::Expression::Block(Box::new(ast::Block {
                    statements: vec![ast::Statement::binding(
                        ast::Pattern::name("var"),
                        Some(ast::TypeSpec::Tuple(Vec::new()).nowhere()),
                        ast::Expression::int_literal_signed(0).nowhere(),
                    )
                    .nowhere()],
                    result: Some(ast::Expression::int_literal_signed(0).nowhere()),
                }))
                .nowhere(),
            ),
        }
        .nowhere();

        let expected = hir::Unit {
            name: UnitName::FullPath(name_id(0, "test")),
            head: hir::UnitHead {
                name: Identifier("test".to_string()).nowhere(),
                inputs: hparams!(("a", hir::TypeSpec::unit().nowhere())).nowhere(),
                output_type: None,
                unit_type_params: vec![],
                scope_type_params: vec![],
                unit_kind: hir::UnitKind::Entity.nowhere(),
                where_clauses: vec![],
                documentation: "".to_string(),
            },
            attributes: hir::AttributeList::empty(),
            inputs: vec![(name_id(1, "a"), hir::TypeSpec::unit().nowhere())],
            body: hir::ExprKind::Block(Box::new(hir::Block {
                statements: vec![hir::Statement::binding(
                    hir::PatternKind::name(name_id(2, "var")).idless().nowhere(),
                    Some(hir::TypeSpec::unit().nowhere()),
                    hir::ExprKind::int_literal(0).idless().nowhere(),
                )
                .nowhere()],
                result: Some(hir::ExprKind::int_literal(0).idless().nowhere()),
            }))
            .idless()
            .nowhere(),
        }
        .nowhere();

        let mut ctx = test_context();

        global_symbols::visit_unit(&None, &input, &None, &vec![], &mut ctx)
            .expect("Failed to collect global symbols");

        let result = visit_unit(None, &input, &None, &mut ctx);

        assert_eq!(result, Ok(hir::Item::Unit(expected)));

        // But the local variables should not
        assert!(!ctx.symtab.has_symbol(ast_path("a").inner));
        assert!(!ctx.symtab.has_symbol(ast_path("var").inner));
    }

    #[ignore]
    #[test]
    fn entity_with_generics_works() {
        unimplemented![]
        // let input = ast::Entity {
        //     name: Identifier("test".to_string()).nowhere(),
        //     inputs: vec![(ast_ident("a"), ast::Type::UnitType.nowhere())],
        //     output_type: ast::Type::UnitType.nowhere(),
        //     body: ast::Expression::Block(Box::new(ast::Block {
        //         statements: vec![ast::Statement::binding(
        //             ast_ident("var"),
        //             Some(ast::Type::UnitType.nowhere()),
        //             ast::Expression::IntLiteral(0).nowhere(),
        //         )
        //         .nowhere()],
        //         result: ast::Expression::IntLiteral(0).nowhere(),
        //     }))
        //     .nowhere(),
        //     type_params: vec![
        //         ast::TypeParam::TypeName(ast_ident("a").inner).nowhere(),
        //         ast::TypeParam::Integer(ast_ident("b")).nowhere(),
        //     ],
        // };

        // let expected = hir::Entity {
        //     head: hir::EntityHead {
        //         inputs: vec![
        //             ((
        //                 NameID(0, Path::from_strs(&["a"])),
        //                 hir::Type::Unit.nowhere(),
        //             )),
        //         ],
        //         output_type: hir::Type::Unit.nowhere(),
        //         type_params: vec![
        //             hir::TypeParam::TypeName(hir_ident("a").inner).nowhere(),
        //             hir::TypeParam::Integer(hir_ident("b")).nowhere(),
        //         ],
        //     },
        //     body: hir::ExprKind::Block(Box::new(hir::Block {
        //         statements: vec![hir::Statement::binding(
        //             hir_ident("var"),
        //             Some(hir::Type::Unit.nowhere()),
        //             hir::ExprKind::IntLiteral(0).idless().nowhere(),
        //         )
        //         .nowhere()],
        //         result: hir::ExprKind::IntLiteral(0).idless().nowhere(),
        //     }))
        //     .idless()
        //     .nowhere(),
        // };

        // let mut symtab = SymbolTable::new();
        // let mut idtracker = ExprIdTracker::new();

        // let result = visit_entity(&input, &mut symtab, &mut idtracker);

        // assert_eq!(result, Ok(expected));

        // // But the local variables should not
        // assert!(!symtab.has_symbol(&hir_ident("a").inner));
        // assert!(!symtab.has_symbol(&hir_ident("var").inner));
    }
}

#[cfg(test)]
mod statement_visiting {
    use super::*;

    use crate::testutil::test_context;
    use id_tracker::ExprID;
    use pretty_assertions::assert_eq;
    use spade_ast::testutil::{ast_ident, ast_path};
    use spade_common::location_info::WithLocation;
    use spade_common::name::testutil::name_id;

    #[test]
    fn bindings_convert_correctly() {
        let mut ctx = test_context();

        let input = ast::Statement::binding(
            ast::Pattern::name("a"),
            Some(ast::TypeSpec::Tuple(Vec::new()).nowhere()),
            ast::Expression::int_literal_signed(0).nowhere(),
        )
        .nowhere();

        let expected = hir::Statement::binding(
            hir::PatternKind::name(name_id(0, "a")).idless().nowhere(),
            Some(hir::TypeSpec::unit().nowhere()),
            hir::ExprKind::int_literal(0).idless().nowhere(),
        )
        .nowhere();

        assert_eq!(visit_statement(&input, &mut ctx), Ok(vec![expected]));
        assert_eq!(ctx.symtab.has_symbol(ast_path("a").inner), true);
    }

    #[test]
    fn registers_are_statements() {
        let input = ast::Statement::Register(
            ast::Register {
                pattern: ast::Pattern::name("regname"),
                clock: ast::Expression::Identifier(ast_path("clk")).nowhere(),
                reset: None,
                initial: None,
                value: ast::Expression::int_literal_signed(0).nowhere(),
                value_type: None,
                attributes: ast::AttributeList::empty(),
            }
            .nowhere(),
        )
        .nowhere();

        let expected = hir::Statement::Register(hir::Register {
            pattern: hir::PatternKind::name(name_id(1, "regname"))
                .idless()
                .nowhere(),
            clock: hir::ExprKind::Identifier(name_id(0, "clk").inner)
                .with_id(ExprID(0))
                .nowhere(),
            reset: None,
            initial: None,
            value: hir::ExprKind::int_literal(0).idless().nowhere(),
            value_type: None,
            attributes: hir::AttributeList::empty(),
        })
        .nowhere();

        let mut ctx = test_context();
        let clk_id = ctx.symtab.add_local_variable(ast_ident("clk"));
        assert_eq!(clk_id.0, 0);
        assert_eq!(visit_statement(&input, &mut ctx), Ok(vec![expected]));
        assert_eq!(ctx.symtab.has_symbol(ast_path("regname").inner), true);
    }

    #[test]
    fn declarations_declare_variables() {
        let input = ast::Statement::Declaration(vec![ast_ident("x"), ast_ident("y")]).nowhere();
        let ctx = &mut test_context();
        assert_eq!(
            visit_statement(&input, ctx),
            Ok(vec![hir::Statement::Declaration(vec![
                name_id(0, "x"),
                name_id(1, "y")
            ])
            .nowhere()])
        );
        assert_eq!(ctx.symtab.has_symbol(ast_path("x").inner), true);
        assert_eq!(ctx.symtab.has_symbol(ast_path("y").inner), true);
    }
}

#[cfg(test)]
mod expression_visiting {
    use super::*;

    use crate::testutil::test_context;
    use hir::hparams;
    use hir::symbol_table::EnumVariant;
    use spade_ast::testutil::{ast_ident, ast_path};
    use spade_common::location_info::WithLocation;
    use spade_common::name::testutil::name_id;

    #[test]
    fn int_literals_work() {
        let input = ast::Expression::int_literal_signed(123);
        let expected = hir::ExprKind::int_literal(123).idless();

        assert_eq!(visit_expression(&input, &mut test_context()), Ok(expected));
    }

    macro_rules! binop_test {
        ($test_name:ident, $token:ident, $op:ident) => {
            #[test]
            fn $test_name() {
                let input = ast::Expression::BinaryOperator(
                    Box::new(ast::Expression::int_literal_signed(123).nowhere()),
                    spade_ast::BinaryOperator::$token.nowhere(),
                    Box::new(ast::Expression::int_literal_signed(456).nowhere()),
                );
                let expected = hir::ExprKind::BinaryOperator(
                    Box::new(hir::ExprKind::int_literal(123).idless().nowhere()),
                    BinaryOperator::$op.nowhere(),
                    Box::new(hir::ExprKind::int_literal(456).idless().nowhere()),
                )
                .idless();

                assert_eq!(visit_expression(&input, &mut test_context()), Ok(expected));
            }
        };
    }

    macro_rules! unop_test {
        ($test_name:ident, $token:ident, $op:ident) => {
            #[test]
            fn $test_name() {
                let input = ast::Expression::UnaryOperator(
                    spade_ast::UnaryOperator::$token.nowhere(),
                    Box::new(ast::Expression::int_literal_signed(456).nowhere()),
                );
                let expected = hir::ExprKind::UnaryOperator(
                    hir::expression::UnaryOperator::$op.nowhere(),
                    Box::new(hir::ExprKind::int_literal(456).idless().nowhere()),
                )
                .idless();

                assert_eq!(visit_expression(&input, &mut test_context()), Ok(expected));
            }
        };
    }

    binop_test!(additions, Add, Add);
    binop_test!(subtractions, Sub, Sub);
    binop_test!(equals, Equals, Eq);
    binop_test!(bitwise_or, BitwiseOr, BitwiseOr);
    binop_test!(bitwise_and, BitwiseAnd, BitwiseAnd);
    unop_test!(usub, Sub, Sub);
    unop_test!(not, Not, Not);

    #[test]
    fn indexing_works() {
        let input = ast::Expression::Index(
            Box::new(ast::Expression::int_literal_signed(0).nowhere()),
            Box::new(ast::Expression::int_literal_signed(1).nowhere()),
        );

        let expected = hir::ExprKind::Index(
            Box::new(hir::ExprKind::int_literal(0).idless().nowhere()),
            Box::new(hir::ExprKind::int_literal(1).idless().nowhere()),
        )
        .idless();

        assert_eq!(visit_expression(&input, &mut test_context()), Ok(expected));
    }

    #[test]
    fn field_access_works() {
        let input = ast::Expression::FieldAccess(
            Box::new(ast::Expression::int_literal_signed(0).nowhere()),
            ast_ident("a"),
        );

        let expected = hir::ExprKind::FieldAccess(
            Box::new(hir::ExprKind::int_literal(0).idless().nowhere()),
            ast_ident("a"),
        )
        .idless();

        assert_eq!(visit_expression(&input, &mut test_context(),), Ok(expected));
    }

    #[test]
    fn blocks_work() {
        let input = ast::Expression::Block(Box::new(ast::Block {
            statements: vec![ast::Statement::binding(
                ast::Pattern::name("a"),
                None,
                ast::Expression::int_literal_signed(0).nowhere(),
            )
            .nowhere()],
            result: Some(ast::Expression::int_literal_signed(0).nowhere()),
        }));
        let expected = hir::ExprKind::Block(Box::new(hir::Block {
            statements: vec![hir::Statement::binding(
                hir::PatternKind::name(name_id(0, "a")).idless().nowhere(),
                None,
                hir::ExprKind::int_literal(0).idless().nowhere(),
            )
            .nowhere()],
            result: Some(hir::ExprKind::int_literal(0).idless().nowhere()),
        }))
        .idless();

        let mut ctx = test_context();
        assert_eq!(visit_expression(&input, &mut ctx), Ok(expected));
        assert!(!ctx.symtab.has_symbol(ast_path("a").inner));
    }

    #[test]
    fn if_expressions_work() {
        let input = ast::Expression::If(
            Box::new(ast::Expression::int_literal_signed(0).nowhere()),
            Box::new(
                ast::Expression::Block(Box::new(ast::Block {
                    statements: vec![],
                    result: Some(ast::Expression::int_literal_signed(1).nowhere()),
                }))
                .nowhere(),
            ),
            Box::new(
                ast::Expression::Block(Box::new(ast::Block {
                    statements: vec![],
                    result: Some(ast::Expression::int_literal_signed(2).nowhere()),
                }))
                .nowhere(),
            ),
        );
        let expected = hir::ExprKind::If(
            Box::new(hir::ExprKind::int_literal(0).idless().nowhere()),
            Box::new(
                hir::ExprKind::Block(Box::new(hir::Block {
                    statements: vec![],
                    result: Some(hir::ExprKind::int_literal(1).idless().nowhere()),
                }))
                .idless()
                .nowhere(),
            ),
            Box::new(
                hir::ExprKind::Block(Box::new(hir::Block {
                    statements: vec![],
                    result: Some(hir::ExprKind::int_literal(2).idless().nowhere()),
                }))
                .idless()
                .nowhere(),
            ),
        )
        .idless();

        assert_eq!(visit_expression(&input, &mut test_context(),), Ok(expected));
    }

    #[test]
    fn match_expressions_work() {
        let input = ast::Expression::Match(
            Box::new(ast::Expression::int_literal_signed(1).nowhere()),
            vec![(
                ast::Pattern::name("x"),
                ast::Expression::int_literal_signed(2).nowhere(),
            )]
            .nowhere(),
        );

        let expected = hir::ExprKind::Match(
            Box::new(hir::ExprKind::int_literal(1).idless().nowhere()),
            vec![(
                hir::PatternKind::name(name_id(0, "x")).idless().nowhere(),
                hir::ExprKind::int_literal(2).idless().nowhere(),
            )],
        )
        .idless();

        assert_eq!(visit_expression(&input, &mut test_context(),), Ok(expected))
    }

    #[test]
    fn match_expressions_with_enum_members_works() {
        let input = ast::Expression::Match(
            Box::new(ast::Expression::int_literal_signed(1).nowhere()),
            vec![(
                ast::Pattern::Type(
                    ast_path("x"),
                    ast::ArgumentPattern::Positional(vec![
                        ast::Pattern::Path(ast_path("y")).nowhere()
                    ])
                    .nowhere(),
                )
                .nowhere(),
                ast::Expression::Identifier(ast_path("y")).nowhere(),
            )]
            .nowhere(),
        );

        let expected = hir::ExprKind::Match(
            Box::new(hir::ExprKind::int_literal(1).idless().nowhere()),
            vec![(
                hir::PatternKind::Type(
                    name_id(100, "x"),
                    vec![hir::PatternArgument {
                        target: ast_ident("x"),
                        value: hir::PatternKind::name(name_id(0, "y")).idless().nowhere(),
                        kind: hir::ArgumentKind::Positional,
                    }],
                )
                .idless()
                .nowhere(),
                hir::ExprKind::Identifier(name_id(0, "y").inner)
                    .idless()
                    .nowhere(),
            )],
        )
        .idless();

        let mut symtab = SymbolTable::new();

        let enum_variant = EnumVariant {
            name: Identifier("".to_string()).nowhere(),
            output_type: hir::TypeSpec::unit().nowhere(),
            option: 0,
            params: hparams![("x", hir::TypeSpec::unit().nowhere())].nowhere(),
            type_params: vec![],
            documentation: "".to_string(),
        }
        .nowhere();

        symtab.add_thing_with_id(100, ast_path("x").inner, Thing::EnumVariant(enum_variant));
        assert_eq!(
            visit_expression(
                &input,
                &mut Context {
                    symtab,
                    ..test_context()
                }
            ),
            Ok(expected)
        )
    }

    #[test]
    fn match_expressions_with_0_argument_enum_works() {
        let input = ast::Expression::Match(
            Box::new(ast::Expression::int_literal_signed(1).nowhere()),
            vec![(
                ast::Pattern::Type(
                    ast_path("x"),
                    ast::ArgumentPattern::Positional(vec![
                        ast::Pattern::Path(ast_path("y")).nowhere()
                    ])
                    .nowhere(),
                )
                .nowhere(),
                ast::Expression::Identifier(ast_path("y")).nowhere(),
            )]
            .nowhere(),
        );

        let expected = hir::ExprKind::Match(
            Box::new(hir::ExprKind::int_literal(1).idless().nowhere()),
            vec![(
                hir::PatternKind::Type(
                    name_id(100, "x"),
                    vec![hir::PatternArgument {
                        target: ast_ident("x"),
                        value: hir::PatternKind::name(name_id(0, "y")).idless().nowhere(),
                        kind: hir::ArgumentKind::Positional,
                    }],
                )
                .idless()
                .nowhere(),
                hir::ExprKind::Identifier(name_id(0, "y").inner)
                    .idless()
                    .nowhere(),
            )],
        )
        .idless();

        let mut symtab = SymbolTable::new();

        let enum_variant = EnumVariant {
            name: Identifier("".to_string()).nowhere(),
            output_type: hir::TypeSpec::unit().nowhere(),
            option: 0,
            params: hparams![("x", hir::TypeSpec::unit().nowhere())].nowhere(),
            type_params: vec![],
            documentation: "".to_string(),
        }
        .nowhere();

        symtab.add_thing_with_id(100, ast_path("x").inner, Thing::EnumVariant(enum_variant));

        assert_eq!(
            visit_expression(
                &input,
                &mut Context {
                    symtab,
                    ..test_context()
                }
            ),
            Ok(expected)
        )
    }

    #[test]
    fn entity_instantiation_works() {
        let input = ast::Expression::Call {
            kind: ast::CallKind::Entity(().nowhere()),
            callee: ast_path("test"),
            args: ast::ArgumentList::Positional(vec![
                ast::Expression::int_literal_signed(1).nowhere(),
                ast::Expression::int_literal_signed(2).nowhere(),
            ])
            .nowhere(),
            turbofish: None,
        }
        .nowhere();

        let expected = hir::ExprKind::Call {
            kind: hir::expression::CallKind::Entity(().nowhere()),
            callee: name_id(0, "test"),
            args: hir::ArgumentList::Positional(vec![
                hir::ExprKind::int_literal(1).idless().nowhere(),
                hir::ExprKind::int_literal(2).idless().nowhere(),
            ])
            .nowhere(),
            turbofish: None,
        }
        .idless();

        let mut symtab = SymbolTable::new();

        symtab.add_thing(
            ast_path("test").inner,
            Thing::Unit(
                hir::UnitHead {
                    name: Identifier("".to_string()).nowhere(),
                    inputs: hparams![
                        ("a", hir::TypeSpec::unit().nowhere()),
                        ("b", hir::TypeSpec::unit().nowhere()),
                    ]
                    .nowhere(),
                    output_type: None,
                    unit_type_params: vec![],
                    scope_type_params: vec![],
                    unit_kind: hir::UnitKind::Entity.nowhere(),
                    where_clauses: vec![],
                    documentation: "".to_string(),
                }
                .nowhere(),
            ),
        );

        assert_eq!(
            visit_expression(
                &input,
                &mut Context {
                    symtab,
                    ..test_context()
                }
            ),
            Ok(expected)
        );
    }

    #[test]
    fn entity_instantiation_with_named_args_works() {
        let input = ast::Expression::Call {
            kind: ast::CallKind::Entity(().nowhere()),
            callee: ast_path("test"),
            args: ast::ArgumentList::Named(vec![
                ast::NamedArgument::Full(
                    ast_ident("b"),
                    ast::Expression::int_literal_signed(2).nowhere(),
                ),
                ast::NamedArgument::Full(
                    ast_ident("a"),
                    ast::Expression::int_literal_signed(1).nowhere(),
                ),
            ])
            .nowhere(),
            turbofish: None,
        }
        .nowhere();

        let expected = hir::ExprKind::Call {
            kind: hir::expression::CallKind::Entity(().nowhere()),
            callee: name_id(0, "test"),
            args: hir::ArgumentList::Named(vec![
                hir::expression::NamedArgument::Full(
                    ast_ident("b"),
                    hir::ExprKind::int_literal(2).idless().nowhere(),
                ),
                hir::expression::NamedArgument::Full(
                    ast_ident("a"),
                    hir::ExprKind::int_literal(1).idless().nowhere(),
                ),
            ])
            .nowhere(),
            turbofish: None,
        }
        .idless();

        let mut symtab = SymbolTable::new();

        symtab.add_thing(
            ast_path("test").inner,
            Thing::Unit(
                hir::UnitHead {
                    name: Identifier("".to_string()).nowhere(),
                    inputs: hparams![
                        ("a", hir::TypeSpec::unit().nowhere()),
                        ("b", hir::TypeSpec::unit().nowhere()),
                    ]
                    .nowhere(),
                    output_type: None,
                    unit_type_params: vec![],
                    scope_type_params: vec![],
                    unit_kind: hir::UnitKind::Entity.nowhere(),
                    where_clauses: vec![],
                    documentation: "".to_string(),
                }
                .nowhere(),
            ),
        );

        assert_eq!(
            visit_expression(
                &input,
                &mut Context {
                    symtab,
                    ..test_context()
                }
            ),
            Ok(expected)
        );
    }

    #[test]
    fn function_instantiation_works() {
        let input = ast::Expression::Call {
            kind: ast::CallKind::Function,
            callee: ast_path("test"),
            args: ast::ArgumentList::Positional(vec![
                ast::Expression::int_literal_signed(1).nowhere(),
                ast::Expression::int_literal_signed(2).nowhere(),
            ])
            .nowhere(),
            turbofish: None,
        }
        .nowhere();

        let expected = hir::ExprKind::Call {
            kind: hir::expression::CallKind::Function,
            callee: name_id(0, "test"),
            args: hir::ArgumentList::Positional(vec![
                hir::ExprKind::int_literal(1).idless().nowhere(),
                hir::ExprKind::int_literal(2).idless().nowhere(),
            ])
            .nowhere(),
            turbofish: None,
        }
        .idless();

        let mut symtab = SymbolTable::new();

        symtab.add_thing(
            ast_path("test").inner,
            Thing::Unit(
                hir::UnitHead {
                    name: Identifier("".to_string()).nowhere(),
                    inputs: hparams![
                        ("a", hir::TypeSpec::unit().nowhere()),
                        ("b", hir::TypeSpec::unit().nowhere()),
                    ]
                    .nowhere(),
                    output_type: None,
                    unit_type_params: vec![],
                    scope_type_params: vec![],
                    unit_kind: hir::UnitKind::Function(hir::FunctionKind::Fn).nowhere(),
                    where_clauses: vec![],
                    documentation: "".to_string(),
                }
                .nowhere(),
            ),
        );

        assert_eq!(
            visit_expression(
                &input,
                &mut Context {
                    symtab,
                    ..test_context()
                }
            ),
            Ok(expected)
        );
    }
}

#[cfg(test)]
mod pattern_visiting {
    use crate::testutil::test_context;
    use ast::{
        testutil::{ast_ident, ast_path},
        ArgumentPattern,
    };
    use hir::{
        hparams,
        symbol_table::{StructCallable, TypeDeclKind},
        PatternKind,
    };
    use spade_common::name::testutil::name_id;

    use super::*;

    #[test]
    fn bool_patterns_work() {
        let input = ast::Pattern::Bool(true);

        let result = visit_pattern(&input, &mut test_context());

        assert_eq!(result, Ok(PatternKind::Bool(true).idless()));
    }

    #[test]
    fn int_patterns_work() {
        let input = ast::Pattern::integer(5);

        let result = visit_pattern(&input, &mut test_context());

        assert_eq!(result, Ok(PatternKind::integer(5).idless()));
    }

    #[test]
    fn named_struct_patterns_work() {
        let input = ast::Pattern::Type(
            ast_path("a"),
            ArgumentPattern::Named(vec![
                (ast_ident("x"), None),
                (ast_ident("y"), Some(ast::Pattern::integer(0).nowhere())),
            ])
            .nowhere(),
        );

        let mut symtab = SymbolTable::new();

        let type_name = symtab.add_type(
            ast_path("a").inner,
            TypeSymbol::Declared(vec![], TypeDeclKind::normal_struct()).nowhere(),
        );

        symtab.add_thing_with_name_id(
            type_name.clone(),
            Thing::Struct(
                StructCallable {
                    name: Identifier("".to_string()).nowhere(),
                    self_type: hir::TypeSpec::Declared(type_name.clone().nowhere(), vec![])
                        .nowhere(),
                    params: hparams![
                        ("x", hir::TypeSpec::unit().nowhere()),
                        ("y", hir::TypeSpec::unit().nowhere()),
                    ]
                    .nowhere(),
                    type_params: vec![],
                }
                .nowhere(),
            ),
        );

        let result = visit_pattern(
            &input,
            &mut Context {
                symtab,
                ..test_context()
            },
        );

        let expected = PatternKind::Type(
            type_name.nowhere(),
            vec![
                hir::PatternArgument {
                    target: ast_ident("x"),
                    value: hir::PatternKind::name(name_id(1, "x")).idless().nowhere(),
                    kind: hir::ArgumentKind::ShortNamed,
                },
                hir::PatternArgument {
                    target: ast_ident("y"),
                    value: hir::PatternKind::integer(0).idless().nowhere(),
                    kind: hir::ArgumentKind::Named,
                },
            ],
        )
        .idless();

        assert_eq!(result, Ok(expected))
    }
}

#[cfg(test)]
mod register_visiting {
    use super::*;

    use crate::testutil::test_context;
    use spade_ast::testutil::{ast_ident, ast_path};
    use spade_common::location_info::WithLocation;
    use spade_common::name::testutil::name_id;

    #[test]
    fn register_visiting_works() {
        let input = ast::Register {
            pattern: ast::Pattern::name("test"),
            clock: ast::Expression::Identifier(ast_path("clk")).nowhere(),
            reset: Some((
                ast::Expression::Identifier(ast_path("rst")).nowhere(),
                ast::Expression::int_literal_signed(0).nowhere(),
            )),
            initial: Some(ast::Expression::int_literal_signed(0).nowhere()),
            value: ast::Expression::int_literal_signed(1).nowhere(),
            value_type: Some(ast::TypeSpec::Tuple(Vec::new()).nowhere()),
            attributes: ast::AttributeList::empty(),
        }
        .nowhere();

        let expected = hir::Register {
            pattern: hir::PatternKind::name(name_id(2, "test"))
                .idless()
                .nowhere(),
            clock: hir::ExprKind::Identifier(name_id(0, "clk").inner)
                .idless()
                .nowhere(),
            reset: Some((
                hir::ExprKind::Identifier(name_id(1, "rst").inner)
                    .idless()
                    .nowhere(),
                hir::ExprKind::int_literal(0).idless().nowhere(),
            )),
            initial: Some(hir::ExprKind::int_literal(0).idless().nowhere()),
            value: hir::ExprKind::int_literal(1).idless().nowhere(),
            value_type: Some(hir::TypeSpec::unit().nowhere()),
            attributes: hir::AttributeList::empty(),
        };

        let mut symtab = SymbolTable::new();
        let clk_id = symtab.add_local_variable(ast_ident("clk"));
        assert_eq!(clk_id.0, 0);
        let rst_id = symtab.add_local_variable(ast_ident("rst"));
        assert_eq!(rst_id.0, 1);
        assert_eq!(
            visit_register(
                &input,
                &mut Context {
                    symtab,
                    ..test_context()
                }
            ),
            Ok(vec![hir::Statement::Register(expected).nowhere()])
        );
    }
}

#[cfg(test)]
mod item_visiting {
    use super::*;

    use ast::aparams;
    use spade_ast::testutil::ast_ident;
    use spade_common::location_info::WithLocation;
    use spade_common::name::testutil::name_id;

    use crate::testutil::test_context;
    use pretty_assertions::assert_eq;

    #[test]
    pub fn item_entity_visiting_works() {
        let input = ast::Item::Unit(
            ast::Unit {
                head: ast::UnitHead {
                    extern_token: None,
                    name: ast_ident("test"),
                    output_type: None,
                    inputs: aparams![],
                    type_params: None,
                    attributes: ast::AttributeList(vec![]),
                    unit_kind: ast::UnitKind::Entity.nowhere(),
                    where_clauses: vec![],
                },
                body: Some(
                    ast::Expression::Block(Box::new(ast::Block {
                        statements: vec![],
                        result: Some(ast::Expression::int_literal_signed(0).nowhere()),
                    }))
                    .nowhere(),
                ),
            }
            .nowhere(),
        );

        let expected = hir::Item::Unit(
            hir::Unit {
                name: hir::UnitName::FullPath(name_id(0, "test")),
                head: hir::UnitHead {
                    name: Identifier("test".to_string()).nowhere(),
                    output_type: None,
                    inputs: hir::ParameterList(vec![]).nowhere(),
                    unit_type_params: vec![],
                    scope_type_params: vec![],
                    unit_kind: hir::UnitKind::Entity.nowhere(),
                    where_clauses: vec![],
                    documentation: "".to_string(),
                },
                attributes: hir::AttributeList::empty(),
                inputs: vec![],
                body: hir::ExprKind::Block(Box::new(hir::Block {
                    statements: vec![],
                    result: Some(hir::ExprKind::int_literal(0).idless().nowhere()),
                }))
                .idless()
                .nowhere(),
            }
            .nowhere(),
        );

        let mut ctx = test_context();

        global_symbols::visit_item(&input, &mut ctx).unwrap();
        assert_eq!(visit_item(&input, &mut ctx), Ok(vec![expected]));
    }
}

#[cfg(test)]
mod module_visiting {
    use std::collections::HashMap;

    use super::*;

    use hir::hparams;
    use spade_ast::testutil::ast_ident;
    use spade_common::location_info::WithLocation;
    use spade_common::name::testutil::name_id;

    use crate::testutil::test_context;
    use pretty_assertions::assert_eq;
    use spade_common::namespace::ModuleNamespace;

    #[test]
    fn visiting_module_with_one_entity_works() {
        let input = ast::ModuleBody {
            members: vec![ast::Item::Unit(
                ast::Unit {
                    head: ast::UnitHead {
                        extern_token: None,
                        name: ast_ident("test"),
                        output_type: None,
                        inputs: ParameterList::without_self(vec![]).nowhere(),
                        type_params: None,
                        attributes: ast::AttributeList(vec![]),
                        unit_kind: ast::UnitKind::Entity.nowhere(),
                        where_clauses: vec![],
                    },
                    body: Some(
                        ast::Expression::Block(Box::new(ast::Block {
                            statements: vec![],
                            result: Some(ast::Expression::int_literal_signed(0).nowhere()),
                        }))
                        .nowhere(),
                    ),
                }
                .nowhere(),
            )],
            documentation: vec![],
        };

        let expected = hir::ItemList {
            executables: vec![(
                name_id(0, "test").inner,
                hir::ExecutableItem::Unit(
                    hir::Unit {
                        name: hir::UnitName::FullPath(name_id(0, "test")),
                        head: hir::UnitHead {
                            name: Identifier("test".to_string()).nowhere(),
                            output_type: None,
                            inputs: hparams!().nowhere(),
                            unit_type_params: vec![],
                            scope_type_params: vec![],
                            unit_kind: hir::UnitKind::Entity.nowhere(),
                            where_clauses: vec![],
                            documentation: "".to_string(),
                        },
                        inputs: vec![],
                        attributes: hir::AttributeList::empty(),
                        body: hir::ExprKind::Block(Box::new(hir::Block {
                            statements: vec![],
                            result: Some(hir::ExprKind::int_literal(0).idless().nowhere()),
                        }))
                        .idless()
                        .nowhere(),
                    }
                    .nowhere(),
                ),
            )]
            .into_iter()
            .collect(),
            types: vec![].into_iter().collect(),
            modules: vec![].into_iter().collect(),
            traits: HashMap::new(),
            impls: HashMap::new(),
        };

        let mut ctx = test_context();
        global_symbols::gather_symbols(&input, &mut ctx).expect("failed to collect global symbols");
        assert_eq!(visit_module_body(&input, &mut ctx), Ok(()));
        assert_eq!(ctx.item_list, expected);
    }

    #[test]
    fn visiting_submodules_works() {
        let input = ast::ModuleBody {
            members: vec![ast::Item::Module(
                ast::Module {
                    name: ast_ident("outer"),
                    body: ast::ModuleBody {
                        members: vec![ast::Item::Module(
                            ast::Module {
                                name: ast_ident("inner"),
                                body: ast::ModuleBody {
                                    members: vec![],
                                    documentation: vec![],
                                }
                                .nowhere(),
                            }
                            .nowhere(),
                        )],
                        documentation: vec![],
                    }
                    .nowhere(),
                }
                .nowhere(),
            )],
            documentation: vec![],
        };

        let expected = hir::ItemList {
            executables: vec![].into_iter().collect(),
            types: vec![].into_iter().collect(),
            modules: vec![
                (
                    name_id(1, "outer").inner,
                    hir::Module {
                        name: name_id(1, "outer"),
                        documentation: "".to_string(),
                    },
                ),
                (
                    name_id(2, "outer::inner").inner,
                    hir::Module {
                        name: name_id(2, "outer::inner"),
                        documentation: "".to_string(),
                    },
                ),
            ]
            .into_iter()
            .collect(),
            traits: HashMap::new(),
            impls: HashMap::new(),
        };

        let mut ctx = test_context();

        let namespace = ModuleNamespace {
            namespace: Path::from_strs(&[""]),
            base_namespace: Path::from_strs(&[""]),
            file: "test/file.spade".to_string(),
        };
        ctx.symtab.add_thing(
            namespace.namespace.clone(),
            Thing::Module(namespace.namespace.0[0].clone()),
        );
        global_symbols::gather_types(&input, &mut ctx).expect("failed to collect types");

        assert_eq!(visit_module_body(&input, &mut ctx), Ok(()));
        assert_eq!(ctx.item_list, expected);
    }
}