veryl-analyzer 0.22.0

A modern hardware description language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
use crate::analyzer_error::{
    AnalyzerError, CaseLabelMismatch, ComponentInterfaceMismatchKind, ExceedLimitKind,
    InvalidForRangeKind, InvalidForStepKind, MismatchAssignmentKind, MismatchTypeKind,
    MultipleDefaultKind, UnevaluableValueKind,
};
use crate::conv::checker::anonymous::check_anonymous;
use crate::conv::checker::clock_domain::check_clock_domain;
use crate::conv::checker::generic::check_generic_refereence;
use crate::conv::checker::portability::check_initial_assign_system_function_args;
use crate::conv::context::RuntimeFunctionEffect;
use crate::conv::instance::InstanceHistoryError;
use crate::conv::{Context, Conv};
use crate::definition_table::{self, Definition, DefinitionId};
use crate::ir::{
    self, Arguments, Comptime, FuncPath, FuncProto, IrResult, Op, PartSelectPath, Shape, ShapeRef,
    Signature, SystemFunctionInput, TbMethod, TbMethodCall, ValueVariant, VarIndex, VarKind,
    VarPath, VarPathSelect, VarSelect, Variable,
};
use crate::namespace::DefineContext;
use crate::symbol::{
    self, Affiliation, ClockDomain, EnumMemberValue, GenericBoundKind, GenericMap, ProtoBound,
    Symbol, SymbolKind, TbComponentKind, TypeKind,
};
use crate::symbol_path::{
    GenericSymbolPath, GenericSymbolPathKind, SymbolPath, SymbolPathNamespace,
};
use crate::symbol_table::{self, ResolveResult};
use crate::value::Value;
use crate::{HashMap, HashSet, ir_error};
use std::rc::Rc;
use std::sync::Arc;
use veryl_parser::resource_table::{self, StrId};
use veryl_parser::token_range::TokenRange;
use veryl_parser::veryl_grammar_trait::*;
use veryl_parser::veryl_token::Token;

/// True for "atomic" expressions whose result type is unambiguous:
/// variable references, sized / real / boolean literals, function
/// calls, and parenthesized recursions. Operators, casts, concatenation
/// and unsized literals are rejected.
pub fn is_inferable_expression(expr: &Expression) -> bool {
    let if_expr = &*expr.if_expression;
    if !if_expr.if_expression_list.is_empty() {
        return false;
    }
    let e01 = &*if_expr.expression01;
    if !e01.expression01_list.is_empty() {
        return false;
    }
    let e02 = &*e01.expression02;
    if !e02.expression02_list.is_empty() || e02.expression02_opt.is_some() {
        return false;
    }
    is_inferable_factor(&e02.factor)
}

fn is_inferable_factor(factor: &Factor) -> bool {
    match factor {
        Factor::IdentifierFactor(_) => true,
        Factor::BooleanLiteral(_) => true,
        Factor::LParenExpressionRParen(x) => is_inferable_expression(&x.expression),
        Factor::Number(x) => match x.number.as_ref() {
            Number::IntegralNumber(x) => match x.integral_number.as_ref() {
                IntegralNumber::Based(_) => true,
                IntegralNumber::BaseLess(_) | IntegralNumber::AllBit(_) => false,
            },
            Number::RealNumber(_) => true,
        },
        _ => false,
    }
}

/// Inference for `var X;` (no type) from a single assignment.
/// Returns the evaluation pair so the caller avoids re-walking the
/// expression. Subsequent conflicting assigns are rejected.
pub fn try_infer_var_assign(
    context: &mut Context,
    dst_symbol: &Symbol,
    expr: &Expression,
    token: TokenRange,
) -> IrResult<Option<(Comptime, ir::Expression)>> {
    let SymbolKind::Variable(var_prop) = &dst_symbol.kind else {
        return Ok(None);
    };
    if !var_prop.r#type.is_inferred() {
        return Ok(None);
    }

    if !is_inferable_expression(expr) {
        context.insert_error(AnalyzerError::type_inference_not_supported(&expr.into()));
        return Err(ir_error!(token));
    }
    let (comptime, ir_expr) = eval_expr(context, None, expr, false)?;
    let inferred = comptime.r#type.clone();
    check_inferred_type_emittable(context, &inferred, expr, token)?;

    if let Some(existing) = crate::resolved_type_table::get(&dst_symbol.token.id) {
        if existing != inferred {
            context.insert_error(AnalyzerError::type_inference_conflict(
                &dst_symbol.token.text.to_string(),
                &expr.into(),
            ));
            return Err(ir_error!(token));
        }
    } else {
        crate::resolved_type_table::insert(dst_symbol.token.id, inferred.clone());
        // Replace the placeholder Comptime so subsequent lookups see
        // the inferred type, not `Unknown`.
        let path = VarPath::new(dst_symbol.token.text);
        if let Some((id, mut ct)) = context.find_path(&path) {
            ct.r#type = inferred.clone();
            context.insert_var_path_with_id(path, id, ct);
        }
    }
    Ok(Some((comptime, ir_expr)))
}

/// Inference for `let`/`const` declarations. Returns `None` when the
/// type is not `Inferred`.
pub fn try_infer_decl_type(
    context: &mut Context,
    sym_type: &symbol::Type,
    expr: &Expression,
    decl_token_id: veryl_parser::resource_table::TokenId,
    token: TokenRange,
) -> IrResult<Option<(Comptime, ir::Expression)>> {
    if !sym_type.is_inferred() {
        return Ok(None);
    }
    if !is_inferable_expression(expr) {
        context.insert_error(AnalyzerError::type_inference_not_supported(&expr.into()));
        return Err(ir_error!(token));
    }
    let (comptime, ir_expr) = eval_expr(context, None, expr, false)?;
    check_inferred_type_emittable(context, &comptime.r#type, expr, token)?;
    crate::resolved_type_table::insert(decl_token_id, comptime.r#type.clone());
    Ok(Some((comptime, ir_expr)))
}

/// The emitter declares an inferred variable by its SV scalar type name;
/// a struct/union/enum has none and would silently emit a 1-bit `logic`,
/// so reject the inference instead of miscompiling.
fn check_inferred_type_emittable(
    context: &mut Context,
    r#type: &ir::Type,
    expr: &Expression,
    token: TokenRange,
) -> IrResult<()> {
    if matches!(
        r#type.kind,
        ir::TypeKind::Struct(_) | ir::TypeKind::Union(_) | ir::TypeKind::Enum(_)
    ) {
        context.insert_error(AnalyzerError::type_inference_not_supported(&expr.into()));
        return Err(ir_error!(token));
    }
    Ok(())
}

fn format_positive_type_name(r#type: &ir::Type) -> Option<String> {
    if !r#type.is_positive {
        return None;
    }

    if let Some(width) = r#type.width().first()
        && let Some(w) = width
    {
        return Some(match *w {
            8 => "p8".to_string(),
            16 => "p16".to_string(),
            32 => "p32".to_string(),
            64 => "p64".to_string(),
            _ => r#type.to_string(),
        });
    }

    Some(r#type.to_string())
}

pub fn eval_expr(
    context: &mut Context,
    dst_type: Option<ir::Type>,
    expr: &Expression,
    allow_anonymous: bool,
) -> IrResult<(Comptime, ir::Expression)> {
    let token: TokenRange = expr.into();
    let expr: IrResult<ir::Expression> = Conv::conv(context, expr);

    if let Ok(mut expr) = expr {
        check_anonymous(context, &expr, allow_anonymous, token);

        let mut comptime = if let Some(dst_type) = dst_type {
            let mut comptime = expr.eval_comptime(context, dst_type.total_width()).clone();

            check_compatibility(context, &dst_type, &comptime, &token);

            comptime.r#type = dst_type;
            comptime
        } else {
            expr.eval_comptime(context, None).clone()
        };

        // `eval_comptime` doesn't evaluate an array literal, so evaluate it here
        // to carry the element values.
        if matches!(expr, ir::Expression::ArrayLiteral(..))
            && !comptime.r#type.array.is_empty()
            && let Some(values) = eval_array_literal_values(context, &comptime.r#type, &mut expr)?
        {
            comptime.value = ValueVariant::NumericArray(values);
        }

        Ok((comptime, expr))
    } else {
        let comptime = Comptime::create_unknown(token);
        let expr = ir::Expression::Term(Box::new(ir::Factor::Unknown(comptime.clone())));
        Ok((comptime, expr))
    }
}

pub fn eval_generic_expr(
    context: &mut Context,
    expr: &Expression,
) -> IrResult<(Comptime, ir::Expression)> {
    let allow_component_as_factor = context.allow_component_as_factor;
    context.allow_component_as_factor = true;
    let ret = eval_expr(context, None, expr, false);
    context.allow_component_as_factor = allow_component_as_factor;
    ret
}

pub fn eval_range(
    context: &mut Context,
    range: &Range,
) -> IrResult<(ir::ForBound, ir::ForBound, bool)> {
    eval_range_inner(context, range, false)
}

pub fn eval_range_const(
    context: &mut Context,
    range: &Range,
) -> IrResult<(ir::ForBound, ir::ForBound, bool)> {
    eval_range_inner(context, range, true)
}

/// A signed bound is read back as an `i64`, where a saturated value would
/// wrap negative.
fn const_for_bound(value: &Value, signed: bool) -> usize {
    let val = value.to_usize_saturating().unwrap_or(0);
    if signed {
        val.min(i64::MAX as usize)
    } else {
        val
    }
}

fn eval_range_inner(
    context: &mut Context,
    range: &Range,
    require_const: bool,
) -> IrResult<(ir::ForBound, ir::ForBound, bool)> {
    // The emitted SV compares an `int` iterator against the bound, so the
    // bound is evaluated at no less than 32 bits.
    let mut beg: ir::Expression = Conv::conv(context, range.expression.as_ref())?;
    let beg_comptime = beg.eval_comptime(context, Some(32));
    if require_const && !beg_comptime.is_const {
        context.insert_error(AnalyzerError::unevaluable_value(
            UnevaluableValueKind::ForRange,
            &range.into(),
        ));
    }
    let beg = if beg_comptime.is_const {
        let value = beg_comptime.get_value()?;
        // A strictly negative bound (signed value <= 0, nonzero payload)
        // would wrap through to_usize into a huge unsigned ForBound.
        if value.is_semantically_not_positive() && value.is_positive() {
            let token: TokenRange = range.into();
            context.insert_error(AnalyzerError::invalid_for_range(
                InvalidForRangeKind::NegativeBound,
                &token,
            ));
            return Err(ir_error!(token));
        }
        let signed = beg_comptime.r#type.signed;
        ir::ForBound::Const(const_for_bound(value, signed), signed)
    } else {
        ir::ForBound::Expression(Box::new(beg))
    };

    let (end, inclusive) = if let Some(x) = &range.range_opt {
        let mut end: ir::Expression = Conv::conv(context, x.expression.as_ref())?;
        let end_comptime = end.eval_comptime(context, Some(32));
        if require_const && !end_comptime.is_const {
            context.insert_error(AnalyzerError::unevaluable_value(
                UnevaluableValueKind::ForRange,
                &range.into(),
            ));
        }
        let end = if end_comptime.is_const {
            let value = end_comptime.get_value()?;
            if value.is_semantically_not_positive() && value.is_positive() {
                let token: TokenRange = range.into();
                context.insert_error(AnalyzerError::invalid_for_range(
                    InvalidForRangeKind::NegativeBound,
                    &token,
                ));
                return Err(ir_error!(token));
            }
            let signed = end_comptime.r#type.signed;
            ir::ForBound::Const(const_for_bound(value, signed), signed)
        } else {
            ir::ForBound::Expression(Box::new(end))
        };

        if matches!(x.range_operator.as_ref(), RangeOperator::DotDotEqu(_)) {
            (end, true)
        } else {
            (end, false)
        }
    } else {
        (beg.clone(), false)
    };

    Ok((beg, end, inclusive))
}

#[derive(Clone)]
pub struct ArrayLiteralExpression {
    pub index: Vec<usize>,
    pub select: Vec<usize>,
    pub expr: ir::Expression,
}

impl ArrayLiteralExpression {
    pub fn to_var_index(&self) -> VarIndex {
        let mut ret = vec![];
        for i in &self.index {
            let expr = ir::Expression::create_value(
                Value::new(*i as u64, 32, false),
                TokenRange::default(),
            );
            ret.push(expr);
        }
        VarIndex(ret)
    }

    pub fn to_var_select(&self) -> VarSelect {
        let mut ret = vec![];
        for i in &self.select {
            let expr = ir::Expression::create_value(
                Value::new(*i as u64, 32, false),
                TokenRange::default(),
            );
            ret.push(expr);
        }
        VarSelect(ret, None)
    }
}

/// A const array declared in another namespace arrives folded to one value per
/// element instead of an array literal; left whole it lowers to `unknown`.
fn eval_const_array(
    context_array: Option<&ShapeRef>,
    expr: &ir::Expression,
) -> Option<Vec<ArrayLiteralExpression>> {
    let array = context_array?;
    if array.is_empty() {
        return None;
    }

    let ir::Expression::Term(factor) = expr else {
        return None;
    };
    let ir::Factor::Value(comptime) = factor.as_ref() else {
        return None;
    };
    let ValueVariant::NumericArray(values) = &comptime.value else {
        return None;
    };
    // Same total but a different shape (`[2, 3]` into `[3, 2]`) is a type
    // error; expanding it would silently reshape instead.
    if comptime.r#type.array.as_slice() != array.as_slice() {
        return None;
    }
    let dims: Vec<usize> = array.iter().copied().collect::<Option<_>>()?;
    // A zero-length dimension would expand to no statement, dropping the assignment.
    if dims.contains(&0) || array.total()? != values.len() {
        return None;
    }

    // Cloned per element, so keeping the element list here would be quadratic.
    let mut element = comptime.clone();
    element.r#type.array = Shape::default();
    element.value = ValueVariant::Unknown;

    let ret = values
        .iter()
        .enumerate()
        .map(|(flat, value)| {
            // Row-major, matching `ShapeRef::calc_index`.
            let mut index = vec![0; dims.len()];
            let mut rest = flat;
            for (i, dim) in dims.iter().enumerate().rev() {
                index[i] = rest % dim;
                rest /= dim;
            }

            let mut comptime = element.clone();
            comptime.value = ValueVariant::Numeric(value.clone());
            ArrayLiteralExpression {
                index,
                select: vec![],
                expr: ir::Expression::Term(Box::new(ir::Factor::Value(comptime))),
            }
        })
        .collect();
    Some(ret)
}

pub fn eval_array_literal(
    context: &mut Context,
    context_array: Option<&ShapeRef>,
    context_width: Option<&ShapeRef>,
    expr: &mut ir::Expression,
) -> IrResult<Option<Vec<ArrayLiteralExpression>>> {
    let token = expr.token_range();

    if let Some(x) = eval_const_array(context_array, expr) {
        return Ok(Some(x));
    }

    let ir::Expression::ArrayLiteral(items, _) = expr else {
        return Ok(None);
    };

    let (is_array, context_array_width) = if let Some(x) = context_array
        && !x.is_empty()
    {
        (true, context_array)
    } else {
        (false, context_width)
    };

    let mut ret = vec![];
    if let Some(array_width) = context_array_width {
        let mut default = None;
        let mut len = 0;
        let mut index = 0;

        for item in items {
            // context_array/context_width for inner item
            let next_array_width: Option<&ShapeRef> = if array_width.dims() < 2 {
                None
            } else {
                Some(array_width[1..].into())
            };
            let (next_array, next_width) = if is_array {
                (next_array_width, context_width)
            } else {
                (None, next_array_width)
            };

            match item {
                ir::ArrayLiteralItem::Value(expr, repeat) => {
                    let repeat = if let Some(repeat) = repeat {
                        let repeat =
                            eval_repeat(context, repeat).ok_or_else(|| ir_error!(token))?;
                        let repeat = repeat.to_usize_saturating().unwrap_or(0);
                        context
                            .check_size(repeat, token)
                            .ok_or_else(|| ir_error!(token))?
                    } else {
                        1
                    };

                    let exprs = if let Some(x) =
                        eval_array_literal(context, next_array, next_width, expr)?
                    {
                        x
                    } else {
                        vec![ArrayLiteralExpression {
                            index: vec![],
                            select: vec![],
                            expr: expr.as_ref().clone(),
                        }]
                    };

                    for _ in 0..repeat {
                        let mut exprs = exprs.clone();
                        for expr in &mut exprs {
                            if is_array {
                                expr.index.insert(0, index);
                            } else {
                                expr.select.insert(0, index);
                            }
                        }
                        ret.append(&mut exprs);
                        index += 1;
                    }

                    len += repeat;
                }
                ir::ArrayLiteralItem::Defaul(expr) => {
                    let exprs = if let Some(x) =
                        eval_array_literal(context, next_array, next_width, expr)?
                    {
                        x
                    } else {
                        vec![ArrayLiteralExpression {
                            index: vec![],
                            select: vec![],
                            expr: expr.as_ref().clone(),
                        }]
                    };

                    if default.is_none() {
                        default = Some(exprs);
                    } else {
                        context.insert_error(AnalyzerError::multiple_default(
                            MultipleDefaultKind::ArrayLiteral,
                            "default",
                            &token,
                        ));
                        return Err(ir_error!(token));
                    }
                }
            }
        }

        if let Some(Some(target_len)) = array_width.get(0) {
            if let Some(x) = default {
                let remaining = target_len.checked_sub(len);
                if let Some(remaining) = remaining {
                    for _ in 0..remaining {
                        let mut exprs = x.clone();
                        for expr in &mut exprs {
                            if is_array {
                                expr.index.insert(0, index);
                            } else {
                                expr.select.insert(0, index);
                            }
                        }
                        ret.append(&mut exprs);
                        index += 1;
                    }
                } else {
                    context.insert_error(AnalyzerError::mismatch_type(
                        MismatchTypeKind::ArrayDimension {
                            expected: *target_len,
                            actual: len,
                        },
                        &token,
                    ));
                    return Err(ir_error!(token));
                }
            } else if *target_len != len {
                context.insert_error(AnalyzerError::mismatch_type(
                    MismatchTypeKind::ArrayDimension {
                        expected: *target_len,
                        actual: len,
                    },
                    &token,
                ));
                return Err(ir_error!(token));
            }
        } else {
            // TODO target_len is unknown
            return Err(ir_error!(token));
        }
    } else {
        // TODO error, not array context
        return Err(ir_error!(token));
    }

    Ok(Some(ret))
}

pub fn eval_repeat(context: &mut Context, expr: &mut ir::Expression) -> Option<Value> {
    let token = expr.token_range();
    let repeat = expr.eval_comptime(context, None);

    // array / type can't be operated
    if repeat.r#type.is_array() | repeat.r#type.is_type() {
        context.insert_error(AnalyzerError::invalid_operand(
            &repeat.r#type.to_string(),
            &Op::Repeat.to_string(),
            &token,
        ));
        return None;
    }

    if !repeat.is_const {
        context.insert_error(AnalyzerError::invalid_operand(
            "non const value",
            &Op::Repeat.to_string(),
            &token,
        ));
        return None;
    }

    match &repeat.value {
        ValueVariant::Numeric(repeat) => Some(repeat.clone()),
        ValueVariant::NumericArray(_) | ValueVariant::Type(_) => {
            context.insert_error(AnalyzerError::invalid_operand(
                &repeat.r#type.to_string(),
                &Op::Repeat.to_string(),
                &token,
            ));
            None
        }
        ValueVariant::Unknown => None,
    }
}

pub fn eval_size(
    context: &mut Context,
    expr: &Expression,
    allow_inferable_size: bool,
) -> IrResult<(Comptime, Option<usize>)> {
    let (comptime, expr) = eval_expr(context, None, expr, allow_inferable_size)?;
    if comptime.r#type.is_type() {
        let token = expr.token_range();
        context.insert_error(AnalyzerError::invalid_size_type(&token));
        return Err(ir_error!(token));
    }
    // Only a value that is really zero is a zero size. One with X/Z bits, or
    // one too wide for `usize`, is not known and must not be reported as
    // zero; a non-constant cast operand reaches here the same way.
    if let Ok(x) = comptime.get_value()
        && let Some(value) = x.to_usize_saturating()
    {
        let value = context.check_size(value, expr.token_range());
        // A zero size emits `[X-1:0]`, which tools disagree on: Verilator
        // rejects it and most others silently make it 2 bits.
        if value == Some(0) {
            context.insert_error(AnalyzerError::zero_size(&expr.token_range()));
            Ok((comptime, None))
        } else {
            Ok((comptime, value))
        }
    } else {
        Ok((comptime, None))
    }
}

/// A declaration the active defines guard out is not one placed further down,
/// and saying so sends the reader to the wrong line.
fn report_unreachable_definition(context: &mut Context, definition: Token, reference: &TokenRange) {
    let define_context: DefineContext = definition.into();
    let error = if define_context.is_active(&context.config.defines) {
        AnalyzerError::referring_before_definition(&definition.to_string(), reference)
    } else {
        AnalyzerError::referring_inactive_definition(&definition.to_string(), reference)
    };
    context.insert_error(error);
}

/// A write to a variable declared further down is invisible to every analysis,
/// while the emitter still emits it.
pub fn check_assign_before_definition<T: Into<SymbolPathNamespace>>(
    context: &mut Context,
    identifier: T,
    token: Token,
) {
    if let Ok(symbol) = symbol_table::resolve(identifier)
        && let SymbolKind::Variable(x) = &symbol.found.kind
        && x.affiliation == Affiliation::Module
        // A module-level variable is registered under its bare name, so a miss
        // means the declaration is still ahead of the write.
        && context
            .find_path(&VarPath::new(symbol.found.token.text))
            .is_none()
    {
        report_unreachable_definition(context, symbol.found.token, &token.into());
    }
}

/// Per-destination clock/CDC checks for an assignment (invalid clock assign,
/// Implicit-domain inference, dst-vs-RHS and dst-vs-always_ff domain). Shared
/// by the scalar and concatenation-LHS paths, which build AssignStatement directly.
pub fn check_assign_clock_domain(
    context: &mut Context,
    dst: &mut ir::AssignDestination,
    comptime: &ir::Comptime,
    token: &TokenRange,
) {
    if (dst.comptime.r#type.is_clock() || dst.comptime.r#type.is_reset())
        && context.is_affiliated(Affiliation::AlwaysFf)
    {
        context.insert_error(AnalyzerError::invalid_clock_assignment(
            &dst.comptime.r#type.to_string(),
            token,
        ));
    }

    if dst.comptime.clock_domain == ClockDomain::Implicit {
        let inferred = if context.is_affiliated(Affiliation::AlwaysFf) {
            context
                .current_clock
                .as_ref()
                .and_then(|c| c.clock_domain.domain_id())
        } else {
            comptime.clock_domain.domain_id()
        };
        if let Some(id) = inferred {
            dst.comptime.clock_domain = ClockDomain::Inferred(id);
            if let Some((_, path_comptime)) = context.var_paths.get_mut(&dst.path) {
                path_comptime.clock_domain = ClockDomain::Inferred(id);
            }
        }
    }

    let mut dst_comptime_for_cdc = dst.comptime.clone();
    dst_comptime_for_cdc.token = dst.token;
    check_clock_domain(context, &dst_comptime_for_cdc, comptime, &token.beg);

    if context.is_affiliated(Affiliation::AlwaysFf)
        && let Some(clock) = context.current_clock.clone()
    {
        check_clock_domain(context, &dst_comptime_for_cdc, &clock, &token.beg);
    }

    // A statement condition gates the write like a mux select: a foreign-domain
    // if/case/switch condition is the same CDC as the expression form
    // (`x = if c {..}`) that the ternary path already reports.
    for cond in context.condition_domains.clone() {
        check_clock_domain(context, &dst_comptime_for_cdc, &cond, &token.beg);
    }
}

pub fn eval_assign_statement(
    context: &mut Context,
    dst: &mut ir::AssignDestination,
    expr: &mut (ir::Comptime, ir::Expression),
    token: TokenRange,
) -> IrResult<Vec<ir::Statement>> {
    let (comptime, expr) = expr;

    check_assign_clock_domain(context, dst, comptime, &token);

    let width = dst.total_width(context);
    let mut ret = vec![];

    let array_exprs = eval_array_literal(
        context,
        Some(&dst.comptime.r#type.array),
        Some(dst.comptime.r#type.width()),
        expr,
    )?;
    if let Some(exprs) = array_exprs {
        for mut expr in exprs {
            check_reset_non_elaborative(context, &mut expr.expr);

            let index = expr.to_var_index();
            let select = expr.to_var_select();

            let mut dst = dst.clone();
            dst.index.append(&index);
            // The emitted RHS initializes the indexed element. Preserve only
            // dimensions not consumed by this lowering; explicit LHS indices
            // have already been removed from the destination type.
            dst.comptime.r#type.array.drain(0..index.dimension());
            dst.select = select;

            let statement = ir::Statement::Assign(ir::AssignStatement {
                hier_dst: None,
                dst: vec![dst],
                width,
                expr: expr.expr,
                token,
            });
            ret.push(statement);
        }
    } else {
        check_reset_non_elaborative(context, expr);

        let statement = ir::Statement::Assign(ir::AssignStatement {
            hier_dst: None,
            dst: vec![dst.clone()],
            width,
            expr: expr.clone(),
            token,
        });
        ret.push(statement);
    }

    Ok(ret)
}

/// IEEE 1800 sizes an assignment RHS against the LHS *select*, not the whole
/// variable.  Only observable when the RHS is no wider than the select, since
/// the context is the max of the two: with an 8-bit `y`, `x[7:0] = (y << 4)
/// >> 4` is 0x0d at 8 bits and 0xcd at a 32-bit `x`'s width.
pub fn assign_rhs_context_type(context: &mut Context, dst: &ir::AssignDestination) -> ir::Type {
    let full = dst.comptime.r#type.clone();
    if dst.select.is_empty() || dst.comptime.part_select.is_some() {
        return full;
    }
    if !matches!(full.kind, ir::TypeKind::Logic | ir::TypeKind::Bit) {
        return full;
    }
    let Some(w) = dst.total_width(context) else {
        return full;
    };
    if w == 0 || full.total_width().is_none_or(|fw| w >= fw) {
        return full;
    }
    let mut t = full;
    t.set_concrete_width(Shape::new(vec![Some(w)]));
    t
}

/// Expand an array-range assignment LHS (`o[0+:N] = '{...}`) into one assignment
/// per covered element (recursing inner dims for multi-dim arrays). Returns `None`
/// to defer to the scalar path when the LHS isn't a range or the RHS isn't an array
/// literal; an invalid slice is rejected.
pub fn eval_array_range_assign(
    context: &mut Context,
    lhs: &VarPathSelect,
    rhs: &Expression,
    token: TokenRange,
) -> IrResult<Option<Vec<ir::Statement>>> {
    let (_, select, _) = lhs.clone().into();
    let Some((_, mut comptime)) = context.find_path(&lhs.0) else {
        return Ok(None);
    };
    let array_dims = comptime.rebase_part_select();
    let (array_select, _) = select.split(array_dims);
    if !array_select.is_range() {
        return Ok(None);
    }

    let dsts = lhs.clone().to_assign_destinations(context, false);
    if dsts.is_empty() {
        // Invalid range (to_assign_destinations validates and reports it). Type-check
        // the RHS, but with no `?`: a propagated error would roll back that diagnostic.
        let _ = eval_expr(context, None, rhs, false);
        return Ok(Some(vec![]));
    }

    // Type-check the RHS against the slice type ([n] prepended to the element dims).
    let n = dsts.len();
    let elem_type = dsts[0].comptime.r#type.clone();
    let mut sub_type = elem_type.clone();
    let mut dims = vec![Some(n)];
    dims.extend(elem_type.array.iter().copied());
    sub_type.array = Shape::new(dims);
    let (rhs_comptime, mut rhs_expr) = eval_expr(context, Some(sub_type), rhs, false)?;

    // Pair each outer literal item with one element dst; `eval_assign_statement`
    // recurses the element's inner dims. (A flat `eval_array_literal` would over-
    // recurse and mis-decompose a multi-dim element.) A non-literal RHS has no
    // lowering: the scalar path can't take a range either.
    let ir::Expression::ArrayLiteral(items, _) = &mut rhs_expr else {
        context.insert_error(AnalyzerError::invalid_range_assign(&token));
        return Ok(Some(vec![]));
    };
    let mut outer: Vec<ir::Expression> = Vec::new();
    let mut default: Option<ir::Expression> = None;
    let mut repeat_unresolved = false;
    for item in items.iter_mut() {
        match item {
            ir::ArrayLiteralItem::Value(expr, repeat) => {
                let count = if let Some(repeat) = repeat {
                    match eval_repeat(context, repeat)
                        .and_then(|v| v.to_usize_saturating())
                        .and_then(|n| context.check_size(n, token))
                    {
                        Some(count) => count,
                        // Non-const repeat: already reported by eval_repeat. Skip the
                        // count below so we don't pile on a spurious dimension error.
                        None => {
                            repeat_unresolved = true;
                            0
                        }
                    }
                } else {
                    1
                };
                for _ in 0..count {
                    outer.push(expr.as_ref().clone());
                }
            }
            ir::ArrayLiteralItem::Defaul(expr) => {
                if default.is_some() {
                    context.insert_error(AnalyzerError::multiple_default(
                        MultipleDefaultKind::ArrayLiteral,
                        "default",
                        &token,
                    ));
                    return Ok(Some(vec![]));
                }
                default = Some(expr.as_ref().clone());
            }
        }
    }
    if let Some(def) = default {
        while outer.len() < n {
            outer.push(def.clone());
        }
    }
    // The one-level walk bypasses `eval_array_literal`'s count check, so verify the
    // item count here (else a mismatch is silently dropped and emits illegal SV).
    if outer.len() != n && !repeat_unresolved {
        context.insert_error(AnalyzerError::mismatch_type(
            MismatchTypeKind::ArrayDimension {
                expected: n,
                actual: outer.len(),
            },
            &token,
        ));
        return Ok(Some(vec![]));
    }

    let mut statements = vec![];
    for (mut dst, sub_expr) in dsts.into_iter().zip(outer) {
        let mut expr = (rhs_comptime.clone(), sub_expr);
        statements.extend(eval_assign_statement(context, &mut dst, &mut expr, token)?);
    }
    Ok(Some(statements))
}

fn eval_array_literal_expressions(
    context: &mut Context,
    r#type: &ir::Type,
    exprs: Vec<ArrayLiteralExpression>,
) -> IrResult<Option<Vec<Value>>> {
    let mut ret = vec![];

    let mut value: Option<Value> = None;
    let mut prev = None;
    for expr in exprs {
        if prev != Some(expr.index.clone())
            && let Some(x) = value
        {
            ret.push(x);
            value = None;
        }

        let mut part_type = r#type.clone();
        part_type.width_mut().drain(0..expr.select.len());

        if let Some(mut part_value) = expr.expr.eval_value(context) {
            // A `string` has no declared width -- `total_width()` answers 1 for
            // it -- so the element carries its own, and truncating to the
            // declared type would leave one bit of the text.
            if !part_type.is_string() {
                // The parts of one element are concatenated, so a width that
                // will not resolve would lay them out at their own widths.
                let Some(part_width) = part_type.total_width() else {
                    return Ok(None);
                };
                part_value.trunc(part_width);
            }

            value = if let Some(x) = value {
                Some(x.concat(&part_value))
            } else {
                Some(part_value)
            };
        } else {
            value = None;
        }

        prev = Some(expr.index);
    }

    if let Some(x) = value {
        ret.push(x);
    }

    Ok(Some(ret))
}

/// Fold an array-literal expression into its per-element values, or `None`
/// when it isn't a resolvable array literal.
fn eval_array_literal_values(
    context: &mut Context,
    r#type: &ir::Type,
    expr: &mut ir::Expression,
) -> IrResult<Option<Vec<Value>>> {
    let Some(exprs) = eval_array_literal(context, Some(&r#type.array), Some(r#type.width()), expr)?
    else {
        return Ok(None);
    };
    eval_array_literal_expressions(context, r#type, exprs)
}

/// Register a const/param variable from its element `values`. The scalar arm
/// of `eval_const_assign` also expands struct/union members, so it can't use
/// this.
fn insert_const_variable(
    context: &mut Context,
    dst: &ir::AssignDestination,
    kind: VarKind,
    r#type: &ir::Type,
    comptime: Comptime,
    values: Vec<Value>,
) {
    let id = context.insert_var_path(dst.path.clone(), comptime);
    let array_limit = context.config.evaluate_array_limit;
    let variable = Variable::new(
        id,
        dst.path.clone(),
        kind,
        r#type.clone(),
        values,
        context.get_affiliation(),
        &dst.token,
        array_limit,
    );
    context.insert_variable(id, variable);
}

/// Fit each element to the destination element width. Values copied from a
/// source variable (inherited/sliced array params) keep the source width, so a
/// narrower signed source must be sign-extended -- the array-literal path can't
/// hit this because it evaluates each element in the destination type context.
/// A width that isn't a real one is left untouched: `None`, and `string`, whose
/// `total_width()` answers 1 while the text lives in the element itself.
fn fit_array_elements(mut values: Vec<Value>, r#type: &ir::Type) -> Vec<Value> {
    if r#type.is_string() {
        return values;
    }
    if let Some(total_width) = r#type.total_width() {
        for value in &mut values {
            if value.width() > total_width {
                value.trunc(total_width);
            } else if value.width() < total_width {
                *value = value.expand(total_width, value.signed()).into_owned();
            }
            // Adopt the destination type's signedness (see eval_const_assign).
            value.set_signed(r#type.signed);
        }
    }
    values
}

pub fn eval_const_assign(
    context: &mut Context,
    kind: VarKind,
    dst: &ir::AssignDestination,
    expr: &mut (ir::Comptime, ir::Expression),
) -> IrResult<()> {
    let (comptime, expr) = expr;
    // Same unfolded form `get_overridden_params` handles: an indexed read of
    // an unpacked-array const arrives const but valueless, and left alone the
    // const stays unresolved.  An array literal keeps its own path.
    if comptime.value.is_unknown()
        && comptime.is_const
        && let Some(value) = expr.eval_value(context)
    {
        comptime.value = ValueVariant::Numeric(value);
    }
    let mut comptime = comptime.clone();
    let path = &dst.path;
    let r#type = &dst.comptime.r#type;
    let token = expr.token_range();

    match expr {
        // The guard skips an override literal, which already carries its values
        // as a NumericArray (below), so the literal isn't folded twice.
        ir::Expression::ArrayLiteral(_, _)
            if !matches!(comptime.value, ValueVariant::NumericArray(_)) =>
        {
            // A constant absent from the path table reads as one placed ahead
            // of its own declaration, so it is bound valueless instead.
            let values = eval_array_literal_values(context, r#type, expr)?.unwrap_or_default();
            insert_const_variable(context, dst, kind, r#type, comptime, values);
        }
        _ => {
            match &comptime.value {
                ValueVariant::Numeric(value) => {
                    let mut value = value.clone();
                    // Giving up on a width that will not resolve would leave the
                    // constant out of the path table, where a later reference to
                    // it reads as one placed ahead of its own declaration.
                    if !comptime.r#type.is_string() {
                        // Normalize to the declared type: extend by the RHS's own
                        // signedness, then adopt the type's signed flag — downstream folds
                        // (==, <:, /, ternary, casts) trust it, and a stray RHS flag
                        // diverges from the emitted SV.
                        if let Some(total_width) = comptime.r#type.total_width() {
                            if value.width() < total_width && value.width() != 0 {
                                value = value.expand(total_width, value.signed()).into_owned();
                            }
                            value.trunc(total_width);
                        }
                        value.set_signed(r#type.signed);
                    }

                    // Keep constant metadata consistent with the stored Variable:
                    // later folds can also read the value without a variable table.
                    comptime.value = ValueVariant::Numeric(value.clone());
                    // A later reference has its own expression context, not the
                    // initializer's width/signedness cached by eval_expr.
                    comptime.evaluated = false;
                    let id = context.insert_var_path(path.clone(), comptime);

                    for x in r#type.expand_struct_union(path, &[], None) {
                        let r#type = x.part_select.last().unwrap().r#type.clone();
                        let mut comptime = Comptime::from_type(r#type, ClockDomain::None, token);
                        comptime.is_const = true;
                        let path = x.path.clone();
                        // Carry the field's bit offset so a member read selects
                        // that field instead of truncating the whole struct to
                        // its lowest field.
                        comptime.part_select = Some(x);
                        context.insert_var_path_with_id(path, id, comptime);
                    }

                    let array_limit = context.config.evaluate_array_limit;
                    let variable = Variable::new(
                        id,
                        path.clone(),
                        kind,
                        r#type.clone(),
                        vec![value],
                        context.get_affiliation(),
                        &dst.token,
                        array_limit,
                    );
                    context.insert_variable(id, variable);
                }
                ValueVariant::NumericArray(values) => {
                    // An array override resolved by `get_overridden_params`
                    // (inheriting `#(XS)` or slicing `#(YS: XS[0])`). Not
                    // materializing it would leave later `XS[0]` reads dangling.
                    let values = fit_array_elements(values.clone(), r#type);
                    insert_const_variable(context, dst, kind, r#type, comptime, values);
                }
                ValueVariant::Type(x) => {
                    let mut comptime = comptime.clone();
                    comptime.value = ValueVariant::Type(x.clone());
                    context.insert_var_path(path.clone(), comptime);
                }
                ValueVariant::Unknown => {
                    // The variable behind the path is what the const-assignment
                    // check and the simulator look for.
                    insert_const_variable(context, dst, kind, r#type, comptime, vec![]);
                }
            }
        }
    }

    Ok(())
}

pub fn eval_variable(
    context: &mut Context,
    path: &VarPath,
    kind: VarKind,
    r#type: &ir::Type,
    clock_domain: ClockDomain,
    token: TokenRange,
) {
    let comptime = Comptime::from_type(r#type.clone(), clock_domain, token);
    let signed = comptime.r#type.signed;
    let id = context.insert_var_path(path.clone(), comptime);

    // Every element starts as the same x-state template, so store it once;
    // the simulator replicates it across the full `r#type.total_array()` at
    // fill time. Const/param arrays with per-element literals go through
    // `eval_array_literal` instead and keep their Vec<Value> intact.
    let values = if let Some(total_width) = r#type.total_width() {
        vec![Value::new_x(total_width, signed)]
    } else {
        vec![]
    };

    for x in r#type.expand_struct_union(path, &[], None) {
        let r#type = x.part_select.last().unwrap().r#type.clone();
        let mut comptime = Comptime::from_type(r#type, clock_domain, token);
        let path = x.path.clone();
        comptime.part_select = Some(x);
        context.insert_var_path_with_id(path, id, comptime);
    }

    let array_limit = context.config.evaluate_array_limit;
    let variable = Variable::new(
        id,
        path.clone(),
        kind,
        r#type.clone(),
        values,
        context.get_affiliation(),
        &token,
        array_limit,
    );
    context.insert_variable(id, variable);
}

fn check_reset_non_elaborative(context: &mut Context, expr: &mut ir::Expression) {
    let comptime = expr.eval_comptime(context, None);
    if context.in_if_reset && !comptime.is_const {
        context.insert_error(AnalyzerError::unevaluable_value(
            UnevaluableValueKind::ResetValue,
            &comptime.token,
        ));
    }
}

pub fn eval_struct_member(
    context: &mut Context,
    member_symbol: &Symbol,
    path: &GenericSymbolPath,
    mut member_path: VarPath,
    token: TokenRange,
) -> IrResult<ir::Factor> {
    fn get_member_type(context: &mut Context, member_symbol: &Symbol) -> IrResult<ir::Type> {
        let SymbolKind::StructMember(member) = &member_symbol.kind else {
            unreachable!();
        };

        member.r#type.to_ir_type(context, TypePosition::Variable)
    }

    let mut parent_path = path.clone();
    if let Some(x) = parent_path.paths.pop() {
        member_path.add_prelude(&[x.base.text]);
    }

    if let Ok(symbol) = symbol_table::resolve(&parent_path) {
        match &symbol.found.kind {
            SymbolKind::Parameter(x) if !x.is_proto => {
                let path = VarPath::new(symbol.found.token.text);
                // A member of an overridden parameter is not the member of the
                // declaration default.
                let overridden = context
                    .get_override(&symbol.found.namespace, &path)
                    .map(|(c, _)| c.clone());

                if overridden.is_some() || x.value.is_some() {
                    let r#type = x.r#type.to_ir_type(context, TypePosition::Variable)?;
                    let whole = if let Some(x) = overridden {
                        x
                    } else {
                        let expr = x.value.as_ref().ok_or_else(|| ir_error!(token))?;
                        let (comptime, mut expr) =
                            eval_expr(context, Some(r#type.clone()), expr, false)?;
                        // An array literal's per-element values are carried by
                        // the comptime `eval_expr` builds; `eval_comptime`
                        // alone leaves an array literal unevaluated.
                        if matches!(comptime.value, ValueVariant::NumericArray(_)) {
                            comptime
                        } else {
                            expr.eval_comptime(context, None).clone()
                        }
                    };

                    member_path.add_prelude(&path.0);
                    for x in r#type.expand_struct_union(&path, &[], None) {
                        if x.path == member_path {
                            let mut comptime = whole.clone();
                            comptime.token = token;
                            // Extract the field value from the full struct value.
                            // part_select encodes the bit position of the field: the sum of
                            // all pos values gives the LSB (end), and the last entry's type
                            // width gives the field width (beg = end + width - 1).
                            let end: usize = x.part_select.iter().map(|ps| ps.pos).sum();
                            let mut member_type = get_member_type(context, member_symbol)?;
                            member_type.array = r#type.array.clone();
                            if let Some(width) =
                                x.part_select.last().and_then(|ps| ps.r#type.total_width())
                            {
                                let beg = end + width - 1;
                                // `Value::select` drops the member's sign.
                                let field = |v: &Value| {
                                    let mut v = v.select(beg, end);
                                    v.set_signed(member_type.signed);
                                    v
                                };
                                comptime.value = match &comptime.value {
                                    ValueVariant::Numeric(v) => ValueVariant::Numeric(field(v)),
                                    // Every element holds a whole struct, so the
                                    // field is taken element by element and the
                                    // array dimension stays on the type.
                                    ValueVariant::NumericArray(v) => {
                                        ValueVariant::NumericArray(v.iter().map(field).collect())
                                    }
                                    v => v.clone(),
                                };
                            }
                            comptime.r#type = member_type;
                            return Ok(ir::Factor::Value(comptime));
                        }
                    }
                }
                Err(ir_error!(token))
            }
            SymbolKind::Parameter(x) if x.is_proto => {
                let path = VarPath::new(symbol.found.token.text);
                let r#type = x.r#type.to_ir_type(context, TypePosition::Variable)?;
                member_path.add_prelude(&path.0);
                for x in r#type.expand_struct_union(&path, &[], None) {
                    if x.path == member_path {
                        let member_type = get_member_type(context, member_symbol)?;
                        let mut comptime =
                            Comptime::from_type(member_type, ClockDomain::None, token);
                        comptime.is_const = true;
                        return Ok(ir::Factor::Value(comptime));
                    }
                }
                Err(ir_error!(token))
            }
            SymbolKind::GenericParameter(x) => match &x.bound {
                GenericBoundKind::Type => {
                    let mut comptime = Comptime::create_unknown(token);
                    comptime.is_const = true;
                    Ok(ir::Factor::Value(comptime))
                }
                GenericBoundKind::Proto(x) => {
                    let r#type = x.to_ir_type(context, TypePosition::Variable)?;
                    let mut comptime = Comptime::from_type(r#type, ClockDomain::None, token);
                    comptime.is_const = true;
                    Ok(ir::Factor::Value(comptime))
                }
                _ => Err(ir_error!(token)),
            },
            SymbolKind::StructMember(_) => {
                eval_struct_member(context, member_symbol, &parent_path, member_path, token)
            }
            _ => Err(ir_error!(token)),
        }
    } else {
        Err(ir_error!(token))
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum TypePosition {
    Variable,
    Modport,
    Cast,
    Enum,
    Generic,
    TypeDef,
}

pub fn eval_type(
    context: &mut Context,
    path: &GenericSymbolPath,
    pos: TypePosition,
) -> IrResult<ir::Type> {
    // `_` is not a type; without this the decl emits an empty type keyword (invalid SV).
    if path.is_anonymous() {
        let token: TokenRange = path.range;
        context.insert_error(AnalyzerError::anonymous_identifier_usage(&token));
        return Err(ir_error!(token));
    }

    let mut width = Shape::default();
    let mut array = Shape::default();
    let mut signed = false;
    let mut is_positive = false;

    // The `var_paths` shortcut below turns a constant into a width, which is what
    // makes `x as W` work -- so a variable position has to be rejected ahead of it.
    let resolved = if matches!(pos, TypePosition::Variable) {
        let resolved = context.resolve_path(path.clone());
        if let Ok(symbol) = symbol_table::resolve(&resolved)
            && !symbol.found.is_variable_type()
        {
            context.insert_error(AnalyzerError::mismatch_type(
                MismatchTypeKind::SymbolKind {
                    name: symbol.found.token.to_string(),
                    expected: "enum, union, struct or typedef".to_string(),
                    actual: symbol.found.kind.to_kind_name(),
                },
                &path.range,
            ));
        }
        Some(resolved)
    } else {
        None
    };

    let non_const_cast = matches!(pos, TypePosition::Cast)
        && path
            .to_var_path()
            .is_some_and(|x| context.var_paths.get(&x).is_some_and(|x| !x.1.is_const));
    if non_const_cast {
        let resolved = context.resolve_path(path.clone());
        if let Ok(symbol) = symbol_table::resolve(&resolved) {
            context.insert_error(AnalyzerError::mismatch_type(
                MismatchTypeKind::SymbolKind {
                    name: symbol.found.token.to_string(),
                    expected: "enum, union, struct, typedef or integer constant".to_string(),
                    actual: symbol.found.kind.to_kind_name(),
                },
                &path.range,
            ));
        }
    }

    let kind = if let Some(x) = path.to_var_path()
        && let Some(x) = context.var_paths.get(&x)
    {
        match &x.1.value {
            ValueVariant::Type(x) => {
                let mut x = x.clone();

                // append internal width/array
                width.append(x.width_mut());
                array.append(&mut x.array);
                signed = x.signed;

                x.kind
            }
            ValueVariant::Numeric(x) => {
                let value = x.to_usize_saturating().unwrap_or(0);
                let value = context.check_size(value, path.paths[0].base.into());
                width.push(value);
                ir::TypeKind::Bit
            }
            _ => ir::TypeKind::Unknown,
        }
    } else {
        let mut path = resolved.unwrap_or_else(|| context.resolve_path(path.clone()));
        check_generic_refereence(context, &path);

        let map = path.to_generic_maps();
        if let Ok(symbol) = symbol_table::resolve(&path) {
            if matches!(pos, TypePosition::Cast) && !symbol.found.is_casting_type() {
                context.insert_error(AnalyzerError::mismatch_type(
                    MismatchTypeKind::SymbolKind {
                        name: symbol.found.token.to_string(),
                        expected: "enum, union, struct, typedef or integer constant".to_string(),
                        actual: symbol.found.kind.to_kind_name(),
                    },
                    &path.range,
                ));
            }

            match &symbol.found.kind {
                SymbolKind::Struct(x) => {
                    context.push_generic_map(map.clone());

                    let members = context.block(|c| {
                        let mut members = vec![];
                        for x in &x.members {
                            let member = symbol_table::get(*x).unwrap();
                            let name = member.token.text;

                            if let SymbolKind::StructMember(x) = &member.kind {
                                if symbol.found.token.text == x.r#type.token.beg.text {
                                    // Prevent cyclic reference
                                    continue;
                                }

                                let r#type = x.r#type.to_ir_type(c, TypePosition::Variable)?;
                                check_unpacked_member(c, &member, &x.r#type.token, &r#type);
                                members.push(ir::TypeKindMember { name, r#type });
                            }
                        }

                        check_struct_union_members(c, &members, &symbol.found);
                        Ok(members)
                    });

                    context.pop_generic_map();

                    ir::TypeKind::Struct(Arc::new(ir::TypeKindStruct {
                        id: symbol.found.id,
                        members: members?,
                    }))
                }
                SymbolKind::Union(x) => {
                    context.push_generic_map(map.clone());

                    let members = context.block(|c| {
                        let mut members = vec![];
                        for x in &x.members {
                            let member = symbol_table::get(*x).unwrap();
                            let name = member.token.text;
                            if let SymbolKind::UnionMember(x) = &member.kind {
                                if symbol.found.token.text == x.r#type.token.beg.text {
                                    // Prevent cyclic reference
                                    continue;
                                }

                                let r#type = x.r#type.to_ir_type(c, TypePosition::Variable)?;
                                check_unpacked_member(c, &member, &x.r#type.token, &r#type);
                                members.push(ir::TypeKindMember { name, r#type });
                            }
                        }

                        check_struct_union_members(c, &members, &symbol.found);
                        Ok(members)
                    });

                    context.pop_generic_map();

                    ir::TypeKind::Union(Arc::new(ir::TypeKindUnion {
                        id: symbol.found.id,
                        members: members?,
                    }))
                }
                SymbolKind::Enum(x) => {
                    let r#type = if let Some(enum_type) = &x.r#type {
                        context.push_generic_map(map.clone());

                        let mut ret =
                            context.block(|c| enum_type.to_ir_type(c, TypePosition::Enum));
                        if let Ok(r#type) = ret.as_mut() {
                            // Infer width from member variants
                            if r#type.is_inferable_width() {
                                r#type.width_mut().replace(0, Some(x.width));
                            }
                        }

                        context.pop_generic_map();

                        ret?
                    } else {
                        {
                            let mut t = ir::Type::new(ir::TypeKind::Logic);
                            t.set_concrete_width(Shape::new(vec![Some(x.width)]));
                            t
                        }
                    };
                    ir::TypeKind::Enum(Arc::new(ir::TypeKindEnum {
                        id: symbol.found.id,
                        r#type: Box::new(r#type),
                    }))
                }
                SymbolKind::Modport(_) => {
                    // Remove modport name
                    path.paths.pop();
                    let token: TokenRange = symbol.found.token.into();
                    let sig =
                        Signature::from_path(context, path).ok_or_else(|| ir_error!(token))?;
                    ir::TypeKind::Modport(sig.into(), symbol.found.token.text)
                }
                SymbolKind::TypeDef(x) if !x.is_proto => {
                    if let Some(ty) = &x.r#type
                        && context.push_typedef_visiting(symbol.found.id)
                    {
                        context.push_generic_map(map.clone());

                        let r#type = context.block(|c| ty.to_ir_type(c, TypePosition::TypeDef));

                        context.pop_generic_map();
                        context.pop_typedef_visiting();

                        let mut r#type = r#type?;

                        width.append(r#type.width_mut());
                        array.append(&mut r#type.array);
                        signed = r#type.signed;

                        r#type.kind
                    } else {
                        // Cyclic typedef chain (type_dag already reports it);
                        // stop expanding instead of recursing forever.
                        ir::TypeKind::Unknown
                    }
                }
                SymbolKind::Parameter(x) if x.is_proto => {
                    if x.r#type.kind.is_type() {
                        ir::TypeKind::Unknown
                    } else {
                        let token: TokenRange = symbol.found.token.into();
                        return Err(ir_error!(token));
                    }
                }
                SymbolKind::TypeDef(x) if x.is_proto => {
                    if let Some(x) = &x.r#type {
                        let mut r#type = x.to_ir_type(context, TypePosition::TypeDef)?;
                        width.append(r#type.width_mut());
                        array.append(&mut r#type.array);
                        signed = r#type.signed;

                        r#type.kind
                    } else {
                        ir::TypeKind::Unknown
                    }
                }
                SymbolKind::SystemVerilog => ir::TypeKind::SystemVerilog,
                SymbolKind::Interface(_) => {
                    let token: TokenRange = symbol.found.token.into();
                    let sig =
                        Signature::from_path(context, path).ok_or_else(|| ir_error!(token))?;
                    ir::TypeKind::Interface(sig.into())
                }
                SymbolKind::GenericParameter(x) => match &x.bound {
                    GenericBoundKind::Proto(x) => {
                        let mut r#type = x.to_ir_type(context, pos)?;
                        width.append(r#type.width_mut());
                        array.append(&mut r#type.array);
                        signed = r#type.signed;

                        r#type.kind
                    }
                    GenericBoundKind::Type => {
                        if let Some(x) = &x.default_value {
                            return eval_type(context, x, pos);
                        } else {
                            ir::TypeKind::Unknown
                        }
                    }
                    _ => ir::TypeKind::Unknown,
                },
                SymbolKind::GenericConst(x) => match &x.bound {
                    GenericBoundKind::Proto(x) => {
                        let mut r#type = x.to_ir_type(context, pos)?;
                        width.append(r#type.width_mut());
                        array.append(&mut r#type.array);
                        signed = r#type.signed;

                        r#type.kind
                    }
                    GenericBoundKind::Type => {
                        let (comptime, _) = eval_generic_expr(context, &x.value)?;
                        if let ValueVariant::Type(mut x) = comptime.value {
                            width.append(x.width_mut());
                            array.append(&mut x.array);
                            signed = x.signed;
                            x.kind
                        } else {
                            ir::TypeKind::Unknown
                        }
                    }
                    _ => ir::TypeKind::Unknown,
                },
                SymbolKind::Parameter(x) if !x.is_proto => {
                    if x.r#type.kind.is_type() {
                        if let Some(expr) = &x.value {
                            context.push_generic_map(map.clone());

                            let expr = context.block(|c| eval_expr(c, None, expr, false));

                            context.pop_generic_map();

                            let (comptime, _) = expr?;
                            if let ValueVariant::Type(mut r#type) = comptime.value {
                                width.append(r#type.width_mut());
                                array.append(&mut r#type.array);
                                signed = r#type.signed;
                                r#type.kind
                            } else {
                                ir::TypeKind::Unknown
                            }
                        } else {
                            ir::TypeKind::Unknown
                        }
                    } else {
                        let token: TokenRange = symbol.found.token.into();
                        return Err(ir_error!(token));
                    }
                }
                SymbolKind::TbComponent(x)
                    if matches!(
                        x.kind,
                        TbComponentKind::File
                            | TbComponentKind::External(_)
                            | TbComponentKind::Random
                    ) =>
                {
                    if !context.in_test_module {
                        let token: TokenRange = path.paths[0].base.into();
                        context.insert_error(AnalyzerError::invalid_tb_usage(&token));
                    }

                    if matches!(x.kind, TbComponentKind::Random)
                        && let Some(arg) =
                            path.paths.last().and_then(|p| p.arguments.first()).cloned()
                    {
                        // `$tb::random::<T>`'s element type is its generic argument
                        // (already resolved through the generic maps above); its
                        // validity is diagnosed by `check_generic_refereence`. The
                        // file/component descriptor lives in the simulator and has
                        // no element type, so its slot is backed by a throwaway
                        // 32-bit width.
                        return eval_type(context, &arg, pos);
                    }

                    width.push(Some(32));
                    ir::TypeKind::Bit
                }
                _ => {
                    let token: TokenRange = symbol.found.token.into();
                    return Err(ir_error!(token));
                }
            }
        } else if matches!(path.kind, GenericSymbolPathKind::TypeLiteral)
            && path.paths.len() == 1
            && path.paths[0].arguments.is_empty()
        {
            // Fixed type given as generic arg
            match path.paths[0].base.to_string().as_str() {
                "p8" => {
                    width.push(Some(8));
                    is_positive = true;
                    ir::TypeKind::Bit
                }
                "p16" => {
                    width.push(Some(16));
                    is_positive = true;
                    ir::TypeKind::Bit
                }
                "p32" => {
                    width.push(Some(32));
                    is_positive = true;
                    ir::TypeKind::Bit
                }
                "p64" => {
                    width.push(Some(64));
                    is_positive = true;
                    ir::TypeKind::Bit
                }
                "u8" => {
                    width.push(Some(8));
                    ir::TypeKind::Bit
                }
                "u16" => {
                    width.push(Some(16));
                    ir::TypeKind::Bit
                }
                "u32" => {
                    width.push(Some(32));
                    ir::TypeKind::Bit
                }
                "u64" => {
                    width.push(Some(64));
                    ir::TypeKind::Bit
                }
                "i8" => {
                    width.push(Some(8));
                    signed = true;
                    ir::TypeKind::Bit
                }
                "i16" => {
                    width.push(Some(16));
                    signed = true;
                    ir::TypeKind::Bit
                }
                "i32" | "f32" => {
                    width.push(Some(32));
                    signed = true;
                    ir::TypeKind::Bit
                }
                "i64" | "f64" => {
                    width.push(Some(64));
                    signed = true;
                    ir::TypeKind::Bit
                }
                "bbool" => ir::TypeKind::Bit,
                "lbool" => ir::TypeKind::Logic,
                "string" => ir::TypeKind::String,
                _ => ir::TypeKind::Unknown,
            }
        } else if let GenericSymbolPathKind::VariableType(widths) = &path.kind {
            // A variable type (`bit<N>` / `logic<N>`) passed as a generic
            // argument carries its width in the path kind; `logic` is 4-state,
            // `bit` (and anything else here) is 2-state.
            for w in widths {
                width.push(Some(*w));
            }
            if path.paths.last().map(|p| p.base.to_string()).as_deref() == Some("logic") {
                ir::TypeKind::Logic
            } else {
                ir::TypeKind::Bit
            }
        } else {
            ir::TypeKind::Unknown
        }
    };

    let width_expr = ir::WidthExpr::from_shape(&width);
    let mut r#type = ir::Type::new(kind);
    r#type.signed = signed;
    r#type.is_positive = is_positive;
    r#type.array = array;
    if width_expr.len() == width.as_slice().len() {
        r#type.set_parametric_width(width, width_expr);
    } else {
        r#type.set_concrete_width(width);
    }
    Ok(r#type)
}

/// A struct/union member is emitted inside a `struct packed`, where an unpacked
/// array is illegal SystemVerilog. Spelling one directly (`m: t [8]`) is a
/// parse error, but a `type` alias carries one past the grammar.
fn check_unpacked_member(
    context: &mut Context,
    member: &Symbol,
    token: &TokenRange,
    r#type: &ir::Type,
) {
    if context.in_generic || r#type.array.is_empty() {
        return;
    }

    context.insert_error(AnalyzerError::unpacked_struct_union_member(
        &member.token.to_string(),
        token,
    ));
}

fn check_struct_union_members(
    context: &mut Context,
    members: &[ir::TypeKindMember],
    symbol: &Symbol,
) {
    if context.in_generic {
        return;
    }

    // SV-imported and unknown types have indeterminate 2/4-state, so accept them as either.
    let is_indeterminate = |t: &ir::Type| t.is_systemverilog() || t.is_unknown();
    let all_4state = members
        .iter()
        .all(|x| x.r#type.is_4state() || is_indeterminate(&x.r#type));
    let all_2state = members
        .iter()
        .all(|x| x.r#type.is_2state() || is_indeterminate(&x.r#type));
    if !(all_4state || all_2state) {
        let token: TokenRange = symbol.token.into();
        context.insert_error(AnalyzerError::mixed_struct_union_member(&token));
    }
}

pub fn eval_clock(context: &mut Context, value: &AlwaysFfDeclaration) -> IrResult<ir::FfClock> {
    let token: TokenRange = value.into();

    if let Some(x) = &value.always_ff_declaration_opt {
        let path = x
            .always_ff_event_list
            .always_ff_clock
            .hierarchical_identifier
            .as_ref();

        let path: VarPathSelect = Conv::conv(context, path)?;
        let (path, select, token) = path.into();

        if let Some((id, comptime)) = context.find_path(&path) {
            let (index, select) = select.split(comptime.r#type.array.dims());

            // Array select type check
            let _ = index.eval_comptime(context, &comptime.r#type, true);

            let index = index.to_index();

            let dim = comptime.r#type.selected_dimension(&index, &select);
            if !comptime.r#type.is_clock() || dim.0 != 0 || dim.1 != 0 || select.is_range() {
                context.insert_error(AnalyzerError::invalid_clock(
                    &path.to_string(),
                    &comptime.token,
                ));
            }

            Ok(ir::FfClock {
                id,
                index,
                select,
                comptime,
            })
        } else {
            Err(ir_error!(token))
        }
    } else if let Some((x, id)) = context.get_default_clock() {
        let token = value.always_ff.always_ff_token.token;
        symbol_table::add_reference(id, &token);
        Ok(x)
    } else {
        context.insert_error(AnalyzerError::missing_clock_signal(&token));
        Err(ir_error!(token))
    }
}

pub fn eval_reset(
    context: &mut Context,
    value: &AlwaysFfDeclaration,
) -> IrResult<Option<ir::FfReset>> {
    let token: TokenRange = value.into();

    if !value.has_if_reset() {
        if value.has_explicit_reset() {
            context.insert_error(AnalyzerError::missing_if_reset(&token));
        }
        return Ok(None);
    }

    if let Some(x) = &value.always_ff_declaration_opt
        && let Some(x) = &x.always_ff_event_list.always_ff_event_list_opt
    {
        let path = x.always_ff_reset.hierarchical_identifier.as_ref();
        let path: VarPathSelect = Conv::conv(context, path)?;
        let (path, select, token) = path.into();

        if let Some((id, comptime)) = context.find_path(&path) {
            let (index, select) = select.split(comptime.r#type.array.dims());

            // Array select type check
            let _ = index.eval_comptime(context, &comptime.r#type, true);

            let index = index.to_index();

            let dim = comptime.r#type.selected_dimension(&index, &select);
            if !comptime.r#type.is_reset() || dim.0 != 0 || dim.1 != 0 || select.is_range() {
                context.insert_error(AnalyzerError::invalid_reset(
                    &path.to_string(),
                    &comptime.token,
                ));
            }

            Ok(Some(ir::FfReset {
                id,
                index,
                select,
                comptime,
            }))
        } else {
            Err(ir_error!(token))
        }
    } else if let Some((x, id)) = context.get_default_reset() {
        let token = value.always_ff.always_ff_token.token;
        symbol_table::add_reference(id, &token);
        Ok(Some(x))
    } else {
        context.insert_error(AnalyzerError::missing_reset_signal(&token));
        Err(ir_error!(token))
    }
}

pub fn eval_width_select(
    context: &mut Context,
    path: &VarPath,
    r#type: &ir::Type,
    width_select: VarSelect,
) -> Option<VarSelect> {
    if r#type.is_struct_union() && !r#type.width().is_empty() && !width_select.is_empty() {
        let part_select = PartSelectPath {
            base: r#type.clone(),
            path: path.clone(),
            part_select: vec![],
        };
        part_select.to_base_select(context, &width_select)
    } else {
        Some(width_select)
    }
}

pub fn eval_generate_for_range(
    context: &mut Context,
    range: &Range,
    rev: bool,
    step: Option<(&AssignmentOperator, &Expression)>,
    token: TokenRange,
) -> IrResult<Vec<usize>> {
    let for_range = build_for_range_inner(context, range, rev, step, true)?;
    for_range.eval_iter(context).ok_or_else(|| ir_error!(token))
}

/// Build a `ForRange` from syntactic elements of a for-loop.
pub fn build_for_range(
    context: &mut Context,
    range: &Range,
    rev: bool,
    step: Option<(&AssignmentOperator, &Expression)>,
) -> IrResult<ir::ForRange> {
    build_for_range_inner(context, range, rev, step, false)
}

fn build_for_range_inner(
    context: &mut Context,
    range: &Range,
    rev: bool,
    step: Option<(&AssignmentOperator, &Expression)>,
    require_const: bool,
) -> IrResult<ir::ForRange> {
    let (beg, end, inclusive) = if require_const {
        eval_range_const(context, range)?
    } else {
        eval_range(context, range)?
    };

    if let Some((op, expr)) = step {
        let mut step_expr: ir::Expression = Conv::conv(context, expr)?;
        let step_comptime = step_expr.eval_comptime(context, None);
        let step_value = step_comptime.get_value()?;
        let step_val = step_value.to_usize_saturating().unwrap_or(0);
        let step_negative = step_value.is_semantically_not_positive() && step_val != 0;
        let op: ir::Op = Conv::conv(context, op)?;

        if matches!(op, ir::Op::Add) {
            // An additive step of 0 never advances the induction variable. The
            // unroll path bails in eval_iter, but a dynamic-range loop reaches
            // build_for_statement and would emit an infinite `for (; ; i += 0)`.
            if step_val == 0 {
                let token: TokenRange = expr.into();
                context.insert_error(AnalyzerError::invalid_for_step(
                    InvalidForStepKind::ZeroStep,
                    &token,
                ));
                return Err(ir_error!(token));
            }
            if step_negative {
                let token: TokenRange = expr.into();
                context.insert_error(AnalyzerError::invalid_for_step(
                    InvalidForStepKind::NeverAdvances,
                    &token,
                ));
                return Err(ir_error!(token));
            }
            // Honor `rev` for additive steps so the unrolled iteration order
            // matches the emitted descending `for (i = hi; i >= lo; i -= step)`.
            if rev {
                Ok(ir::ForRange::Reverse {
                    start: beg,
                    end,
                    inclusive,
                    step: step_val,
                })
            } else {
                Ok(ir::ForRange::Forward {
                    start: beg,
                    end,
                    inclusive,
                    step: step_val,
                })
            }
        } else if rev {
            // A reverse loop is emitted as `for (i = hi; i >= lo; <step>)`, so a
            // non-additive step (`*=`, `<<=`, ...) cannot be inverted to descend
            // toward the lower bound and would never terminate. Reject it rather
            // than emit a broken loop.
            let token: TokenRange = range.into();
            context.insert_error(AnalyzerError::invalid_for_step(
                InvalidForStepKind::NonAdditiveReverse,
                &token,
            ));
            Err(ir_error!(token))
        } else {
            // A forward stepped loop runs while `i < end`, so the step must
            // strictly increase the induction variable. Ops that can only
            // hold or decrease it (and identity step values) would emit an
            // infinite SV loop while the unroller sees ≤1 iteration.
            let never_advances = match op {
                ir::Op::Sub
                | ir::Op::Div
                | ir::Op::Rem
                | ir::Op::BitAnd
                | ir::Op::ArithShiftR
                | ir::Op::LogicShiftR => true,
                ir::Op::Mul => step_val <= 1,
                ir::Op::BitOr | ir::Op::BitXor | ir::Op::ArithShiftL | ir::Op::LogicShiftL => {
                    step_val == 0
                }
                _ => false,
            };
            if never_advances {
                let token: TokenRange = expr.into();
                context.insert_error(AnalyzerError::invalid_for_step(
                    InvalidForStepKind::NeverAdvances,
                    &token,
                ));
                return Err(ir_error!(token));
            }
            const INDUCTION_MAX: usize = i32::MAX as usize;
            let end_val = end.eval_value(context).map(|end_val| {
                if inclusive {
                    end_val.saturating_add(1)
                } else {
                    end_val
                }
            });
            let scannable = end_val.is_some() || !matches!(op, ir::Op::Add);
            if let Some(start_val) = beg.eval_value(context)
                && scannable
            {
                let limit = context.config.evaluate_size_limit;
                let mut i = start_val;
                let mut n = 0usize;
                while end_val.is_none_or(|end_val| i < end_val) && n <= limit {
                    match op.eval(i, step_val) {
                        Some(next) if next > INDUCTION_MAX => {
                            let token: TokenRange = expr.into();
                            context.insert_error(AnalyzerError::for_loop_overflow(&token));
                            return Err(ir_error!(token));
                        }
                        Some(next) if next > i => i = next,
                        _ if end_val.is_some() => {
                            let token: TokenRange = expr.into();
                            context.insert_error(AnalyzerError::invalid_for_step(
                                InvalidForStepKind::StopsAdvancing,
                                &token,
                            ));
                            return Err(ir_error!(token));
                        }
                        _ => break,
                    }
                    n += 1;
                }
            }
            Ok(ir::ForRange::Stepped {
                start: beg,
                end,
                inclusive,
                step: step_val,
                op,
            })
        }
    } else if rev {
        Ok(ir::ForRange::Reverse {
            start: beg,
            end,
            inclusive,
            step: 1,
        })
    } else {
        Ok(ir::ForRange::Forward {
            start: beg,
            end,
            inclusive,
            step: 1,
        })
    }
}

/// Convert a `ForStatement` AST node into a runtime `ir::Statement::For`.
/// Used for dynamic-range for-loops that cannot be unrolled at compile time.
pub fn build_for_statement(
    context: &mut Context,
    value: &ForStatement,
    r#type: &ir::Type,
    clock_domain: ClockDomain,
    for_range: ir::ForRange,
    token: TokenRange,
) -> IrResult<ir::StatementBlock> {
    let var_name = value.identifier.text();

    let index = value.identifier.text();
    let path = VarPath::new(index);
    let kind = VarKind::Const;
    let comptime = Comptime::from_type(r#type.clone(), clock_domain, token);

    let loop_var_id = context.insert_var_path(path.clone(), comptime.clone());
    let values = if let Some(total_width) = r#type.total_width() {
        vec![Value::new_x(total_width, r#type.signed)]
    } else {
        vec![]
    };
    let array_limit = context.config.evaluate_array_limit;
    let variable = Variable::new(
        loop_var_id,
        path,
        kind,
        comptime.r#type.clone(),
        values,
        context.get_affiliation(),
        &token,
        array_limit,
    );
    context.insert_variable(loop_var_id, variable);

    let body: ir::StatementBlock = Conv::conv(context, value.statement_block.as_ref())?;

    Ok(ir::StatementBlock(vec![ir::Statement::For(Box::new(
        ir::ForStatement {
            var_id: loop_var_id,
            var_name,
            var_type: r#type.clone(),
            range: for_range,
            body: body.0,
            token,
        },
    ))]))
}

pub fn eval_function_call(
    context: &mut Context,
    value: &IdentifierFactor,
    token: TokenRange,
) -> IrResult<ir::Expression> {
    if let Some(x) = &value.identifier_factor_opt
        && let IdentifierFactorOptGroup::FunctionCall(x) = x.identifier_factor_opt_group.as_ref()
    {
        // A component method call in expression position hoists to its own
        // zero-time statement; builtin $tb methods return nothing. Testbench
        // components only exist inside #[test] modules, so the probe (one
        // extra resolve per multi-segment call) is skipped elsewhere.
        if context.in_test_module
            && let Some(tb_stmt) = tb_method_call(
                context,
                value.expression_identifier.as_ref(),
                &x.function_call,
                token,
                TbMethodCallPosition::Value,
            )?
        {
            let ir::Statement::TbMethodCall(method_call) = tb_stmt else {
                unreachable!()
            };
            if method_call.method.has_return_value() {
                return hoist_component_method_call(context, method_call, token);
            }
            context.insert_error(AnalyzerError::invalid_factor(
                None,
                "testbench method without return value",
                &token,
                &[],
            ));
            return Err(ir_error!(token));
        }

        let args = if let Some(x) = &x.function_call.function_call_opt {
            argument_list(context, x.argument_list.as_ref())?
        } else {
            ir::Arguments::Null
        };

        let resolved_path = context.resolve_path(value.expression_identifier.as_ref().into());
        let symbol = symbol_table::resolve(&resolved_path).map_err(|_| ir_error!(token))?;

        match &symbol.found.kind {
            SymbolKind::SystemFunction(_) => {
                let name = symbol.found.token.text;
                let args = args.to_system_function_args(context, &symbol.found);
                check_initial_assign_system_function_args(context, &symbol.found, &args);
                let ret = ir::SystemFunctionCall::new(context, name, args, token)?;
                Ok(ir::Expression::Term(Box::new(
                    ir::Factor::SystemFunctionCall(ret),
                )))
            }
            SymbolKind::Function(x) if x.is_proto => {
                if context.in_generic {
                    let ret =
                        function_call(context, value.expression_identifier.as_ref(), args, token)?;

                    Ok(ir::Expression::Term(Box::new(ir::Factor::FunctionCall(
                        ret,
                    ))))
                } else {
                    Err(ir_error!(token))
                }
            }
            SymbolKind::Function(_) | SymbolKind::ModportFunctionMember(_) => {
                let ret =
                    function_call(context, value.expression_identifier.as_ref(), args, token)?;

                Ok(ir::Expression::Term(Box::new(ir::Factor::FunctionCall(
                    ret,
                ))))
            }
            SymbolKind::SystemVerilog => {
                let mut x = Comptime::create_unknown(token);
                x.is_const = true;
                Ok(ir::Expression::Term(Box::new(ir::Factor::Value(x))))
            }
            _ => {
                let name = symbol.found.token.text.to_string();
                let kind = symbol.found.kind.to_kind_name();
                context.insert_error(AnalyzerError::call_non_function(&name, &kind, &token));
                Err(ir_error!(token))
            }
        }
    } else {
        unreachable!();
    }
}

pub fn eval_struct_constructor(
    context: &mut Context,
    value: &IdentifierFactor,
    token: TokenRange,
) -> IrResult<ir::Expression> {
    if let Some(x) = &value.identifier_factor_opt
        && let IdentifierFactorOptGroup::StructConstructor(x) =
            x.identifier_factor_opt_group.as_ref()
    {
        let items: Vec<_> = x.struct_constructor.struct_constructor_list.as_ref().into();
        let default = &x.struct_constructor.struct_constructor_opt;

        let path: GenericSymbolPath = value.expression_identifier.as_ref().into();
        let r#type = symbol::Type {
            modifier: vec![],
            kind: symbol::TypeKind::UserDefined(symbol::UserDefinedType { path, symbol: None }),
            width: vec![],
            array: vec![],
            array_type: None,
            is_const: false,
            token,
        };
        let r#type = r#type.to_ir_type(context, TypePosition::Variable)?;

        let members = match &r#type.kind {
            ir::TypeKind::Struct(x) => &x.members,
            ir::TypeKind::SystemVerilog => &vec![],
            // A union stores one member at a time, so a pattern naming its
            // members has no value to build. SystemVerilog leaves the case to
            // the tool -- implementations disagree on which forms are legal
            // and on what they mean -- so emitting one is not portable.
            ir::TypeKind::Union(_) => {
                context.insert_error(AnalyzerError::mismatch_type(
                    MismatchTypeKind::UnionConstructor,
                    &token,
                ));
                return Err(ir_error!(token));
            }
            _ => {
                context.insert_error(AnalyzerError::mismatch_type(
                    MismatchTypeKind::NonStructType {
                        actual: r#type.kind.to_string(),
                    },
                    &token,
                ));
                return Err(ir_error!(token));
            }
        };

        let mut exprs = HashMap::default();
        for item in items {
            let name = item.identifier.text();
            exprs.insert(name, item.expression.as_ref().clone());
        }

        let mut ret = vec![];
        for x in members {
            let (_, expr) = if let Some(expr) = exprs.get(&x.name) {
                eval_expr(context, Some(x.r#type.clone()), expr, false)?
            } else if let Some(expr) = default {
                eval_expr(context, Some(x.r#type.clone()), &expr.expression, false)?
            } else {
                context.insert_error(AnalyzerError::unknown_member(
                    "struct constructor",
                    &x.name.to_string(),
                    &token,
                ));
                return Err(ir_error!(token));
            };

            ret.push((x.name, expr));
        }

        let comptime = Box::new(Comptime::create_unknown(token));
        Ok(ir::Expression::StructConstructor(
            Box::new(r#type),
            ret,
            comptime,
        ))
    } else {
        unreachable!();
    }
}

/// A member path whose first segment is a module instance: a hierarchical
/// testbench reference (`dut.u_core.pc`) or one of its misuse forms.
enum HierReference {
    Resolved {
        /// Instance names from the referencing module down to the target.
        inst_path: Vec<StrId>,
        var_path: VarPath,
        r#type: Box<ir::Type>,
        /// A struct/union member named by trailing segments, read as a bit
        /// range of the whole variable.
        part_select: Option<Box<PartSelectPath>>,
    },
    UnknownMember {
        owner: String,
        member: StrId,
    },
    /// First segment is a scalar module instance that has not been
    /// converted yet (declared after the referencing statement).
    NotDeclaredYet(StrId),
    InstanceArray(StrId),
    NotHier,
}

fn classify_hier_reference(context: &Context, path: &VarPath) -> HierReference {
    let segs = &path.0;
    if segs.len() < 2 {
        return HierReference::NotHier;
    }

    if let Some(component) = context.inst_components.get(&segs[0]) {
        let mut component = component.as_ref();
        let mut inst_path = vec![segs[0]];
        let mut i = 1;

        loop {
            let ir::Component::Module(module) = component else {
                return HierReference::NotHier;
            };

            // The remaining segments may be a variable path in this module
            // (multi-segment for interface-flattened members) ...
            let var_path = VarPath::from_slice(&segs[i..]);
            if let Some(variable) = module.variables.values().find(|v| v.path == var_path) {
                return HierReference::Resolved {
                    inst_path,
                    var_path,
                    r#type: Box::new(variable.r#type.clone()),
                    part_select: None,
                };
            }

            // ... or a struct/union member of one. A struct is a single
            // variable, so the member resolves against its type, not the
            // variable list. Longest prefix wins: an interface flattens into
            // multi-segment variable paths.
            let holder = module
                .variables
                .values()
                .filter(|v| v.path.0.len() < var_path.0.len() && var_path.0.starts_with(&v.path.0))
                .max_by_key(|v| v.path.0.len());
            if let Some(variable) = holder
                && let Some(part_select) = variable
                    .r#type
                    .expand_struct_union(&variable.path, &[], None)
                    .into_iter()
                    .find(|x| x.path == var_path)
            {
                return HierReference::Resolved {
                    inst_path,
                    var_path: variable.path.clone(),
                    r#type: Box::new(variable.r#type.clone()),
                    part_select: Some(Box::new(part_select)),
                };
            }

            // ... or descend into the child instance whose qualified path
            // (generate prefix then name) begins the remaining segments.
            let child = module.declarations.iter().find_map(|x| {
                let ir::Declaration::Inst(inst) = x else {
                    return None;
                };
                let consumed = ir::qualified_prefix_len(&inst.hierarchy, inst.name, &segs[i..])?;
                Some((&inst.component, consumed))
            });
            let Some((child, consumed)) = child else {
                // Name the struct, not the instance, when a variable path
                // matched but its trailing member did not.
                let (owner_tail, member) = match holder {
                    Some(v) => (v.path.0.as_slice(), segs[i + v.path.0.len()]),
                    None => (&[][..], segs[i]),
                };
                let owner = inst_path
                    .iter()
                    .chain(owner_tail)
                    .map(|x| x.to_string())
                    .collect::<Vec<_>>()
                    .join(".");
                return HierReference::UnknownMember { owner, member };
            };
            inst_path.extend_from_slice(&segs[i..i + consumed]);
            component = child.as_ref();
            i += consumed;
            if i >= segs.len() {
                let owner = inst_path
                    .iter()
                    .map(|x| x.to_string())
                    .collect::<Vec<_>>()
                    .join(".");
                return HierReference::UnknownMember {
                    owner,
                    member: *segs.last().unwrap(),
                };
            }
        }
    }

    // Not converted (yet); classify through the symbol table so misuse gets
    // a diagnostic instead of a silent conversion failure.
    let Some(namespace) = context.current_namespace() else {
        return HierReference::NotHier;
    };
    let Ok(symbol) = symbol_table::resolve((segs[0], &namespace)) else {
        return HierReference::NotHier;
    };
    let SymbolKind::Instance(prop) = &symbol.found.kind else {
        return HierReference::NotHier;
    };
    let Ok(type_symbol) =
        symbol_table::resolve((&prop.type_name.generic_path(), &symbol.found.namespace))
    else {
        return HierReference::NotHier;
    };
    let is_module = match &type_symbol.found.kind {
        SymbolKind::Module(_) | SymbolKind::AliasModule(_) => true,
        SymbolKind::GenericInstance(x) => matches!(
            symbol_table::get(x.base).map(|x| x.kind),
            Some(SymbolKind::Module(_))
        ),
        _ => false,
    };
    if !is_module {
        return HierReference::NotHier;
    }

    if prop.array.is_empty() {
        HierReference::NotDeclaredYet(segs[0])
    } else {
        HierReference::InstanceArray(segs[0])
    }
}

/// The write-side counterpart of the `HierReference::Resolved` arm in
/// [`eval_factor_path_inner`]: turns `dut.u_core.mem[0]` on the left of an
/// assignment into a [`ir::HierAssignDestination`], which the simulator
/// resolves to a buffer offset after elaboration.
///
/// Returns `None` when the path is not a hierarchical reference at all, so the
/// caller can fall through to its ordinary "destination not found" handling.
/// Like the read side this is testbench-only; a hierarchical write from RTL is
/// reported as an invisible identifier.
pub fn to_hier_assign_destination(
    context: &mut Context,
    dst: VarPathSelect,
) -> IrResult<Option<ir::HierAssignDestination>> {
    let (path, select, token) = dst.into();
    let HierReference::Resolved {
        inst_path,
        var_path,
        r#type,
        part_select,
    } = classify_hier_reference(context, &path)
    else {
        return Ok(None);
    };

    if !context.in_tb_block {
        context.insert_error(AnalyzerError::invisible_identifier(
            &path.0[1].to_string(),
            &token,
        ));
        return Err(ir_error!(token));
    }

    let mut comptime = Comptime::from_type(*r#type, ClockDomain::None, token);

    let (array_select, width_select) = select.split(comptime.r#type.array.dims());
    let _ = array_select.eval_comptime(context, &comptime.r#type, true);
    let width_select = if let Some(part_select) = &part_select {
        part_select.to_base_select(context, &width_select)
    } else {
        eval_width_select(context, &var_path, &comptime.r#type, width_select)
    }
    .ok_or_else(|| ir_error!(token))?;

    // An array RANGE destination would need one write per covered element;
    // `to_assign_destinations` does that for local paths and has no
    // hierarchical twin, so reject it rather than write the wrong element.
    if array_select.is_range() {
        return Err(ir_error!(token));
    }

    let index = array_select.to_index();
    comptime.r#type.array.drain(0..index.dimension());
    if !width_select.is_empty() {
        comptime.r#type.flatten_struct_union_enum();
        if let Some(width) = width_select.eval_comptime(context, &comptime.r#type, false) {
            comptime.r#type.set_concrete_width(width);
        }
    }
    comptime.token = token;

    Ok(Some(ir::HierAssignDestination {
        inst_path,
        var_path,
        index,
        select: width_select,
        comptime,
        token,
    }))
}

pub fn eval_factor_path(
    context: &mut Context,
    symbol_path: GenericSymbolPath,
    var_path: VarPathSelect,
    allow_unknown_value: bool,
    token: TokenRange,
) -> IrResult<ir::Factor> {
    // Bounds recursion when a recursive generic function's self-call can't be
    // resolved to a base case here; otherwise it recurses until the native
    // stack overflows.
    context.function_eval_depth += 1;
    let ret = if context.function_eval_depth > context.config.symbol_eval_depth_limit {
        if context.function_eval_overflow.is_none() {
            context.function_eval_overflow = Some((token, context.function_eval_depth));
        }
        Err(ir_error!(token))
    } else {
        eval_factor_path_inner(context, symbol_path, var_path, allow_unknown_value, token)
    };
    context.function_eval_depth -= 1;
    ret
}

fn eval_factor_path_inner(
    context: &mut Context,
    symbol_path: GenericSymbolPath,
    var_path: VarPathSelect,
    allow_unknown_value: bool,
    token: TokenRange,
) -> IrResult<ir::Factor> {
    let (path, select, _) = var_path.into();

    let mut generic_path = context.resolve_path(symbol_path);
    generic_path.unalias(None);
    check_generic_refereence(context, &generic_path);

    // An anonymous loop variable is also registered as `_`.
    if generic_path.is_anonymous() {
        let mut comptime = Comptime::create_unknown(token);
        comptime.is_const = true;
        comptime.is_global = true;
        return Ok(ir::Factor::Anonymous(comptime));
    }

    let found = if let Some(path) = generic_path.to_var_path()
        && let Some((var_id, comptime)) = context.find_path(&path)
    {
        Some((var_id, comptime))
    } else {
        context.find_path(&path)
    };

    // Classified even outside initial/final blocks: reference_table
    // suppresses invisible_identifier for these paths, so misuse inside a
    // test module must be diagnosed here.
    let hier = if found.is_none() && context.in_test_module {
        classify_hier_reference(context, &path)
    } else {
        HierReference::NotHier
    };

    if let Some((var_id, mut comptime)) = found {
        let array_dims = comptime.rebase_part_select();

        let (array_select, width_select) = select.split(array_dims);

        // Array select type check
        let _ = array_select.eval_comptime(context, &comptime.r#type, true);

        if !width_select.is_empty() {
            comptime.member_signed = None;
        }
        let width_select = if let Some(part_select) = &comptime.part_select {
            let (select, domain) = part_select
                .to_base_select_with_domain(context, &width_select)
                .ok_or_else(|| ir_error!(token))?;
            comptime.member_select_domain = domain;
            Some(select)
        } else {
            eval_width_select(context, &path, &comptime.r#type, width_select)
        };
        let width_select = width_select.ok_or_else(|| ir_error!(token))?;

        comptime.is_global = false;

        if array_select.is_range() {
            // TODO
            Err(ir_error!(token))
        } else {
            let index = array_select.to_index();
            let array = comptime.r#type.array.clone();
            comptime.r#type.array.drain(0..index.dimension());

            comptime.is_const &= index.is_const() && width_select.is_const();

            // The whole-array value doesn't describe a selected part of it; drop
            // it so consumers resolve the selection from the variable table.
            if (index.dimension() > 0 || !width_select.is_empty())
                && let ValueVariant::NumericArray(values) = &comptime.value
            {
                // Except for a `string`: it has no width to lay out, so the
                // variable table holds nothing to resolve against and the
                // element has to be folded here.
                let element = if comptime.r#type.is_string() && width_select.is_empty() {
                    index
                        .eval_value(context)
                        .and_then(|x| array.calc_index(&x))
                        .and_then(|x| values.get(x))
                        .cloned()
                } else {
                    None
                };
                comptime.value = match element {
                    Some(x) => ValueVariant::Numeric(x),
                    None => ValueVariant::Unknown,
                };
            }

            comptime.token = token;
            // A `string` read is only ever its value: there is no variable
            // behind it for a later stage to look up.
            let is_folded_string = comptime.r#type.is_string()
                && width_select.is_empty()
                && matches!(comptime.value, ValueVariant::Numeric(_));
            if comptime.r#type.is_type() || is_folded_string {
                Ok(ir::Factor::Value(comptime))
            } else {
                // Params arrive with evaluated=true (set by eval_expr), which
                // would make gather_context skip applying the select width —
                // and skip the index/select clock-domain check, laundering a
                // foreign-domain index into a const lookup table.
                if !width_select.is_empty() || !index.is_const() {
                    comptime.evaluated = false;
                }
                Ok(ir::Factor::Variable(var_id, index, width_select, comptime))
            }
        }
    } else if let HierReference::Resolved {
        inst_path,
        var_path,
        r#type,
        part_select,
    } = hier
    {
        if !context.in_tb_block {
            context.insert_error(AnalyzerError::invisible_identifier(
                &path.0[1].to_string(),
                &token,
            ));
            return Err(ir_error!(token));
        }

        let mut comptime = Comptime::from_type(*r#type, ClockDomain::None, token);

        let (array_select, width_select) = select.split(comptime.r#type.array.dims());
        let _ = array_select.eval_comptime(context, &comptime.r#type, true);
        // A part-select is unsigned; a whole member keeps its sign.
        let member_signed = match part_select.as_ref().and_then(|x| x.part_select.last()) {
            Some(member) if width_select.is_empty() => {
                let mut member = member.r#type.clone();
                member.flatten_struct_union_enum();
                member.signed
            }
            _ => false,
        };
        let width_select = if let Some(part_select) = &part_select {
            part_select.to_base_select(context, &width_select)
        } else {
            eval_width_select(context, &var_path, &comptime.r#type, width_select)
        }
        .ok_or_else(|| ir_error!(token))?;

        if array_select.is_range() {
            Err(ir_error!(token))
        } else {
            let index = array_select.to_index();
            comptime.r#type.array.drain(0..index.dimension());

            if !width_select.is_empty() {
                comptime.r#type.flatten_struct_union_enum();
                if let Some(width) = width_select.eval_comptime(context, &comptime.r#type, false) {
                    comptime.r#type.set_concrete_width(width);
                }
                comptime.r#type.signed = member_signed;
            }
            comptime.token = token;

            Ok(ir::Factor::HierVariable(Box::new(ir::HierVarRef {
                inst_path,
                var_path,
                index,
                select: width_select,
                comptime,
            })))
        }
    } else if !matches!(hier, HierReference::NotHier) {
        match hier {
            HierReference::UnknownMember { owner, member } => {
                context.insert_error(AnalyzerError::unknown_member(
                    &owner,
                    &member.to_string(),
                    &token,
                ));
            }
            HierReference::NotDeclaredYet(name) => {
                if context.in_tb_block {
                    context.insert_error(AnalyzerError::referring_before_definition(
                        &name.to_string(),
                        &token,
                    ));
                } else {
                    context.insert_error(AnalyzerError::invisible_identifier(
                        &path.0[1].to_string(),
                        &token,
                    ));
                }
            }
            HierReference::InstanceArray(name) => {
                context.insert_error(AnalyzerError::invalid_factor(
                    Some(&name.to_string()),
                    "instance array",
                    &token,
                    &[],
                ));
            }
            HierReference::Resolved { .. } | HierReference::NotHier => unreachable!(),
        }
        Err(ir_error!(token))
    } else if let Some(x) = generic_path.to_literal() {
        let x = x.eval_comptime(token);
        Ok(ir::Factor::Value(x))
    } else if let Ok(symbol) = symbol_table::resolve(&generic_path) {
        let is_inernal = context
            .current_namespace()
            .map(|x| symbol.found.namespace.included(&x))
            .unwrap_or(false);
        let factor = if is_inernal {
            eval_factor_symbol(
                context,
                generic_path,
                (*symbol).clone(),
                allow_unknown_value,
                token,
            )?
        } else {
            let maps = generic_path.to_generic_maps();
            eval_factor_symbol_external(
                context,
                generic_path,
                (*symbol).clone(),
                maps,
                allow_unknown_value,
                token,
            )?
        };

        apply_symbol_select(context, factor, select, &symbol.found, token)
    } else {
        Err(ir_error!(token))
    }
}

/// Apply a `select` that the symbol route (`eval_factor_symbol[_external]`)
/// drops.
fn apply_symbol_select(
    context: &mut Context,
    factor: ir::Factor,
    select: VarSelect,
    symbol: &Symbol,
    token: TokenRange,
) -> IrResult<ir::Factor> {
    if select.is_empty() {
        return Ok(factor);
    }
    let ir::Factor::Value(mut comptime) = factor else {
        return Ok(factor);
    };
    let values = match &comptime.value {
        ValueVariant::NumericArray(values) => values.clone(),
        ValueVariant::Numeric(value) => vec![value.clone()],
        // A value that can't be evaluated (e.g. a proto-bound const) still
        // has to shrink its type, or the select is invisible to the operand
        // and compatibility checks.
        _ => {
            reduce_unevaluable_select(context, &mut comptime, select, token);
            return Ok(ir::Factor::Value(comptime));
        }
    };

    let array = comptime.r#type.array.clone();
    let (array_select, width_select) = select.split(array.dims());
    // Array select type check (out-of-range / wrong-order).
    let _ = array_select.eval_comptime(context, &comptime.r#type, true);
    if array_select.is_range() {
        // TODO: array range select.
        return Err(ir_error!(token));
    }
    let index = array_select.to_index();
    let is_const_select = index.is_const() && width_select.is_const_with_range();
    comptime.is_const &= is_const_select;
    comptime.is_global &= comptime.is_const;

    if is_const_select
        && let Some(comptime) = fold_symbol_select(
            context,
            &comptime,
            &values,
            &array,
            &index,
            &width_select,
            token,
        )
    {
        return Ok(ir::Factor::Value(comptime));
    }

    // A run-time select needs the whole const: read it as a variable, the same
    // way a local const is read.
    let id = materialize_const(context, &comptime, values, symbol, token)?;

    comptime.r#type.array.drain(0..index.dimension());
    comptime.value = ValueVariant::Unknown;
    comptime.token = token;
    // `gather_context` applies the select width and checks its clock domain
    // only while the comptime isn't evaluated.
    comptime.evaluated = false;
    Ok(ir::Factor::Variable(id, index, width_select, comptime))
}

/// Shrink a type by a select whose value can't be evaluated. A type name and
/// a `$sv` member have no shape to reduce.
fn reduce_unevaluable_select(
    context: &mut Context,
    comptime: &mut Comptime,
    select: VarSelect,
    token: TokenRange,
) {
    if comptime.r#type.is_type() || comptime.r#type.is_systemverilog() {
        return;
    }

    let (array_select, width_select) = select.split(comptime.r#type.array.dims());
    let _ = array_select.eval_comptime(context, &comptime.r#type, true);
    if array_select.is_range() {
        return;
    }

    comptime.r#type.array.drain(0..array_select.dimension());
    if !width_select.is_empty() {
        comptime.r#type.flatten_struct_union_enum();
        if let Some(width) = width_select.eval_comptime(context, &comptime.r#type, false) {
            comptime.r#type.set_concrete_width(width);
        }
        comptime.r#type.signed = comptime.member_signed.unwrap_or(false);
    }
    comptime.token = token;
}

/// Fold a constant select into the selected value. `None` when it can't be
/// evaluated, leaving the caller to read the const at run time.
fn fold_symbol_select(
    context: &mut Context,
    comptime: &Comptime,
    values: &[Value],
    array: &Shape,
    index: &VarIndex,
    select: &VarSelect,
    token: TokenRange,
) -> Option<Comptime> {
    let mut comptime = comptime.clone();
    comptime.r#type.array.drain(0..index.dimension());
    comptime.token = token;
    let indices = index.eval_value(context)?;

    // A partial array index selects a sub-array, which has no single value to
    // fold to. The width select is necessarily empty: it splits off only once
    // every array dimension is indexed.
    if !comptime.r#type.array.is_empty() {
        let (beg, end) = array.calc_range(&indices)?;
        comptime.value = ValueVariant::NumericArray(values.get(beg..=end)?.to_vec());
        return Some(comptime);
    }

    // The select resolves against the element type: the reduction below
    // replaces its width dimensions by the selected width.
    let mut element = comptime.r#type.clone();
    if !select.is_empty() {
        element.flatten_struct_union_enum();
        comptime.r#type = element.clone();
        if let Some(width) = select.eval_comptime(context, &element, false) {
            comptime.r#type.set_concrete_width(width);
        }
        comptime.r#type.signed = comptime.member_signed.unwrap_or(false);
    }

    let flat = array.calc_index(&indices)?;
    let value = values.get(flat)?;
    comptime.value = if comptime.r#type.is_string() && select.is_empty() {
        // An empty select reads the declared width, which for a `string` is the
        // nominal 1 bit rather than the text the element holds.
        ValueVariant::Numeric(value.clone())
    } else {
        let (beg, end) = select.eval_value(context, &element, false)?;
        let mut value = value.select(beg, end);
        value.set_signed(comptime.r#type.signed);
        ValueVariant::Numeric(value)
    };
    Some(comptime)
}

/// Materialize a symbol-resolved const as a variable of the current component.
/// References from the same scope share one variable.
fn materialize_const(
    context: &mut Context,
    comptime: &Comptime,
    values: Vec<Value>,
    symbol: &Symbol,
    token: TokenRange,
) -> IrResult<ir::VarId> {
    let r#type = comptime.r#type.clone();
    let values = fit_array_elements(values, &r#type);
    // An index only resolves when every element of the const is known.
    if values.len() != r#type.total_array().unwrap_or(1).max(1) {
        return Err(ir_error!(token));
    }

    // The namespace keeps generic instances apart: theirs are mangled.
    let name: String = format!("__const_{}_{}", symbol.namespace, symbol.token)
        .chars()
        .map(|x| if x.is_ascii_alphanumeric() { x } else { '_' })
        .collect();
    let affiliation = context.get_affiliation();
    let mut path = VarPath::new(resource_table::insert_str(&name));
    if let Some(id) = reusable_const(context, &path, affiliation, &r#type, &values) {
        return Ok(id);
    }
    if context.find_path(&path).is_some() {
        // Distinct paths can sanitize alike: disambiguate rather than share
        // another const's values.
        path = VarPath::new(resource_table::insert_str(&format!(
            "{name}_{}",
            symbol.id.0
        )));
        if let Some(id) = reusable_const(context, &path, affiliation, &r#type, &values) {
            return Ok(id);
        }
    }

    let mut comptime = comptime.clone();
    comptime.token = token;
    let id = context.insert_var_path(path.clone(), comptime);
    let array_limit = context.config.evaluate_array_limit;
    let variable = Variable::new(
        id,
        path,
        VarKind::Const,
        r#type,
        values,
        affiliation,
        &token,
        array_limit,
    );
    context.insert_variable(id, variable);
    Ok(id)
}

fn reusable_const(
    context: &Context,
    path: &VarPath,
    affiliation: Affiliation,
    r#type: &ir::Type,
    values: &[Value],
) -> Option<ir::VarId> {
    let (id, _) = context.find_path(path)?;
    let variable = context.variables.get(&id)?;
    let reusable = variable.kind == VarKind::Const
        && variable.affiliation == affiliation
        && variable.r#type == *r#type
        && variable.value == values;
    reusable.then_some(id)
}

/// Evaluates a resolved symbol that lives outside the current module: an
/// independent context avoids name conflicts, with the given generic
/// arguments applied.
pub fn eval_factor_symbol_external(
    context: &mut Context,
    path: GenericSymbolPath,
    symbol: ResolveResult,
    maps: Vec<GenericMap>,
    allow_unknown_value: bool,
    token: TokenRange,
) -> IrResult<ir::Factor> {
    let mut external_context = Context::default();
    external_context.inherit(context);

    external_context.push_generic_map(maps);
    let ret =
        external_context.block(|c| eval_factor_symbol(c, path, symbol, allow_unknown_value, token));

    external_context.pop_generic_map();
    context.inherit(&mut external_context);

    ret
}

pub fn eval_factor_symbol(
    context: &mut Context,
    path: GenericSymbolPath,
    symbol: ResolveResult,
    allow_unknown_value: bool,
    token: TokenRange,
) -> IrResult<ir::Factor> {
    match &symbol.found.kind {
        SymbolKind::Parameter(x) if !x.is_proto => {
            // Parameter should be found through context.find_path from the
            // defined namespace. Not while sizing a declared width, where a
            // component instantiating itself would name its own scope.
            if !context.sizing_component_width()
                && !context.is_global_func_caller(&symbol.found.namespace)
                && let Some(namespace) = context.current_namespace()
                && symbol.found.namespace.included(&namespace)
            {
                report_unreachable_definition(context, symbol.found.token, &token);
            }

            // Reached while a width names a parameter of a component whose body
            // has not been converted yet, so the declaration default is not
            // what that parameter stands for.
            if let Some((comptime, _)) = context.get_override(
                &symbol.found.namespace,
                &VarPath::new(symbol.found.token.text),
            ) {
                let mut comptime = comptime.clone();
                // A value whose representation is narrower than its type
                // reaches the back end as a store the variable's width does
                // not match.
                if let Some(width) = comptime.r#type.total_width() {
                    comptime.value.expand_value(width);
                }

                comptime.token = token;
                return Ok(ir::Factor::Value(comptime));
            }

            if let Some(expr) = &x.value {
                let r#type = x.r#type.to_ir_type(context, TypePosition::Variable)?;
                let (mut comptime, _) =
                    context.block(|c| eval_expr(c, Some(r#type), expr, false))?;

                if let Some(width) = comptime.r#type.total_width() {
                    comptime.value.expand_value(width);
                }

                comptime.token = token;
                return Ok(ir::Factor::Value(comptime));
            }
        }
        SymbolKind::GenericParameter(x) => {
            let default_value = if let Some(x) = &x.default_value
                && let Some(x) = x.to_literal()
            {
                let x = x.eval_comptime(token);
                Some(x)
            } else if allow_unknown_value {
                None
            } else {
                return Err(ir_error!(token));
            };

            if let Ok(proto) = x.bound.resolve_proto_bound(&symbol.found.namespace) {
                match proto {
                    ProtoBound::ProtoModule(_)
                    | ProtoBound::ProtoInterface(_)
                    | ProtoBound::ProtoPackage(_)
                        if context.allow_component_as_factor =>
                    {
                        context.allow_component_as_factor = false;
                        return Ok(ir::Factor::from_component_symbol(&symbol.found, token));
                    }
                    ProtoBound::FactorType(x)
                    | ProtoBound::Enum((_, x))
                    | ProtoBound::Struct((_, x))
                    | ProtoBound::Union((_, x)) => {
                        let r#type = x.to_ir_type(context, TypePosition::Generic)?;
                        let mut x = Comptime::from_type(r#type, ClockDomain::None, token);

                        if let Some(val) = default_value {
                            x.value = val.value;
                        }

                        // GenericParameter is const and global
                        x.is_const = true;
                        x.is_global = true;

                        return Ok(ir::Factor::Value(x));
                    }
                    _ => {}
                }
            } else if matches!(x.bound, GenericBoundKind::Type) {
                let mut x = Comptime::create_unknown(token);

                if let Some(val) = default_value {
                    x.value = val.value;
                }

                // GenericParameter is const and global
                x.is_const = true;
                x.is_global = true;
                x.r#type.kind = ir::TypeKind::Type;

                return Ok(ir::Factor::Value(x));
            } else {
                context.insert_error(AnalyzerError::invalid_factor(
                    Some(&symbol.found.token.to_string()),
                    &symbol.found.kind.to_kind_name(),
                    &token,
                    &[],
                ));
            }
        }
        SymbolKind::GenericConst(x) => {
            if let Ok(proto) = x.bound.resolve_proto_bound(&symbol.found.namespace) {
                match proto {
                    ProtoBound::ProtoModule(_)
                    | ProtoBound::ProtoInterface(_)
                    | ProtoBound::ProtoPackage(_)
                        if context.allow_component_as_factor =>
                    {
                        context.allow_component_as_factor = false;
                        return Ok(ir::Factor::from_component_symbol(&symbol.found, token));
                    }
                    ProtoBound::FactorType(t)
                    | ProtoBound::Enum((_, t))
                    | ProtoBound::Struct((_, t))
                    | ProtoBound::Union((_, t)) => {
                        let r#type = t.to_ir_type(context, TypePosition::Generic)?;

                        let mut comptime = if context.in_generic {
                            // RHS value of generic const may not be evaluated in generic component
                            Comptime::from_type(r#type.clone(), ClockDomain::None, token)
                        } else {
                            let (mut comptime, _) = eval_generic_expr(context, &x.value)?;
                            comptime.r#type = r#type;
                            comptime
                        };
                        comptime.is_const = true;
                        comptime.is_global = true;
                        comptime.token = token;
                        return Ok(ir::Factor::Value(comptime));
                    }
                    _ => {}
                }
            } else if matches!(x.bound, GenericBoundKind::Type) {
                let (mut comptime, _) = eval_generic_expr(context, &x.value)?;
                comptime.is_const = true;
                comptime.is_global = true;
                comptime.token = token;
                return Ok(ir::Factor::Value(comptime));
            }
        }
        SymbolKind::Parameter(x) if x.is_proto && allow_unknown_value => {
            let r#type = x.r#type.to_ir_type(context, TypePosition::Variable)?;
            let mut x = Comptime::from_type(r#type, ClockDomain::None, token);

            x.is_const = true;
            x.is_global = true;

            return Ok(ir::Factor::Value(x));
        }
        SymbolKind::TypeDef(x) if x.is_proto => {
            if allow_unknown_value {
                let mut x = Comptime::create_unknown(token);

                x.is_const = true;
                x.is_global = true;

                return Ok(ir::Factor::Value(x));
            }
        }
        SymbolKind::EnumMember(x) => {
            let enum_symbol = symbol.found.get_parent().unwrap();
            let SymbolKind::Enum(r#enum) = enum_symbol.kind else {
                unreachable!();
            };

            let factor = match &x.value {
                EnumMemberValue::Unresolved => {
                    context.insert_error(AnalyzerError::referring_before_definition(
                        &symbol.found.token.to_string(),
                        &token,
                    ));
                    None
                }
                EnumMemberValue::ImplicitValue(x) => {
                    let value = Value::new_biguint(x.clone(), r#enum.width, false);
                    Some(ir::Factor::create_value(value, token))
                }
                EnumMemberValue::ExplicitValue(x, _) => {
                    let (mut x, _) = eval_expr(context, None, x, false)?;
                    x.token = token;
                    // Coerce to the enum width like the ImplicitValue arm: otherwise the
                    // expression's own width (32 for a bare literal) becomes the member's
                    // IR width, while the emitted SV casts every member to enum width.
                    // Untyped enums keep width 0 in EnumProperty, so leave those alone.
                    if r#enum.width > 0
                        && let Ok(value) = x.get_value()
                    {
                        let mut value = value.clone();
                        if value.width() < r#enum.width {
                            value = value.expand(r#enum.width, value.signed()).into_owned();
                        }
                        value.trunc(r#enum.width);
                        // Match the ImplicitValue arm's unsigned values.
                        value.set_signed(false);
                        Some(ir::Factor::create_value(value, token))
                    } else {
                        Some(ir::Factor::Value(x))
                    }
                }
                EnumMemberValue::UnevaluableValue => None,
            };

            if let Some(mut factor) = factor {
                let enum_type = factor.comptime().r#type.clone();
                let type_kind = ir::TypeKind::Enum(Arc::new(ir::TypeKindEnum {
                    id: enum_symbol.id,
                    r#type: Box::new(enum_type),
                }));

                let factor_comptime = factor.comptime_mut();
                factor_comptime.r#type.kind = type_kind;
                // The member width lives in TypeKindEnum, so the outer shape must
                // be scalar (else total_width squares it), like to_ir_type's enums.
                factor_comptime.r#type.set_concrete_width(Shape::default());

                return Ok(factor);
            }
        }
        SymbolKind::StructMember(_) => {
            // Module local variable should be found through context.find_path
            let module_variable = symbol.full_path.iter().any(|x| {
                let symbol = symbol_table::get(*x).unwrap();
                if let SymbolKind::Variable(x) = symbol.kind {
                    x.affiliation == Affiliation::Module
                } else {
                    false
                }
            });
            if module_variable {
                report_unreachable_definition(context, symbol.found.token, &token);
            }
            return eval_struct_member(context, &symbol.found, &path, VarPath::default(), token);
        }
        SymbolKind::SystemVerilog => {
            let r#type = ir::Type::new(ir::TypeKind::SystemVerilog);
            let mut x = Comptime::from_type(r#type, ClockDomain::None, token);

            // $sv member is const / global
            x.is_const = true;
            x.is_global = true;

            return Ok(ir::Factor::Value(x));
        }
        SymbolKind::Module(_)
        | SymbolKind::AliasModule(_)
        | SymbolKind::Interface(_)
        | SymbolKind::AliasInterface(_)
        | SymbolKind::Package(_)
        | SymbolKind::AliasPackage(_) => {
            if context.allow_component_as_factor {
                context.allow_component_as_factor = false;
                return Ok(ir::Factor::from_component_symbol(&symbol.found, token));
            } else {
                context.insert_error(AnalyzerError::invalid_factor(
                    Some(&symbol.found.token.to_string()),
                    &symbol.found.kind.to_kind_name(),
                    &token,
                    &[],
                ));
            }
        }
        SymbolKind::Instance(x) if context.allow_component_as_factor => {
            context.allow_component_as_factor = false;
            if let Ok(component) =
                symbol_table::resolve_generic_structural(&x.type_name, &symbol.found.namespace)
            {
                let sig = Arc::new(Signature::new(component.found.id));
                let kind = if symbol.found.is_module(true) {
                    ir::TypeKind::Instance(sig.clone(), ir::InstanceKind::Module)
                } else if symbol.found.is_interface(true) {
                    ir::TypeKind::Instance(sig.clone(), ir::InstanceKind::Interface)
                } else {
                    ir::TypeKind::Instance(sig.clone(), ir::InstanceKind::SystemVerilog)
                };
                let r#type = ir::Type::new(kind);

                let comptime = Comptime::from_type(r#type, ClockDomain::None, token);
                return Ok(ir::Factor::Value(comptime));
            }
        }
        SymbolKind::Function(x) if !x.is_proto => {
            context.insert_error(AnalyzerError::invalid_factor(
                Some(&symbol.found.token.to_string()),
                &symbol.found.kind.to_kind_name(),
                &token,
                &[],
            ));
        }
        SymbolKind::SystemFunction(_) => {
            context.insert_error(AnalyzerError::invalid_factor(
                Some(&symbol.found.token.to_string()),
                &symbol.found.kind.to_kind_name(),
                &token,
                &[],
            ));
        }
        // Mangled enum member can't be used directly
        SymbolKind::EnumMemberMangled => {
            context.insert_error(AnalyzerError::undefined_identifier(
                &symbol.found.token.to_string(),
                &symbol.found.token.into(),
            ));
        }
        SymbolKind::Variable(x) => {
            // Module local variable should be found through context.find_path
            if x.affiliation == Affiliation::Module {
                report_unreachable_definition(context, symbol.found.token, &token);
            }

            let r#type = x.r#type.to_ir_type(context, TypePosition::Variable)?;
            let x = Comptime::from_type(r#type, x.clock_domain, token);

            return Ok(ir::Factor::Value(x));
        }
        // Reached only when evaluated without IR context (e.g. cast emit in emitter)
        SymbolKind::Port(x) => {
            let r#type = x.r#type.to_ir_type(context, TypePosition::Variable)?;
            let x = Comptime::from_type(r#type, x.clock_domain, token);

            return Ok(ir::Factor::Value(x));
        }
        SymbolKind::ModportVariableMember(x) => {
            let variable = symbol_table::get(x.variable).unwrap();
            if let SymbolKind::Variable(x) = &variable.kind {
                let r#type = x.r#type.to_ir_type(context, TypePosition::Variable)?;
                let x = Comptime::from_type(r#type, x.clock_domain, token);

                return Ok(ir::Factor::Value(x));
            }
        }
        SymbolKind::Enum(_)
        | SymbolKind::Struct(_)
        | SymbolKind::Union(_)
        | SymbolKind::TypeDef(_) => {
            let r#type = symbol::Type {
                modifier: vec![],
                kind: symbol::TypeKind::UserDefined(symbol::UserDefinedType { path, symbol: None }),
                width: vec![],
                array: vec![],
                array_type: None,
                is_const: true,
                token,
            };
            let r#type = r#type.to_ir_type(context, TypePosition::Variable)?;
            let x = Comptime {
                value: ValueVariant::Type(r#type),
                r#type: ir::Type::new(ir::TypeKind::Type),
                is_const: true,
                is_global: true,
                token,
                ..Default::default()
            };

            return Ok(ir::Factor::Value(x));
        }
        SymbolKind::ProjectProperty(x) => {
            let value = match &x.value {
                veryl_metadata::ProjectProperty::Int(x) => Value::new(*x as u64, 64, true),
                veryl_metadata::ProjectProperty::Bool(x) => {
                    if *x {
                        Value::new(1, 1, false)
                    } else {
                        Value::new(0, 1, false)
                    }
                }
            };
            let comptime = Comptime::create_value(value, symbol.found.token.into());
            return Ok(ir::Factor::Value(comptime));
        }
        _ => (),
    }
    Err(ir_error!(token))
}

/// A target that is not self-determined stays unfolded, so that each
/// comparison can size it again.
pub fn eval_case_target(context: &mut Context, tgt: &mut ir::Expression) -> Comptime {
    let prev = context.disalbe_const_opt;
    context.disalbe_const_opt |= !tgt.is_self_determined();
    let ret = tgt.eval_comptime(context, None).clone();
    context.disalbe_const_opt = prev;
    ret
}

/// The sign and width a `case` target or pattern value has on its own.
#[derive(Clone, Copy)]
pub struct CaseOperand {
    signed: bool,
    width: usize,
    /// The width it adds to the one SystemVerilog sizes the whole `case` at.
    sv_width: usize,
    /// Its value can change with the width it is evaluated at.
    widens: bool,
    /// Its value can change with the sign it is evaluated with.
    sign_sensitive: bool,
    /// The bit length of a non-negative constant.
    magnitude: Option<usize>,
    /// It is a range bound, compared by order rather than equality.
    bound: bool,
    /// An exclusive upper bound, emitted as `(hi)-1`.
    exclusive: bool,
    is_const: bool,
    is_zero: bool,
    is_min: bool,
    known: bool,
    is_string: bool,
    token: TokenRange,
}

impl CaseOperand {
    /// `expr` is not yet evaluated, or was evaluated by `eval_case_target`.
    pub fn new(context: &mut Context, expr: &ir::Expression) -> Self {
        let mut probe = expr.clone();
        let comptime = probe.eval_comptime(context, None);
        let r#type = &comptime.r#type;
        let known = !(r#type.is_unknown() || r#type.is_systemverilog() || r#type.is_type());
        let self_determined = expr.is_self_determined();
        let width = comptime.expr_context.width;
        let signed = comptime.expr_context.signed;
        let value = comptime
            .get_value()
            .ok()
            .filter(|x| comptime.is_const && width > 0 && !x.is_xz());
        let msb_set = value.is_some_and(|x| !x.select(width - 1, width - 1).is_zero());
        let non_negative = value.is_some() && !(signed && msb_set);
        let is_zero = value.is_some_and(|x| x.is_zero());
        let is_min = signed
            && msb_set
            && value.is_some_and(|x| width == 1 || x.select(width - 2, 0).is_zero());
        let magnitude = value
            .filter(|_| non_negative)
            .and_then(|x| x.to_u64())
            .map(|x| (u64::BITS - x.leading_zeros()) as usize);
        Self {
            signed,
            width,
            sv_width: width,
            // An unsized fill takes the context's width; only `'0` is the
            // same at every width.
            widens: !self_determined
                || (width == 0 && !comptime.get_value().is_ok_and(|x| x.is_zero())),
            sign_sensitive: !(non_negative && self_determined),
            magnitude,
            bound: false,
            exclusive: false,
            is_const: value.is_some(),
            is_zero,
            is_min,
            known,
            is_string: r#type.is_string(),
            token: expr.token_range(),
        }
    }

    fn bound(self) -> Self {
        Self {
            bound: true,
            ..self
        }
    }

    /// `(hi)-1` has at least the 32 bits of `1`.
    fn exclusive_bound(self) -> Self {
        Self {
            sv_width: self.width.max(32),
            exclusive: true,
            ..self.bound()
        }
    }

    /// The `values` SystemVerilog, sizing and signing `target` and all of
    /// them together, may compare differently from Veryl, which compares each
    /// with the target alone.
    fn mismatches<'a>(target: &Self, values: &'a [Self]) -> Vec<(&'a Self, CaseLabelMismatch)> {
        if !target.known || values.iter().any(|x| !x.known) {
            return Vec::new();
        }
        let width = values
            .iter()
            .map(|x| x.sv_width)
            .fold(target.width, usize::max);
        let signed = target.signed && values.iter().all(|x| x.signed);
        values
            .iter()
            .filter_map(|x| {
                // `(hi)-1` wraps at the minimum of the type it is evaluated
                // in, which a signed bound reaches only if nothing widens it.
                let wraps = !x.is_const
                    || (!signed && x.is_zero)
                    || (signed && x.is_min && x.width >= width);
                if x.exclusive && wraps {
                    return Some((x, CaseLabelMismatch::ExclusiveBound));
                }
                let widens = x.widens || target.widens;
                let width_kept = x.width.max(target.width) == width || !widens;
                // A negative target extended either way differs from a
                // non-negative constant narrower than its sign bit.
                let below_target_sign = x.magnitude.is_some_and(|m| m < target.width);
                let sign_kept = (target.signed && x.signed) == signed
                    || !(target.sign_sensitive || x.sign_sensitive)
                    || (!x.bound && !widens && target.width == width && x.width == width)
                    || (!x.bound && !widens && !x.sign_sensitive && below_target_sign);
                (!(width_kept && sign_kept)).then_some((x, CaseLabelMismatch::Joint))
            })
            .collect()
    }

    pub fn check(context: &mut Context, target: &Self, values: &[Self]) {
        // A generic definition's widths are known only per instance.
        if context.in_generic {
            return;
        }
        for (x, kind) in Self::mismatches(target, values) {
            context.insert_error(AnalyzerError::mismatch_case_label(kind, &x.token));
        }
    }
}

/// Each value is evaluated within its comparison with `tgt`, as in an `if`,
/// and its own shape appended to `operands`.
pub fn case_patterns(
    context: &mut Context,
    cond: &CaseCondition,
    tgt: &ir::Expression,
    operands: &mut Vec<CaseOperand>,
) -> IrResult<Vec<ir::CasePattern>> {
    let mut ret = Vec::with_capacity(1 + cond.case_condition_list.len());
    ret.push(range_item_pattern(
        context,
        &cond.range_item,
        tgt,
        operands,
    )?);
    for x in &cond.case_condition_list {
        ret.push(range_item_pattern(context, &x.range_item, tgt, operands)?);
    }
    Ok(ret)
}

/// Gives `value` the context of its comparison with `tgt`.
fn eval_against_target(
    context: &mut Context,
    tgt: &ir::Expression,
    op: Op,
    value: ir::Expression,
    value_first: bool,
) -> ir::Expression {
    let comptime = Box::new(Comptime::create_unknown(value.token_range()));
    let (x, y) = if value_first {
        (Box::new(value), Box::new(tgt.clone()))
    } else {
        (Box::new(tgt.clone()), Box::new(value))
    };
    let mut cond = ir::Expression::Binary(x, op, y, comptime);
    let expr_context = cond.gather_context(context);
    cond.apply_context(context, expr_context);
    let ir::Expression::Binary(x, _, y, _) = cond else {
        unreachable!()
    };
    if value_first { *x } else { *y }
}

fn range_item_pattern(
    context: &mut Context,
    range_item: &RangeItem,
    tgt: &ir::Expression,
    operands: &mut Vec<CaseOperand>,
) -> IrResult<ir::CasePattern> {
    let lo: ir::Expression = Conv::conv(context, range_item.range.expression.as_ref())?;
    let lo_operand = CaseOperand::new(context, &lo);
    operands.push(lo_operand);

    let Some(opt) = &range_item.range.range_opt else {
        // A string has no wildcard digits, and `==?` does not take one.
        let op = if lo_operand.is_string {
            Op::Eq
        } else {
            Op::EqWildcard
        };
        let lo = eval_against_target(context, tgt, op, lo, false);
        if !lo.comptime().is_const {
            context.insert_error(AnalyzerError::unevaluable_value(
                UnevaluableValueKind::CaseCondition,
                &range_item.into(),
            ));
        }
        return Ok(ir::CasePattern::Eq(Box::new(lo)));
    };
    let lo = eval_against_target(context, tgt, Op::LessEq, lo, true);
    let hi: ir::Expression = Conv::conv(context, opt.expression.as_ref())?;
    let inclusive = matches!(opt.range_operator.as_ref(), RangeOperator::DotDotEqu(_));
    if let Some(lo) = operands.last_mut() {
        *lo = lo.bound();
    }
    let hi_operand = CaseOperand::new(context, &hi);
    operands.push(if inclusive {
        hi_operand.bound()
    } else {
        hi_operand.exclusive_bound()
    });

    let op = if inclusive { Op::LessEq } else { Op::Less };
    let hi = eval_against_target(context, tgt, op, hi, false);
    Ok(ir::CasePattern::Range {
        lo: Box::new(lo),
        hi: Box::new(hi),
        inclusive,
    })
}

pub fn case_condition(
    context: &mut Context,
    tgt: &ir::Expression,
    cond: &CaseCondition,
) -> IrResult<ir::Expression> {
    let target = Some(CaseOperand::new(context, tgt));
    let mut ret = range_item(context, tgt, &cond.range_item, target)?;
    for x in &cond.case_condition_list {
        let item = range_item(context, tgt, &x.range_item, target)?;
        let comptime = Box::new(Comptime::create_unknown(item.token_range()));
        ret = ir::Expression::Binary(Box::new(ret), Op::LogicOr, Box::new(item), comptime);
    }
    Ok(ret)
}

pub fn range_list(
    context: &mut Context,
    tgt: &ir::Expression,
    list: &RangeList,
) -> IrResult<ir::Expression> {
    let mut ret = range_item(context, tgt, &list.range_item, None)?;
    for x in &list.range_list_list {
        let item = range_item(context, tgt, &x.range_item, None)?;
        let comptime = Box::new(Comptime::create_unknown(item.token_range()));
        ret = ir::Expression::Binary(Box::new(ret), Op::LogicOr, Box::new(item), comptime);
    }
    Ok(ret)
}

/// A `case` item's values (`target` set) are left for their comparisons
/// with the target to evaluate, as in an `if`.
fn range_item(
    context: &mut Context,
    tgt: &ir::Expression,
    range_item: &RangeItem,
    target: Option<CaseOperand>,
) -> IrResult<ir::Expression> {
    fn eval(context: &mut Context, exp: &mut ir::Expression, in_case: bool) -> Comptime {
        if in_case {
            exp.clone().eval_comptime(context, None).clone()
        } else {
            exp.eval_comptime(context, None).clone()
        }
    }

    let mut exp: ir::Expression = Conv::conv(context, range_item.range.expression.as_ref())?;
    let lo_operand = target.map(|_| CaseOperand::new(context, &exp));

    let comptime = eval(context, &mut exp, target.is_some());
    let lo_value = comptime.get_value().ok().and_then(|v| v.to_usize());
    let lo_is_string = comptime.r#type.is_string();
    if !comptime.is_const && range_item.range.range_opt.is_none() {
        context.insert_error(AnalyzerError::unevaluable_value(
            UnevaluableValueKind::CaseCondition,
            &range_item.into(),
        ));
    }

    let ret = if let Some(x) = &range_item.range.range_opt {
        let mut exp0: ir::Expression = Conv::conv(context, x.expression.as_ref())?;

        let token: TokenRange = range_item.into();
        if let (Some(target), Some(lo)) = (target, lo_operand) {
            let hi = CaseOperand::new(context, &exp0);
            let hi = match x.range_operator.as_ref() {
                RangeOperator::DotDot(_) => hi.exclusive_bound(),
                RangeOperator::DotDotEqu(_) => hi.bound(),
            };
            CaseOperand::check(context, &target, &[lo.bound(), hi]);
        }
        let comptime = eval(context, &mut exp0, target.is_some());

        // An empty exclusive range (constant `lo >= hi`) miscompiles: the emitter's
        // `(hi)-1` underflows an unsigned `hi == 0` to a near-universal range.
        if matches!(x.range_operator.as_ref(), RangeOperator::DotDot(_))
            && let (Some(lo), Some(hi)) = (
                lo_value,
                comptime.get_value().ok().and_then(|v| v.to_usize()),
            )
            && lo >= hi
        {
            context.insert_error(AnalyzerError::invalid_range(
                "the lower bound of an exclusive range is not less than the upper bound",
                &token,
            ));
        }

        let comptime = Box::new(Comptime::create_unknown(token));

        match x.range_operator.as_ref() {
            RangeOperator::DotDot(_) => {
                let cond0 = ir::Expression::Binary(
                    Box::new(exp.clone()),
                    Op::LessEq,
                    Box::new(tgt.clone()),
                    comptime.clone(),
                );
                let cond1 = ir::Expression::Binary(
                    Box::new(tgt.clone()),
                    Op::Less,
                    Box::new(exp0.clone()),
                    comptime.clone(),
                );
                ir::Expression::Binary(Box::new(cond0), Op::LogicAnd, Box::new(cond1), comptime)
            }
            RangeOperator::DotDotEqu(_) => {
                let cond0 = ir::Expression::Binary(
                    Box::new(exp.clone()),
                    Op::LessEq,
                    Box::new(tgt.clone()),
                    comptime.clone(),
                );
                let cond1 = ir::Expression::Binary(
                    Box::new(tgt.clone()),
                    Op::LessEq,
                    Box::new(exp0.clone()),
                    comptime.clone(),
                );
                ir::Expression::Binary(Box::new(cond0), Op::LogicAnd, Box::new(cond1), comptime)
            }
        }
    } else {
        let token: TokenRange = range_item.into();
        let comptime = Box::new(Comptime::create_unknown(token));
        // A string has no wildcard digits, and `==?` does not take one.
        let op = if lo_is_string { Op::Eq } else { Op::EqWildcard };
        ir::Expression::Binary(Box::new(tgt.clone()), op, Box::new(exp), comptime)
    };
    Ok(ret)
}

pub fn switch_condition(context: &mut Context, cond: &SwitchCondition) -> IrResult<ir::Expression> {
    let mut ret: ir::Expression = Conv::conv(context, cond.expression.as_ref())?;
    for x in &cond.switch_condition_list {
        let exp: ir::Expression = Conv::conv(context, x.expression.as_ref())?;
        let comptime = Box::new(Comptime::create_unknown(exp.token_range()));
        ret = ir::Expression::Binary(Box::new(ret), Op::LogicOr, Box::new(exp), comptime);
    }
    // Resolve comptime widths like `if` conditions / `case` targets do;
    // otherwise a compound condition's sub-expression widths stay unevaluated.
    ret.eval_comptime(context, None);
    Ok(ret)
}

pub fn argument_list(context: &mut Context, value: &ArgumentList) -> IrResult<Arguments> {
    let mut positional = vec![];
    let mut named = vec![];
    let mut seen_named = HashSet::default();
    let x: Vec<_> = value.into();
    for arg in x {
        if let Some(x) = &arg.argument_item_opt {
            if let Some(name) = arg.argument_expression.expression.unwrap_identifier() {
                let name_token = name.identifier().token;
                let name = name_token.text;
                let token: TokenRange = x.expression.as_ref().into();
                if !seen_named.insert(name) {
                    context.insert_error(AnalyzerError::duplicate_argument(
                        &name_token.to_string(),
                        &token,
                    ));
                }
                let expr = Conv::conv(context, x.expression.as_ref())?;
                let dst: Vec<VarPathSelect> = Conv::conv(context, x.expression.as_ref())?;
                named.push((name, (expr, dst, token)));
            } else {
                // TODO error
            }
        } else {
            let token: TokenRange = arg.argument_expression.expression.as_ref().into();
            let expr = Conv::conv(context, arg.argument_expression.expression.as_ref())?;
            let dst: Vec<VarPathSelect> =
                Conv::conv(context, arg.argument_expression.expression.as_ref())?;
            positional.push((expr, dst, token));
        }
    }

    if !positional.is_empty() && !named.is_empty() {
        context.insert_error(AnalyzerError::mixed_function_argument(&value.into()));
    }

    let ret = if !positional.is_empty() && !named.is_empty() {
        Arguments::Mixed(positional, named)
    } else if !named.is_empty() {
        Arguments::Named(named)
    } else if !positional.is_empty() {
        Arguments::Positional(positional)
    } else {
        Arguments::Null
    };
    Ok(ret)
}

pub fn get_component(
    context: &mut Context,
    sig: &Signature,
    token: TokenRange,
) -> IrResult<Arc<ir::Component>> {
    get_component_at(context, sig, token, None)
}

/// Records `token` as the instantiation site for diagnostics raised inside.
pub fn get_instantiated_component(
    context: &mut Context,
    sig: &Signature,
    token: TokenRange,
) -> IrResult<Arc<ir::Component>> {
    get_component_at(context, sig, token, Some(token))
}

fn get_component_at(
    context: &mut Context,
    sig: &Signature,
    token: TokenRange,
    site: Option<TokenRange>,
) -> IrResult<Arc<ir::Component>> {
    // Normalize before any cache operations so keys always match what push() stores.
    let mut sig = sig.clone();
    sig.normalize();
    let sig = &sig;

    if let Some((component, in_generic)) = context.get_instance_history(sig) {
        if in_generic && !context.in_generic {
            // The IR result gotten from the cache may be incomplete
            // if the `in_generic` flag is set.
            // Such result should be removed from the cache and be created again.
            context.remove_instance_history(sig);
            get_component_at(context, sig, token, site)
        } else {
            Ok(component)
        }
    } else {
        let symbol = symbol_table::get(sig.symbol).unwrap();

        if let SymbolKind::SystemVerilog = symbol.kind {
            let component = ir::SystemVerilog {
                name: symbol.token.text,
                connects: vec![],
            };
            return Ok(Arc::new(ir::Component::SystemVerilog(component)));
        }

        let err = context.push_instance_history(sig.clone(), site);

        if let Err(x) = err {
            match x {
                InstanceHistoryError::ExceedDepthLimit(x) => {
                    context.insert_error(AnalyzerError::exceed_limit(
                        ExceedLimitKind::HierarchyDepth,
                        x,
                        &token,
                    ));
                }
                InstanceHistoryError::ExceedTotalLimit(x) => {
                    context.insert_error(AnalyzerError::exceed_limit(
                        ExceedLimitKind::TotalInstance,
                        x,
                        &token,
                    ));
                }
                InstanceHistoryError::InfiniteRecursion => {
                    context.insert_error(AnalyzerError::infinite_recursion(&token));
                }
            }
            return Err(ir_error!(token));
        }

        context.push_generic_map(sig.to_generic_map());

        let ret = context.block(|c| match &symbol.kind {
            SymbolKind::Module(x) if !x.is_proto => {
                let definition =
                    definition_table::get(x.definition).ok_or_else(|| ir_error!(token))?;
                let Definition::Module(x) = definition.as_ref() else {
                    unreachable!()
                };

                let header_only = c.in_generic;
                let component: IrResult<ir::Module> = Conv::conv(c, (x, header_only));
                match component {
                    Ok(mut component) => {
                        component.signature = sig.clone();
                        if !c.config.retain_component_body {
                            component.functions.clear();
                            component.declarations.clear();
                        }

                        let component = Arc::new(ir::Component::Module(component));
                        c.set_instance_history(sig, component.clone());
                        Ok(component)
                    }
                    Err(x) => Err(x),
                }
            }
            SymbolKind::Interface(x) if !x.is_proto => {
                let definition = x
                    .definition
                    .and_then(definition_table::get)
                    .ok_or_else(|| ir_error!(token))?;
                let Definition::Interface(x) = definition.as_ref() else {
                    unreachable!()
                };

                let component: IrResult<ir::Interface> = Conv::conv(c, x);
                component.map(|component| {
                    let component = Arc::new(ir::Component::Interface(component));
                    c.set_instance_history(sig, component.clone());
                    component
                })
            }
            SymbolKind::Module(x) if x.is_proto => {
                let definition =
                    definition_table::get(x.definition).ok_or_else(|| ir_error!(token))?;
                let Definition::ProtoModule(x) = definition.as_ref() else {
                    unreachable!()
                };

                let component: IrResult<ir::Module> = Conv::conv(c, x);
                match component {
                    Ok(mut component) => {
                        component.signature = sig.clone();
                        if !c.config.retain_component_body {
                            component.functions.clear();
                            component.declarations.clear();
                        }

                        let component = Arc::new(ir::Component::Module(component));
                        c.set_instance_history(sig, component.clone());
                        Ok(component)
                    }
                    Err(x) => Err(x),
                }
            }
            _ => Err(ir_error!(token)),
        });

        // Outside the block so an early `?` in it cannot skip the pop.
        context.pop_instance_history();
        context.pop_generic_map();
        ret
    }
}

/// Resolve the per-element values of an array-typed parameter override.
///
/// `eval_expr` leaves an array value `Unknown` (only scalars fold to
/// `Numeric`), so this must run while the source variables are still in scope,
/// letting the caller carry the values in the override comptime for the
/// instance signature and `eval_const_assign`.
fn resolve_array_value(
    context: &mut Context,
    r#type: &ir::Type,
    expr: &ir::Expression,
) -> Option<Vec<Value>> {
    if r#type.array.is_empty() {
        return None;
    }

    match expr {
        ir::Expression::ArrayLiteral(_, _) => {
            // Clone so folding's constant-fold side effects don't mutate the
            // stored override expression.
            let mut expr = expr.clone();
            eval_array_literal_values(context, r#type, &mut expr)
                .ok()
                .flatten()
        }
        ir::Expression::Term(factor) => {
            let ir::Factor::Variable(id, index, select, _) = factor.as_ref() else {
                return None;
            };
            // A bit/part select can't be copied element-wise.
            if !select.is_empty() {
                return None;
            }
            if index.dimension() == 0 {
                // Whole-array reference; a single-entry template is preserved.
                return context.variables.get(id).map(|v| v.value.clone());
            }
            // Constant-indexed sub-array reference, e.g. `XS[0]` selecting a row
            // of a 2-D source into a 1-D parameter.
            if !index.is_const() {
                return None;
            }
            let idx = index.eval_value(context)?;
            let var = context.variables.get(id)?;
            let shape = &var.r#type.array;
            // calc_range/calc_index don't bounds-check, so an out-of-range index
            // would silently pick the wrong sub-array; reject it here.
            if idx
                .iter()
                .enumerate()
                .any(|(i, &v)| matches!(shape.get(i), Some(&Some(dim)) if v >= dim))
            {
                return None;
            }
            let (beg, end) = shape.calc_range(&idx)?;
            let inner_total = end - beg + 1;
            let total = var.r#type.total_array().unwrap_or(var.value.len());
            if var.value.len() == total {
                var.value.get(beg..=end).map(<[Value]>::to_vec)
            } else if var.value.len() == 1 {
                // All-same array stored as a single template value.
                Some(vec![var.value[0].clone(); inner_total])
            } else {
                None
            }
        }
        _ => None,
    }
}

/// The width expression names the component's scope, so the instantiating
/// module's variables must not be in reach: they resolve first, and a parameter
/// the two modules happen to give the same name would answer with the caller's
/// value. With none, resolution goes through the symbol route, where this
/// instantiation's overrides are what a parameter stands for.
fn size_in_component_scope(
    context: &mut Context,
    r#type: &crate::symbol::Type,
) -> IrResult<ir::Type> {
    let mut external = Context::default();
    external.inherit(context);
    external.enter_component_sizing();
    let ret = external.block(|c| r#type.to_ir_type(c, TypePosition::Variable));
    external.leave_component_sizing();
    context.inherit(&mut external);
    ret
}

/// Follow `alias module` / `alias interface` to the symbol that declares the
/// parameters. The chain is bounded the way the instantiation checker bounds
/// it: a revisited symbol ends the walk rather than looping.
fn resolve_alias_target(symbol: &Rc<Symbol>) -> Rc<Symbol> {
    let mut current = Rc::clone(symbol);
    let mut visited = vec![current.id];
    loop {
        let target = match &current.kind {
            SymbolKind::AliasModule(x) => &x.target,
            SymbolKind::AliasInterface(x) => &x.target,
            _ => return current,
        };
        let path: SymbolPathNamespace = (&target.generic_path(), &current.namespace).into();
        let Ok(resolved) = symbol_table::resolve(&path) else {
            return current;
        };
        if visited.contains(&resolved.found.id) {
            return current;
        }
        visited.push(resolved.found.id);
        current = Rc::clone(&resolved.found);
    }
}

pub fn get_overridden_params(
    context: &mut Context,
    arg: &ComponentInstantiation,
) -> IrResult<HashMap<VarPath, (Comptime, ir::Expression)>> {
    let token: TokenRange = arg.scoped_identifier.as_ref().into();
    let symbol =
        symbol_table::resolve(arg.scoped_identifier.as_ref()).map_err(|_| ir_error!(token))?;
    // An `alias module` has its own namespace, and the parameters live in the
    // TARGET's. Resolving them in the alias's finds nothing, and the loop
    // below skips what it cannot resolve -- so every override through an
    // alias was dropped in silence. `get_parameters` is empty for an alias
    // too, which would leave the declaration order below unknown.
    let component = resolve_alias_target(&symbol.found);
    let component_namespace = component.inner_namespace();

    let params: Vec<_> = if let Some(ref x) = arg.component_instantiation_opt1 {
        if let Some(x) = &x.inst_parameter.inst_parameter_opt {
            x.inst_parameter_list.as_ref().into()
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    };

    // A parameter's declared width can name a parameter that precedes it, so
    // the values are bound in declaration order: by the time one is sized,
    // everything its width may legally name is already bound. An instantiation
    // may write them in any order.
    let order: HashMap<StrId, usize> = component
        .kind
        .get_parameters()
        .iter()
        .enumerate()
        .map(|(i, x)| (x.name, i))
        .collect();
    let mut params: Vec<_> = params.into_iter().enumerate().collect();
    params.sort_by_key(|(i, param)| {
        (
            order
                .get(&param.identifier.text())
                .copied()
                .unwrap_or(usize::MAX),
            *i,
        )
    });

    context.push_override(component_namespace.clone(), HashMap::default());
    let result = (|| -> IrResult<()> {
        for (_, param) in params {
            let name = param.identifier.text();

            let Ok(target) =
                symbol_table::resolve((param.identifier.as_ref(), &component_namespace))
                    .map(|x| Rc::clone(&x.found))
            else {
                continue;
            };

            // A type that will not size is no reason to drop the binding; a
            // parameter declaring no type takes this same route.
            let target_type = target
                .kind
                .get_type()
                .and_then(|x| size_in_component_scope(context, x).ok());

            let mut expr = if let Some(x) = &param.inst_parameter_item_opt {
                eval_expr(context, target_type.clone(), &x.expression, false)?
            } else {
                let src: Expression = param.identifier.as_ref().into();
                eval_expr(context, target_type.clone(), &src, false)?
            };

            // Carry an array override's element values as a NumericArray so the
            // signature distinguishes them and eval_const_assign can materialize it.
            if expr.0.value.is_unknown()
                && let Some(r#type) = &target_type
                && let Some(values) = resolve_array_value(context, r#type, &expr.1)
            {
                expr.0.value = ValueVariant::NumericArray(values);
            }

            // An element of an unpacked-array parameter arrives const but
            // unfolded, so no instance is specialised and a width derived from it
            // stays symbolic — which the simulator cannot elaborate.
            if expr.0.value.is_unknown()
                && expr.0.is_const
                && let Some(value) = expr.1.eval_value(context)
            {
                expr.0.value = ValueVariant::Numeric(value);
            }

            let is_type_param = matches!(
                &target.kind,
                SymbolKind::Parameter(x) if !x.is_proto && matches!(x.r#type.kind, TypeKind::Type)
            );
            if !is_type_param && !expr.0.is_const {
                let token: TokenRange = param.identifier.as_ref().into();
                context.insert_error(AnalyzerError::unevaluable_value(
                    UnevaluableValueKind::ParameterValue,
                    &token,
                ));
            }

            // An override is converted to the parameter's DECLARED type
            // (IEEE 1800-2023 23.10), so a wider value keeps only the low
            // bits. The variable the parameter becomes is fitted on its own,
            // which is why the wrapper reads correctly; what is stored here is
            // what the next level down is handed, and an untruncated value
            // there reaches a wider child parameter whole.
            //
            // `is_bit_sized` is the gate, not the presence of a width:
            // `TypeKind::width` answers `Some(1)` for `string` as well, and
            // fitting a `string` parameter to one bit loses the text.
            if !is_type_param
                && let Some(r#type) = &target_type
                && r#type.kind.is_bit_sized()
                && let Some(width) = r#type
                    .total_width()
                    .zip(r#type.total_array())
                    .map(|(w, n)| w * n)
            {
                expr.0.value.trunc_value(width);
            }

            context.insert_override(VarPath::new(name), expr);
        }

        Ok(())
    })();
    let ret = context.take_override();
    result?;

    Ok(ret)
}

pub fn get_return_str() -> StrId {
    resource_table::insert_str("return")
}

pub struct PortConnects {
    pub connects: Vec<(VarPath, Vec<VarPathSelect>, ir::Expression)>,
    pub interface_binding: Option<VarPathSelect>,
}

pub fn get_port_connects(
    context: &mut Context,
    component: &ir::Module,
    port: &InstPortItem,
    port_path: &VarPath,
    port_type: &ir::Type,
    token: TokenRange,
) -> IrResult<PortConnects> {
    let mut ret = vec![];
    let mut interface_binding = None;

    if let ir::TypeKind::Modport(_, _) = &port_type.kind {
        if let Some(x) = &port.inst_port_item_opt {
            // for check_compatibility
            let _ = eval_expr(context, Some(port_type.clone()), &x.expression, false)?;
        }

        let (dst_path, dst_select) = if let Some(x) = &port.inst_port_item_opt {
            let dst: Vec<VarPathSelect> = Conv::conv(context, x.expression.as_ref())?;
            let dst = dst.first().ok_or_else(|| ir_error!(token))?;
            let mut path = dst.0.clone();
            // An explicit modport selects a view of the interface; its members
            // still live under the interface instance, not under that view.
            if let Some(identifier) = x.expression.unwrap_identifier()
                && let Ok(symbol) = symbol_table::resolve(identifier)
                && matches!(symbol.found.kind, SymbolKind::Modport(_))
            {
                path.0.pop();
            }
            (path, dst.1.clone())
        } else {
            (port_path.clone(), VarSelect::default())
        };
        interface_binding = Some(VarPathSelect(dst_path.clone(), dst_select.clone(), token));

        let members = port_type.expand_modport(context, &dst_path, token)?;
        for member in members {
            if member.1.is_input() | member.1.is_output() {
                let member_path = member.0.clone();
                let expr = if let Some((var_id, mut comptime)) = context.find_path(&member_path) {
                    comptime.token = token;
                    // Apply dst_select (e.g. `[i]` in `port: s_port[i]`):
                    // array dims go to the variable's index, the rest to a bit select.
                    let (array_select, width_select) =
                        dst_select.clone().split(comptime.r#type.array.dims());
                    comptime.r#type.array.drain(0..array_select.dimension());
                    ir::Expression::Term(Box::new(ir::Factor::Variable(
                        var_id,
                        array_select.to_index(),
                        width_select,
                        comptime,
                    )))
                } else {
                    let comptime = Comptime::create_unknown(token);
                    ir::Expression::Term(Box::new(ir::Factor::Unknown(comptime)))
                };
                let dst = vec![VarPathSelect(
                    member_path.clone(),
                    dst_select.clone(),
                    token,
                )];

                // append member name to port_path
                let mut port_path = port_path.clone();
                let mut member_name = member_path.0.clone();
                member_name.remove(0);
                port_path.append(&member_name);

                ret.push((port_path.clone(), dst, expr));
            }
        }
    } else if let Some(x) = &port.inst_port_item_opt {
        let mut allow_anonymous = true;

        if let Some(id) = component.ports.get(port_path)
            && let Some(variable) = component.variables.get(id)
            && variable.kind == VarKind::Input
        {
            allow_anonymous = false;
        }

        let (comptime, expr) = eval_expr(
            context,
            Some(port_type.clone()),
            &x.expression,
            allow_anonymous,
        )?;

        check_compatibility(context, port_type, &comptime, &token);

        let dst: Vec<VarPathSelect> = Conv::conv(context, x.expression.as_ref())?;

        ret.push((port_path.clone(), dst, expr));
    } else if let Some((var_id, mut comptime)) = context.find_path(port_path) {
        check_compatibility(context, port_type, &comptime, &token);

        comptime.token = token;
        let expr = ir::Expression::Term(Box::new(ir::Factor::Variable(
            var_id,
            VarIndex::default(),
            VarSelect::default(),
            comptime,
        )));
        let dst = vec![VarPathSelect(
            port_path.clone(),
            VarSelect::default(),
            token,
        )];
        ret.push((port_path.clone(), dst, expr));
    }

    Ok(PortConnects {
        connects: ret,
        interface_binding,
    })
}

/// Expands an unpacked-array slice connection (`i: arr[2*n+:2]`) into one
/// expression per port element; anything else stays a single expression.
///
/// Separate from `insert_port_connect` so the caller can clock-domain check the
/// result: unexpanded, the slice evaluates to `Unknown`, which carries no domain.
pub fn expand_input_connect(
    context: &mut Context,
    variable: &ir::Variable,
    dst: &[VarPathSelect],
    expr: ir::Expression,
) -> Vec<ir::Expression> {
    if variable.kind != VarKind::Input
        || variable.r#type.array.is_empty()
        || dst.len() != 1
        || !dst[0].is_array_range(context)
    {
        return vec![expr];
    }

    // A mismatched count keeps the single-expression form, so a malformed
    // connection is diagnosed downstream as before.
    let exprs = dst[0].clone().to_expressions(context);
    if exprs.len() == variable.r#type.total_array().unwrap_or(1) {
        exprs
    } else {
        vec![expr]
    }
}

pub fn insert_port_connect(
    context: &mut Context,
    variable: &ir::Variable,
    dst: Vec<VarPathSelect>,
    exprs: Vec<ir::Expression>,
    inputs: &mut Vec<ir::InstInput>,
    outputs: &mut Vec<ir::InstOutput>,
) {
    match variable.kind {
        VarKind::Input => {
            inputs.push(ir::InstInput {
                id: variable.id,
                exprs,
            });
        }
        VarKind::Output => {
            // Expansion applies to inputs only, so an output always has one.
            let expr = &exprs[0];
            if !expr.is_assignable() {
                context.insert_error(AnalyzerError::unassignable_output(&expr.token_range()));
            }
            let dst = var_path_to_assign_destination(context, dst, false);
            outputs.push(ir::InstOutput {
                id: variable.id,
                dst,
            });
        }
        _ => (),
    }
}

pub fn expand_connect(
    context: &mut Context,
    lhs: VarPathSelect,
    rhs: VarPathSelect,
    token: TokenRange,
) -> IrResult<Vec<ir::Statement>> {
    let mut ret = vec![];

    let (lhs_path, lhs_select, lhs_token) = lhs.into();
    let (rhs_path, rhs_select, rhs_token) = rhs.into();

    if let Some((_, lhs_comptime)) = context.find_path(&lhs_path)
        && let Some((_, rhs_comptime)) = context.find_path(&rhs_path)
    {
        // remove modport name from path
        let mut lhs_base = lhs_path.clone();
        let mut rhs_base = rhs_path.clone();
        if lhs_base.0.len() != 1 {
            lhs_base.pop();
        }
        if rhs_base.0.len() != 1 {
            rhs_base.pop();
        }

        let lhs_members = lhs_comptime
            .r#type
            .expand_modport(context, &lhs_base, lhs_token)?;
        let rhs_members = rhs_comptime
            .r#type
            .expand_modport(context, &rhs_base, rhs_token)?;

        let rhs_members: HashMap<_, _> = rhs_members
            .into_iter()
            .map(|(path, dir)| {
                let mut key = path.clone();
                key.remove_prelude(&rhs_base.0);
                (key, (path, dir))
            })
            .collect();

        for lhs in &lhs_members {
            let mut key = lhs.0.clone();
            key.remove_prelude(&lhs_base.0);
            if let Some(rhs) = rhs_members.get(&key) {
                let lhs_path = lhs.0.clone();
                let rhs_path = rhs.0.clone();
                let lhs_direction = lhs.1;
                let rhs_direction = rhs.1;
                let lhs = VarPathSelect(lhs_path, lhs_select.clone(), lhs_token);
                let rhs = VarPathSelect(rhs_path, rhs_select.clone(), rhs_token);

                let (dst, src) = if lhs_direction.is_output() && rhs_direction.is_input() {
                    (lhs, rhs)
                } else if rhs_direction.is_output() && lhs_direction.is_input() {
                    (rhs, lhs)
                } else {
                    // TODO direction error
                    return Ok(ret);
                };

                if let Some((_, mut dst_comptime)) = context.find_path(&dst.0)
                    && let Some((_, mut src_comptime)) = context.find_path(&src.0)
                {
                    dst_comptime.token = dst.2;
                    src_comptime.token = src.2;
                    check_clock_domain(context, &dst_comptime, &src_comptime, &token.beg);
                }

                if let Some(src) = src.to_expression(context)
                    && let Some(dst) = dst.to_assign_destination(context, false)
                {
                    let width = dst.total_width(context);
                    let statement = ir::Statement::Assign(ir::AssignStatement {
                        hier_dst: None,
                        dst: vec![dst],
                        width,
                        expr: src,
                        token,
                    });
                    ret.push(statement);
                } else {
                    // TODO unknown member error
                }
            }
        }
    }

    Ok(ret)
}

pub fn expand_connect_const(
    context: &mut Context,
    lhs: VarPathSelect,
    comptime: Comptime,
    token: TokenRange,
) -> IrResult<Vec<ir::Statement>> {
    let mut ret = vec![];

    let (lhs_path, lhs_select, lhs_token) = lhs.into();

    if let Some((_, lhs_comptime)) = context.find_path(&lhs_path) {
        // remove modport name from path
        let mut lhs_base = lhs_path.clone();
        if lhs_base.0.len() != 1 {
            lhs_base.pop();
        }

        let lhs_members = lhs_comptime
            .r#type
            .expand_modport(context, &lhs_base, lhs_token)?;

        for lhs in lhs_members {
            if lhs.1.is_output() {
                let dst = VarPathSelect(lhs.0, lhs_select.clone(), lhs_token);
                let mut comptime = comptime.clone();
                comptime.token = token;
                let src = ir::Factor::Value(comptime);
                let src = ir::Expression::Term(Box::new(src));

                if let Some(dst) = dst.to_assign_destination(context, false) {
                    let width = dst.total_width(context);
                    let statement = ir::Statement::Assign(ir::AssignStatement {
                        hier_dst: None,
                        dst: vec![dst],
                        width,
                        expr: src,
                        token,
                    });
                    ret.push(statement);
                } else {
                    // TODO unknown member error
                }
            }
        }
    }

    Ok(ret)
}

pub fn var_path_to_assign_destination(
    context: &mut Context,
    path: Vec<VarPathSelect>,
    ignore_error: bool,
) -> Vec<ir::AssignDestination> {
    path.into_iter()
        .flat_map(|x| x.to_assign_destinations(context, ignore_error))
        .collect()
}

fn get_function(context: &mut Context, path: &FuncPath, token: TokenRange) -> IrResult<FuncProto> {
    fn conv_function(
        context: &mut Context,
        definition: DefinitionId,
        path: &FuncPath,
    ) -> IrResult<()> {
        let definition = definition_table::get(definition).unwrap();
        match definition.as_ref() {
            Definition::Function(x) => Conv::conv(context, (x, Some(path))),
            Definition::ProtoFunction(x) => Conv::conv(context, (x, Some(path))),
            _ => unreachable!(),
        }
    }

    if !context.func_paths.contains_key(path) {
        let symbol = symbol_table::get(path.sig.symbol).unwrap();
        let (definition, is_global) = match &symbol.kind {
            SymbolKind::Function(x) => (x.definition.unwrap(), x.is_global()),
            SymbolKind::ModportFunctionMember(x) => {
                let symbol = symbol_table::get(x.function).unwrap();
                let SymbolKind::Function(x) = symbol.kind else {
                    unreachable!();
                };
                (x.definition.unwrap(), false)
            }
            _ => return Err(ir_error!(token)),
        };

        let array = if let Some((_, comptime)) = context.find_path(&path.path) {
            comptime.r#type.array
        } else {
            Shape::default()
        };

        let is_local_func = context
            .current_namespace()
            .map(|namespace| symbol.namespace.included(&namespace))
            .unwrap_or(false);
        if is_local_func {
            let ret = conv_function(context, definition, path);
            ret?;
        } else {
            let mut local_context = Context::default();
            local_context.var_id = context.var_id;
            local_context.inherit(context);
            local_context.extract_var_paths(context, &path.path, &array);

            let caller = is_global
                .then(|| local_context.current_namespace())
                .flatten();
            if let Some(namespace) = &caller {
                local_context.push_global_func_caller(namespace.clone());
            }

            let ret = conv_function(&mut local_context, definition, path);

            if caller.is_some() {
                local_context.pop_global_func_caller();
            }

            context.extract_function(&mut local_context, &path.path, &array);
            context.inherit(&mut local_context);
            context.var_id = local_context.var_id;

            ret?;
        }
    }

    let Some(id) = context.func_paths.get(path) else {
        return Err(ir_error!(token));
    };
    context
        .functions
        .get(id)
        .map(|func| func.to_proto())
        .ok_or_else(|| ir_error!(token))
}

pub fn function_call(
    context: &mut Context,
    path: &ExpressionIdentifier,
    args: Arguments,
    token: TokenRange,
) -> IrResult<ir::FunctionCall> {
    let generic_path: GenericSymbolPath = path.into();

    check_generic_refereence(context, &generic_path);

    let mut sig =
        Signature::from_path(context, generic_path.clone()).ok_or_else(|| ir_error!(token))?;
    sig.normalize();

    // same signature re-entered => true infinite recursion
    if context.function_call_stack.contains(&sig) {
        context.insert_error(AnalyzerError::infinite_recursion(&token));
        return Err(ir_error!(token));
    }

    let path: VarPathSelect = Conv::conv(context, path)?;
    let (mut base_path, select, _) = path.into();
    let index = select.to_index();
    let index = index.eval_value(context);

    // remove function name
    base_path.pop();

    let path = ir::FuncPath {
        path: base_path.clone(),
        sig: sig.clone(),
    };

    let map = symbol_table::function_call_generic_maps(&sig, &generic_path);

    context.push_generic_map(map);
    context.function_call_stack.push(sig.clone());

    let ret = context.block(|c| {
        let func = get_function(c, &path, token)?;
        let (mut inputs, outputs) = args.to_function_args(c, &func, token)?;

        let symbol = symbol_table::get(sig.symbol);
        let mut effect = symbol
            .as_ref()
            .and_then(|symbol| match &symbol.kind {
                SymbolKind::Function(func) => Some(RuntimeFunctionEffect {
                    external_write: func.has_side_effect_in(&c.config.defines),
                    written_outputs: func
                        .written_output_paths(&c.config.defines)
                        .into_iter()
                        .filter_map(|path| path.to_var_path())
                        .collect(),
                }),
                _ => None,
            })
            .unwrap_or_default();
        if let Some(runtime_effect) = c.function_effect(&path) {
            effect.external_write |= runtime_effect.external_write;
            effect
                .written_outputs
                .extend(runtime_effect.written_outputs);
        }
        c.record_function_call_effect(&effect, &outputs);

        if c.is_affiliated(Affiliation::AlwaysFf)
            && effect.external_write
            && let Some(symbol) = &symbol
        {
            let definition = TokenRange::from(&symbol.token);
            let external_write = symbol_table::find_external_write(symbol, &sig, c);
            let (calls, external_writes) = external_write
                .map(|trace| (trace.calls, vec![trace.write]))
                .unwrap_or_default();
            c.insert_error(AnalyzerError::side_effect_function_call_in_always_ff(
                &symbol.token.text.to_string(),
                &token,
                &definition,
                &calls,
                &external_writes,
            ));
        }

        if c.is_affiliated(Affiliation::AlwaysFf) {
            for (formal, dsts) in &outputs {
                let Some(formal_name) = formal.0.first() else {
                    continue;
                };
                if effect.written_paths_for(formal).next().is_none() {
                    continue;
                }
                let output = resource_table::get_str_value(*formal_name).unwrap_or_default();
                let output_port = symbol.as_ref().and_then(|symbol| match &symbol.kind {
                    SymbolKind::Function(function) => function.ports.iter().find(|port| {
                        port.token.token.text == *formal_name
                            && symbol_table::get(port.symbol).is_some_and(|symbol| {
                                matches!(symbol.kind, SymbolKind::Port(ref port) if port.direction == symbol::Direction::Output)
                            })
                    }),
                    _ => None,
                });
                let Some(output_port) = output_port else {
                    continue;
                };
                let declaration = TokenRange::from(&output_port.token.token);
                for dst in dsts {
                    if c.get_variable_info(dst.id)
                        .is_some_and(|variable| variable.affiliation != Affiliation::AlwaysFf)
                    {
                        c.insert_error(AnalyzerError::function_output_in_always_ff(
                            &func.name.to_string(),
                            &output,
                            &dst.path.to_string(),
                            &dst.token,
                            Some(&declaration),
                        ));
                    }
                }
            }
        }

        let mut comptime = func.r#type.clone();
        comptime.token = token;

        // Merge the inputs' clock domains into the result and cross-check, so a
        // call can't launder a domain crossing (mirrors Op::eval_type_binary);
        // also check output-arg destinations against the merged domain.
        for expr in inputs.values_mut() {
            let x = expr.eval_comptime(c, None);
            check_clock_domain(c, &comptime, x, &token.beg);
            comptime.clock_domain = comptime.clock_domain.merge(&x.clock_domain);
        }
        for dsts in outputs.values() {
            for dst in dsts {
                let mut dst_comptime = dst.comptime.clone();
                dst_comptime.token = dst.token;
                check_clock_domain(c, &dst_comptime, &comptime, &token.beg);
            }
        }

        Ok(ir::FunctionCall {
            id: func.id,
            index,
            comptime,
            inputs,
            outputs,
        })
    });

    context.pop_generic_map();
    context.function_call_stack.pop();
    ret
}

pub fn check_compatibility(
    context: &mut Context,
    dst: &ir::Type,
    src: &ir::Comptime,
    token: &TokenRange,
) {
    if dst.is_positive
        && let Ok(value) = src.get_value()
        && !(src.r#type.is_positive && value.is_xz())
        && (!value.is_positive() || value.is_semantically_not_positive())
    {
        context.insert_error(AnalyzerError::non_positive_value(
            "non-positive",
            &format_positive_type_name(dst).unwrap(),
            token,
        ));
    }
    // This branch is reached via `eval_expr` BEFORE its dst_type
    // overwrite, so `src` is the connected value's own type; the later
    // call on the same connection sees the overwritten (matching) type
    // and stays silent.
    if (dst.is_clock() || dst.is_reset()) && context.in_inst_port {
        check_implicit_clock_conversion(context, dst, src, token);
        return;
    }
    // The unpacked dimensions are asked on their own axis rather than inside
    // `compatible`, which answers from the element kind for a 2-state, clock or
    // reset destination and never reaches its array branch for one. The answer
    // only refines the help: the severity is the same conservative warning.
    let kind = if dst.array_shape_mismatch(src) {
        Some(MismatchAssignmentKind::ArrayShape)
    } else if !dst.compatible(src, context.in_generic) {
        Some(MismatchAssignmentKind::Normal)
    } else {
        None
    };
    if let Some(kind) = kind {
        context.insert_error(AnalyzerError::mismatch_assignment(
            &src.r#type.to_string(),
            &dst.to_string(),
            kind,
            token,
            &[],
        ));
    }
}

/// Reject implicit conversion to a clock/reset-typed input port or
/// function argument.  `$sv` ports are SystemVerilog-typed and never
/// reach this check, which keeps the SystemVerilog boundary unchecked
/// by design.
pub fn check_implicit_clock_conversion(
    context: &mut Context,
    dst: &ir::Type,
    src: &Comptime,
    token: &TokenRange,
) {
    let dst_is_clock = dst.is_clock();
    let dst_is_reset = dst.is_reset();
    if !dst_is_clock && !dst_is_reset {
        return;
    }
    if src.r#type.is_unknown() || src.r#type.is_systemverilog() || src.is_const {
        return;
    }
    let ok = if dst_is_clock {
        src.r#type.is_clock()
    } else {
        src.r#type.is_reset()
    };
    if !ok {
        context.insert_error(AnalyzerError::implicit_clock_conversion(
            &src.r#type.to_string(),
            &dst.to_string(),
            token,
            &[],
        ));
    }
}

pub fn check_module_with_unevaluable_generic_parameters(ident: &Identifier) -> bool {
    if let Ok(symbol) = symbol_table::resolve(ident)
        && let SymbolKind::Module(x) = &symbol.found.kind
    {
        let mut ret = false;

        for x in &x.generic_parameters {
            let param = symbol_table::get(*x).unwrap();
            if let SymbolKind::GenericParameter(x) = param.kind {
                let has_default = x.default_value.is_some();
                ret |= match &x.bound {
                    GenericBoundKind::Type => false,
                    GenericBoundKind::Inst(_) => false,
                    GenericBoundKind::Proto(x) => {
                        // Fixed type or proto package with non-default may be unevaluable
                        if x.kind.is_fixed() && !has_default {
                            true
                        } else if let TypeKind::UserDefined(x) = &x.kind
                            && let Ok(symbol) = symbol_table::resolve(&x.path)
                            && (matches!(symbol.found.kind, SymbolKind::Package(ref x) if x.is_proto)
                                || matches!(&symbol.found.kind, SymbolKind::AliasPackage(x) if x.is_proto))
                            && !has_default
                        {
                            true
                        } else {
                            false
                        }
                    }
                };
            } else {
                unreachable!();
            }
        }

        ret
    } else {
        false
    }
}

#[cfg(test)]
pub fn parse_expression(s: &str) -> Expression {
    use veryl_parser::parser::Parser;
    use veryl_parser::veryl_walker::VerylWalker;

    let src = format!(
        r#"
        module A {{
            let a: bit = {s};
        }}
        "#
    );
    let parser = Parser::parse(&src, &"").unwrap();

    struct Extractor(Option<Expression>);
    impl VerylWalker for Extractor {
        fn expression(&mut self, arg: &Expression) {
            self.0 = Some(arg.clone());
        }
    }

    let mut extractor = Extractor(None);
    extractor.veryl(&parser.veryl);
    extractor.0.unwrap()
}

/// Where a testbench method call appears, for return-value diagnostics.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum TbMethodCallPosition {
    /// Bare statement: a declared return value would be silently dropped.
    Statement,
    /// Assignment or expression position: the value is consumed.
    Value,
}

/// Converts a method call on a user-defined `$comp` component into a
/// [`TbMethod::Component`], diagnosing the call against the interface
/// manifest when one is present. Returns the method and the resolved return
/// width (`None` when undeclared).
fn conv_external_method_call(
    context: &mut Context,
    component: resource_table::StrId,
    path: &GenericSymbolPath,
    args: Option<ir::Arguments>,
    inst_name: resource_table::StrId,
    position: TbMethodCallPosition,
    token: TokenRange,
) -> IrResult<(TbMethod, Option<u32>)> {
    // Only the exact `instance.method(...)` shape reaches the component;
    // extra path segments or generic arguments would otherwise be silently
    // dropped.
    if path.paths.len() != 2 {
        context.insert_error(AnalyzerError::component_interface_mismatch(
            ComponentInterfaceMismatchKind::MethodCallForm,
            Some(component),
            &token,
        ));
        return Err(ir_error!(token));
    }
    if path.paths.iter().any(|x| !x.arguments.is_empty()) {
        context.insert_error(AnalyzerError::component_interface_mismatch(
            ComponentInterfaceMismatchKind::MethodNoGenericArgs,
            Some(component),
            &token,
        ));
        return Err(ir_error!(token));
    }
    let args: Vec<SystemFunctionInput> = match args {
        Some(ir::Arguments::Positional(ref positional)) => positional
            .iter()
            .map(|arg| SystemFunctionInput(arg.0.clone()))
            .collect(),
        None | Some(ir::Arguments::Null) => Vec::new(),
        // The ABI carries values only, no argument names.
        Some(ir::Arguments::Named(_)) | Some(ir::Arguments::Mixed(..)) => {
            context.insert_error(AnalyzerError::invalid_factor(
                None,
                "component method with named arguments",
                &token,
                &[],
            ));
            return Err(ir_error!(token));
        }
    };
    // The manifest keys methods by their unrawed name.
    let method = resource_table::canonical_str_id(path.paths[path.paths.len() - 1].base.text);
    let mut ret_width = None;
    if let Some(manifest) = crate::component_manifest_table::get(component)
        && !manifest.methods.is_empty()
    {
        let name = method.to_string();
        match manifest.method(&name) {
            None => {
                context.insert_error(AnalyzerError::component_interface_mismatch(
                    ComponentInterfaceMismatchKind::UnknownMethod {
                        method: name.clone(),
                    },
                    Some(component),
                    &token,
                ));
            }
            Some(m) if m.args.len() != args.len() => {
                context.insert_error(AnalyzerError::mismatch_function_arity(
                    &name,
                    m.args.len(),
                    args.len(),
                    &token,
                ));
            }
            Some(m) => {
                match position {
                    TbMethodCallPosition::Statement if m.ret.is_some() => {
                        context.insert_error(AnalyzerError::unused_return(&name, &token));
                    }
                    TbMethodCallPosition::Value if m.ret.is_none() => {
                        context.insert_error(AnalyzerError::component_interface_mismatch(
                            ComponentInterfaceMismatchKind::MethodReturnsNoValue {
                                method: name.clone(),
                            },
                            Some(component),
                            &token,
                        ));
                    }
                    _ => {}
                }

                let inst_params = context
                    .tb_component_params
                    .get(&inst_name)
                    .cloned()
                    .unwrap_or_default();
                let resolve_width =
                    |context: &mut Context, expr: &veryl_metadata::WidthExpr, what: &str| {
                        match veryl_metadata::eval_width_expr(expr, &inst_params) {
                            Some(w) if w > 0 => Some(w as u32),
                            _ => {
                                context.insert_error(AnalyzerError::component_interface_mismatch(
                                    ComponentInterfaceMismatchKind::UnresolvableWidth {
                                        expr: expr.to_string(),
                                        what: what.to_string(),
                                    },
                                    Some(component),
                                    &token,
                                ));
                                None
                            }
                        }
                    };
                if let Some(expr) = &m.ret_width.clone() {
                    ret_width = resolve_width(context, expr, &format!("method `{name}`'s return"));
                    // Method return values cross the host ABI in a fixed
                    // 8 x 64-bit word buffer; wider declared returns can never
                    // be delivered.
                    const METHOD_RET_MAX_WIDTH: u32 = 512;
                    if let Some(w) = ret_width
                        && w > METHOD_RET_MAX_WIDTH
                    {
                        context.insert_error(AnalyzerError::component_interface_mismatch(
                            ComponentInterfaceMismatchKind::MethodReturnTooWide {
                                method: name.clone(),
                                declared: w,
                                max: METHOD_RET_MAX_WIDTH,
                            },
                            Some(component),
                            &token,
                        ));
                    }
                }
                // A `Value` argument's width is inferred from the call-site
                // expression, so there is nothing to check here.
            }
        }
    }
    Ok((TbMethod::Component { method, args }, ret_width))
}

pub fn tb_method_call(
    context: &mut Context,
    expr_id: &ExpressionIdentifier,
    func_call: &FunctionCall,
    token: TokenRange,
    position: TbMethodCallPosition,
) -> IrResult<Option<ir::Statement>> {
    let path: GenericSymbolPath = expr_id.into();

    // Need at least 2 path elements: instance.method
    if path.paths.len() < 2 {
        return Ok(None);
    }

    // Resolve just the first element (the instance name)
    let inst_name = path.paths[0].base.text;
    let inst_path = SymbolPath::new(&[inst_name]);
    let Some((inst_scope, inst_define_context)) = crate::scope::token_scope(path.paths[0].base.id)
    else {
        return Ok(None);
    };

    let inst_symbol = match symbol_table::resolve(SymbolPathNamespace::from_scope(
        inst_path,
        inst_scope,
        inst_define_context,
    )) {
        Ok(s) => s,
        Err(_) => {
            return Ok(None);
        }
    };

    // `$tb` methods are called on either an `inst` (clock_gen/reset_gen) or a
    // `var` (file). Pull the component type path from whichever form it is.
    let type_path = match &inst_symbol.found.kind {
        SymbolKind::Instance(x) => &x.type_name,
        SymbolKind::Variable(x) => {
            if let TypeKind::UserDefined(ref ud) = x.r#type.kind {
                &ud.path
            } else {
                return Ok(None);
            }
        }
        _ => {
            return Ok(None);
        }
    };

    let type_symbol =
        match symbol_table::resolve_generic_structural(type_path, &inst_symbol.found.namespace) {
            Ok(s) => s,
            Err(_) => {
                return Ok(None);
            }
        };

    let tb_kind = match &type_symbol.found.kind {
        SymbolKind::TbComponent(x) => &x.kind,
        _ => {
            return Ok(None);
        }
    };

    let method_name = resource_table::get_str_value(path.paths[path.paths.len() - 1].base.text);
    let method_name = method_name.as_deref().unwrap_or("");

    // Parse arguments for the method call
    let args = if let Some(ref arg_list) = func_call.function_call_opt {
        Some(argument_list(context, arg_list.argument_list.as_ref())?)
    } else {
        None
    };

    let mut ret_width = None;
    let mut ret_signed = false;
    let method = match (tb_kind, method_name) {
        (TbComponentKind::ClockGen, "next") => {
            let count = if let Some(ir::Arguments::Positional(ref positional)) = args
                && !positional.is_empty()
            {
                // Self-determine the width (as for $display args): otherwise a
                // binary count like `clk.next(DW / 2)` keeps a width-0 comptime
                // type and folds to 0 in the simulator.
                let mut count = positional[0].0.clone();
                count.eval_comptime(context, None);
                Some(count)
            } else {
                None
            };
            let period = context
                .tb_clock_period
                .get(&inst_name)
                .cloned()
                .map(Box::new);
            TbMethod::ClockNext { count, period }
        }
        (TbComponentKind::ResetGen, "assert") => {
            let clock = context
                .tb_reset_clock
                .get(&inst_name)
                .copied()
                .ok_or_else(|| ir_error!(token))?;
            let duration = if let Some(ir::Arguments::Positional(ref positional)) = args
                && let Some(arg) = positional.first()
            {
                // Self-determine the width like the count above — else a binary
                // `rst.assert(DW / 2)` folds to 0 (then clamps to 1 cycle).
                let mut duration = arg.0.clone();
                duration.eval_comptime(context, None);
                Some(duration)
            } else {
                context.tb_reset_cycles.get(&inst_name).cloned()
            };
            TbMethod::ResetAssert { clock, duration }
        }
        (TbComponentKind::File, "open") | (TbComponentKind::File, "append") => {
            let name = if let Some(ir::Arguments::Positional(ref positional)) = args
                && let Some(arg) = positional.first()
            {
                SystemFunctionInput(arg.0.clone())
            } else {
                let actual = if let Some(ir::Arguments::Positional(ref positional)) = args {
                    positional.len()
                } else {
                    0
                };
                context.insert_error(AnalyzerError::mismatch_function_arity(
                    method_name,
                    1,
                    actual,
                    &token,
                ));
                return Err(ir_error!(token));
            };
            TbMethod::FileOpen {
                name,
                append: method_name == "append",
            }
        }
        (TbComponentKind::File, "write") => {
            let args = if let Some(ir::Arguments::Positional(ref positional)) = args {
                positional
                    .iter()
                    .map(|arg| SystemFunctionInput(arg.0.clone()))
                    .collect()
            } else {
                Vec::new()
            };
            TbMethod::FileWrite { args }
        }
        (TbComponentKind::File, "close") => TbMethod::FileClose,
        (TbComponentKind::File, "flush") => TbMethod::FileFlush,
        (TbComponentKind::Random, "seed") => {
            let value = random_arg(context, &args, 0, method_name, 1, &token)?;
            TbMethod::RandomSeed { value }
        }
        (TbComponentKind::Random, "get") => {
            let (width, signed) = resolve_random_elem_type(context, type_path);
            ret_width = Some(width);
            ret_signed = signed;
            TbMethod::RandomGet { width, signed }
        }
        (TbComponentKind::Random, "get_range") => {
            let min = random_arg(context, &args, 0, method_name, 2, &token)?;
            let max = random_arg(context, &args, 1, method_name, 2, &token)?;
            let (width, signed) = resolve_random_elem_type(context, type_path);
            ret_width = Some(width);
            ret_signed = signed;
            TbMethod::RandomGetRange {
                min,
                max,
                width,
                signed,
            }
        }
        (TbComponentKind::Random, "get_seed") => {
            ret_width = Some(64);
            TbMethod::RandomGetSeed
        }
        // Any method name is accepted on a user-defined component; the
        // component validates it at run time. With a manifest present the
        // name and arity are also diagnosed here.
        (TbComponentKind::External(component), _) => {
            let (method, rw) = conv_external_method_call(
                context, *component, &path, args, inst_name, position, token,
            )?;
            ret_width = rw;
            method
        }
        _ => return Err(ir_error!(token)),
    };

    Ok(Some(ir::Statement::TbMethodCall(TbMethodCall {
        inst: inst_name,
        method,
        ret: None,
        ret_strict: false,
        ret_width,
        ret_signed,
    })))
}

/// Captures the `i`-th positional argument of a `$tb::random` method as a
/// self-determined expression (its width folds from the argument, as for
/// `$display`). Emits an arity error and fails when the argument is missing.
fn random_arg(
    context: &mut Context,
    args: &Option<ir::Arguments>,
    i: usize,
    method_name: &str,
    arity: usize,
    token: &TokenRange,
) -> IrResult<ir::Expression> {
    if let Some(ir::Arguments::Positional(positional)) = args
        && let Some(arg) = positional.get(i)
    {
        let mut expr = arg.0.clone();
        expr.eval_comptime(context, None);
        Ok(expr)
    } else {
        let actual = if let Some(ir::Arguments::Positional(positional)) = args {
            positional.len()
        } else {
            0
        };
        context.insert_error(AnalyzerError::mismatch_function_arity(
            method_name,
            arity,
            actual,
            token,
        ));
        Err(ir_error!(*token))
    }
}

/// Resolves the element type `T` of a `$tb::random::<T>` variable through the
/// generic maps in effect, returning its `(width, signed)`. The element type's
/// validity (fixed integer / `bbool`) is diagnosed by `check_generic_refereence`;
/// this falls back to a 32-bit unsigned width when resolution fails so a broken
/// type does not also cause a spurious ICE.
fn resolve_random_elem_type(context: &mut Context, type_path: &GenericSymbolPath) -> (u32, bool) {
    let resolved = context.resolve_path(type_path.clone());
    if let Some(arg) = resolved.paths.last().and_then(|p| p.arguments.first())
        && let Ok(ty) = eval_type(context, &arg.clone(), TypePosition::Variable)
        && let Some(width) = ty.total_width()
    {
        (width as u32, ty.signed)
    } else {
        (32, false)
    }
}

/// Hoists a component method call out of an expression: the call runs as
/// its own zero-time statement immediately before the enclosing testbench
/// statement, its return value lands in a synthetic temporary, and the
/// expression reads the temporary. The temporary carries the declared
/// return width when the manifest provides one; otherwise it is 64 bits
/// and a wider return fails at run time (the direct assignment form
/// `x = inst.method(...)` then carries the declared width of `x`).
pub fn hoist_component_method_call(
    context: &mut Context,
    mut method_call: TbMethodCall,
    token: TokenRange,
) -> IrResult<ir::Expression> {
    if context.tb_hoist.is_none() {
        context.insert_error(AnalyzerError::invalid_factor(
            None,
            "component method call outside testbench statements",
            &token,
            &[],
        ));
        return Err(ir_error!(token));
    }

    let width = method_call.ret_width.unwrap_or(64) as usize;
    let signed = method_call.ret_signed;
    let name = format!("__tb_method_ret_{}", context.tb_hoist_count);
    context.tb_hoist_count += 1;
    let path = VarPath::new(resource_table::insert_str(&name));
    let mut r#type = ir::Type::new(ir::TypeKind::Bit);
    r#type.set_concrete_width(Shape::new(vec![Some(width)]));
    r#type.signed = signed;

    let comptime = Comptime::from_type(r#type.clone(), ClockDomain::None, token);
    let id = context.insert_var_path(path.clone(), comptime.clone());
    let array_limit = context.config.evaluate_array_limit;
    let variable = Variable::new(
        id,
        path.clone(),
        VarKind::Variable,
        r#type,
        vec![Value::new_x(width, signed)],
        context.get_affiliation(),
        &token,
        array_limit,
    );
    context.insert_variable(id, variable);

    method_call.ret = Some(Box::new(ir::AssignDestination {
        id,
        path,
        index: VarIndex::default(),
        select: VarSelect::default(),
        comptime: comptime.clone(),
        token,
    }));
    method_call.ret_strict = true;
    context
        .tb_hoist
        .as_mut()
        .unwrap()
        .push(ir::Statement::TbMethodCall(method_call));

    Ok(ir::Expression::Term(Box::new(ir::Factor::Variable(
        id,
        VarIndex::default(),
        VarSelect::default(),
        comptime,
    ))))
}

/// Extracts the sole `receiver.method(...)` call of an expression, when the
/// expression is exactly one identifier factor with a function call. Used to
/// intercept component method calls in assignment position.
pub fn single_function_call_factor(
    expr: &Expression,
) -> Option<(&ExpressionIdentifier, &FunctionCall)> {
    let if_expr = &*expr.if_expression;
    if !if_expr.if_expression_list.is_empty() {
        return None;
    }
    let e01 = &*if_expr.expression01;
    if !e01.expression01_list.is_empty() {
        return None;
    }
    let e02 = &*e01.expression02;
    if !e02.expression02_list.is_empty() || e02.expression02_opt.is_some() {
        return None;
    }
    if let Factor::IdentifierFactor(x) = e02.factor.as_ref()
        && let Some(opt) = &x.identifier_factor.identifier_factor_opt
        && let IdentifierFactorOptGroup::FunctionCall(call) =
            opt.identifier_factor_opt_group.as_ref()
    {
        return Some((
            x.identifier_factor.expression_identifier.as_ref(),
            call.function_call.as_ref(),
        ));
    }
    None
}

#[cfg(test)]
pub fn parse_number(s: &str) -> Number {
    use veryl_parser::parser::Parser;
    use veryl_parser::veryl_walker::VerylWalker;

    let src = format!(
        r#"
        module A {{
            let a: bit = {s};
        }}
        "#
    );
    let parser = Parser::parse(&src, &"").unwrap();

    struct Extractor(Option<Number>);
    impl VerylWalker for Extractor {
        fn number(&mut self, arg: &Number) {
            self.0 = Some(arg.clone());
        }
    }

    let mut extractor = Extractor(None);
    extractor.veryl(&parser.veryl);
    extractor.0.unwrap()
}