veryl-analyzer 0.21.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
mod connect;
mod r#enum;
mod function;
mod msb;

use crate::analyzer_error::DuplicatedIdentifierKind;
use crate::attribute::IfdefCondition;
use crate::attribute_table;
use crate::namespace::{DefineContext, Namespace};
use crate::scope;
use crate::sv_system_function;
use crate::symbol::{
    ConnectTarget, Direction, DocComment, GenericBoundKind, GenericMap, GenericTable,
    GenericTables, InstanceProperty, ModportDefault, ModportFunctionMemberProperty,
    ModportProperty, ModportVariableMemberProperty, Symbol, SymbolId, SymbolKind, TbComponentKind,
    TestProperty, TypeKind,
};
use crate::symbol_path::{
    GenericSymbol, GenericSymbolPath, GenericSymbolPathNamespace, SymbolPath, SymbolPathNamespace,
};
use crate::tb_component;
use crate::wavedrom::{self, DocTestTarget};
use crate::{AnalyzerError, HashMap, HashSet, SVec};
use connect::check_connect;
pub(crate) use function::{
    find_external_write, function_call_generic_maps, specialized_direct_effect,
};
use log::trace;
use msb::check_msb;
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use veryl_parser::resource_table::{self, PathId, StrId};
use veryl_parser::token_collector::TokenCollector;
use veryl_parser::token_range::TokenRange;
use veryl_parser::veryl_grammar_trait::{Expression, ExpressionIdentifier, HierarchicalIdentifier};
use veryl_parser::veryl_token::{Token, TokenSource};
use veryl_parser::veryl_walker::VerylWalker;

#[derive(Clone, Debug)]
pub struct ResolveResult {
    pub found: std::rc::Rc<Symbol>,
    pub full_path: Vec<SymbolId>,
    pub imported: bool,
    pub generic_tables: GenericTables,
}

#[derive(Clone, Debug)]
pub struct ResolveError {
    pub last_found: Option<Box<Symbol>>,
    pub cause: ResolveErrorCause,
}

#[derive(Clone, Debug)]
pub enum ResolveErrorCause {
    NotFound(StrId),
    Private,
    Invisible,
    /// The name resolved to two or more distinct symbols imported at equal
    /// priority (e.g. the same name from two wildcard-imported packages).
    Ambiguous(StrId),
}

impl ResolveError {
    pub fn new(last_found: Option<&Rc<Symbol>>, cause: ResolveErrorCause) -> Self {
        Self {
            last_found: last_found.map(|x| Box::new((**x).clone())),
            cause,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Import {
    pub path: GenericSymbolPathNamespace,
    pub namespace: Namespace,
    pub wildcard: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Bind {
    pub token: Token,
    pub target: GenericSymbolPathNamespace,
    pub doc_comment: DocComment,
    pub property: InstanceProperty,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Msb {
    pub token: Token,
    pub path: SymbolPathNamespace,
    pub dimension: usize,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Connect {
    Statement(ExpressionIdentifier, Expression),
    Declaration(HierarchicalIdentifier, Expression),
}

/// Pending-list lengths captured before one file's pass1; delimits the
/// file's additions for fragment caching.
#[derive(Clone, Copy, Debug)]
pub struct PendingWatermark {
    import: usize,
    bind: usize,
    msb: usize,
    connect: usize,
}

/// Outcome of a lexical `lookup_name` over the scope tree.
enum LexicalLookup {
    Found {
        symbol: SymbolId,
        imported: bool,
    },
    /// Two or more distinct, simultaneously-active bindings of the name in the
    /// nearest scope that binds it (e.g. a local and an explicit import, or two
    /// wildcard imports). The reference must be qualified.
    Ambiguous,
    NotFound,
}

/// One candidate binding gathered for a single scope during `lookup_name`.
struct LookupCandidate {
    /// Definition site (`token` source/line/column); generic instantiation
    /// clones one declaration into several `SymbolId`s, so candidates are
    /// deduplicated by this rather than by id.
    site: (TokenSource, u32, u32),
    /// Define context that gates this binding's activeness (the declaration's
    /// or the import statement's ifdef).
    define_context: DefineContext,
    depth: usize,
    id: SymbolId,
    imported: bool,
    /// Whether the symbol can hold `::member`, used to prefer a container over a
    /// same-named leaf when this candidate fills a non-final path segment.
    can_have_member: bool,
}

/// Resolves the candidates gathered within one scope (one precedence tier).
/// Ambiguous when two distinct definition sites could be active together;
/// otherwise picks the deepest binding (last wins ties) among generic clones
/// and ifdef variants. When `prefer_container` (a non-final path segment), a
/// container outranks a deeper same-named leaf.
fn resolve_tier(candidates: &[LookupCandidate], prefer_container: bool) -> LexicalLookup {
    let mut distinct: Vec<&LookupCandidate> = Vec::new();
    for candidate in candidates {
        if !distinct.iter().any(|x| x.site == candidate.site) {
            distinct.push(candidate);
        }
    }
    let ambiguous = distinct.iter().enumerate().any(|(i, ci)| {
        distinct
            .iter()
            .skip(i + 1)
            .any(|cj| !ci.define_context.exclusive(&cj.define_context))
    });
    if ambiguous {
        return LexicalLookup::Ambiguous;
    }

    let rank = |c: &LookupCandidate| (prefer_container && c.can_have_member, c.depth);
    let mut best = &candidates[0];
    for candidate in &candidates[1..] {
        if rank(candidate) >= rank(best) {
            best = candidate;
        }
    }
    LexicalLookup::Found {
        symbol: best.id,
        imported: best.imported,
    }
}

/// Everything one file's pass1 wrote into the symbol table, in a
/// serializable form. Part of the fragment cache payload.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SymbolTableFragment {
    pub symbols: Vec<Symbol>,
    pub imports: Vec<Import>,
    pub binds: Vec<Bind>,
    pub msbs: Vec<Msb>,
    pub connects: Vec<Connect>,
    pub reference_functions: Vec<(SymbolId, Vec<GenericSymbolPath>)>,
    pub references: Vec<(SymbolId, Vec<Token>)>,
}

#[derive(Clone, Default, Debug)]
pub struct SymbolTable {
    name_table: HashMap<StrId, Vec<SymbolId>>,
    symbol_table: HashMap<SymbolId, Rc<Symbol>>,
    namespace_index: HashMap<SVec<StrId>, Vec<SymbolId>>,
    project_local_table: HashMap<StrId, HashMap<StrId, StrId>>,
    import_list: Vec<Import>,
    bind_list: Vec<Bind>,
    msb_list: Vec<Msb>,
    connect_list: Vec<Connect>,
    reference_func_table: HashMap<SymbolId, Vec<GenericSymbolPath>>,
    reference_table: HashMap<SymbolId, Vec<Token>>,
    /// `$sv::` members whose insert lost the dedup to another file. Kept so
    /// every file's fragment can define the members it uses: the `$sv`
    /// namespace is shared, not owned by whichever file mentions one first.
    sv_shadows: Vec<Symbol>,
    suppress_cache_clear: bool,
    skip_generic_args: bool,
}

impl SymbolTable {
    pub fn new() -> Self {
        let mut ret = Self::default();

        // add builtin symbols to "" namespace
        let namespace = Namespace::new();

        for func in DEFINED_NAMESPACES {
            let token = Token::builtin_text(func);
            let symbol = Symbol::new(
                &token,
                SymbolKind::Namespace,
                &namespace,
                true,
                DocComment::default(),
            );
            let _ = ret.insert(&token, symbol);
        }

        sv_system_function::insert_symbols(&mut ret, &namespace);
        tb_component::insert_symbols(&mut ret, &namespace);

        ret
    }

    pub fn insert(&mut self, token: &Token, symbol: Symbol) -> Option<SymbolId> {
        let entry = self
            .name_table
            .entry(resource_table::canonical_str_id(token.text))
            .or_default();
        for id in entry.iter() {
            let item = self.symbol_table.get(id).unwrap();
            let symbol = &symbol.namespace;
            let item = &item.namespace;

            let same_namespace = symbol.paths == item.paths;
            let define_exclusive = symbol.define_context.exclusive(&item.define_context);

            let conflict = same_namespace && !define_exclusive;
            if conflict {
                return None;
            }
        }
        let id = symbol.id;
        let scope = symbol.scope;
        let ns_paths = symbol.namespace.paths.clone();
        entry.push(id);
        self.symbol_table.insert(id, Rc::new(symbol));
        self.namespace_index.entry(ns_paths).or_default().push(id);
        // Mirror the binding into the scope tree so lexical lookup sees every
        // inserted symbol regardless of which path created it.
        scope::add_local(scope, token.text, id);
        Some(id)
    }

    /// Registers a member synthesized for a `$sv::` reference; see `sv_shadows`.
    pub fn insert_sv_member(&mut self, token: &Token, symbol: Symbol) -> Option<SymbolId> {
        let ret = self.insert(token, symbol.clone());
        if ret.is_none() {
            self.sv_shadows.push(symbol);
        }
        ret
    }

    pub fn get(&self, id: SymbolId) -> Option<Symbol> {
        self.symbol_table.get(&id).map(|x| (**x).clone())
    }

    pub fn get_rc(&self, id: SymbolId) -> Option<Rc<Symbol>> {
        self.symbol_table.get(&id).cloned()
    }

    pub fn update(&mut self, symbol: Symbol) {
        let id = symbol.id;
        self.symbol_table.insert(id, Rc::new(symbol));
    }

    fn match_nested_generic_instance(&self, context: &ResolveContext, found: &Symbol) -> bool {
        if let Some(last_found) = context.last_found
            && let (SymbolKind::GenericInstance(_), SymbolKind::GenericInstance(_)) =
                (&last_found.kind, &found.kind)
        {
            let inner = scope::inner_scope(last_found.scope, last_found.token.text);
            return inner == found.scope
                && !last_found
                    .namespace
                    .define_context
                    .exclusive(&found.namespace.define_context);
        }
        false
    }

    fn trace_type_kind<'a>(
        &self,
        mut context: ResolveContext<'a>,
        kind: &TypeKind,
    ) -> Result<ResolveContext<'a>, ResolveError> {
        if let TypeKind::UserDefined(x) = kind {
            let mut path = x.path.clone();
            path.resolve_imported(context.scope, &context.define_context, None);
            path.unalias(None);
            let symbol = self.resolve(
                &path.generic_path(),
                &path.generic_arguments(),
                context.push(),
            )?;

            // cyclic-type guard: stop tracing if this type is already being
            // traced (a self- or mutually-referential type definition).
            let key = (symbol.found.id, ResolvePhase::TypeTrace);
            if context.visiting.contains(&key) {
                return Ok(context);
            }
            context.visiting.push(key);

            match &symbol.found.kind {
                SymbolKind::SystemVerilog => context.sv_member = true,
                // A user-defined component's interface is only known at
                // simulator load time; accept any member like a
                // SystemVerilog blackbox.
                SymbolKind::TbComponent(x) if matches!(x.kind, TbComponentKind::External(_)) => {
                    context.sv_member = true
                }
                SymbolKind::Parameter(x) if !x.is_proto => {
                    if matches!(x.r#type.kind, TypeKind::Type) {
                        let value = x.value.as_ref().unwrap();
                        return self.trace_type_parameter(context, value, &symbol.found);
                    }
                }
                SymbolKind::TypeDef(x) => {
                    if let Some(r#type) = &x.r#type {
                        context.set_namespace(
                            symbol.found.scope,
                            symbol.found.namespace.define_context.clone(),
                        );
                        return self.trace_type_kind(context, &r#type.kind);
                    }
                }
                SymbolKind::GenericParameter(x) => {
                    if matches!(x.bound, GenericBoundKind::Type) {
                        return self.trace_generic_parameter(context.clone(), &symbol.found);
                    }
                }
                _ => (),
            }
            context.set_inner(&symbol.found);
            context.last_found_type = Some(symbol.found.id);
            context.inner = true;
            context.generic_tables = symbol.generic_tables;
        } else {
            // assign a new empty namespace becuase
            // factor types and abstruct interface type have no members.
            context.set_namespace(scope::ScopeId::default(), DefineContext::default());
            context.inner = true;
        }
        Ok(context)
    }

    fn trace_type_path<'a>(
        &self,
        context: ResolveContext<'a>,
        path: &GenericSymbolPath,
    ) -> Result<ResolveContext<'a>, ResolveError> {
        let (mut context, found) = self.expand_alias(context, path)?;
        match &found.kind {
            SymbolKind::GenericInstance(_) => self.trace_generic_instance(context, &found),
            SymbolKind::GenericParameter(_) => self.trace_generic_parameter(context, &found),
            _ => {
                match &found.kind {
                    SymbolKind::SystemVerilog => context.sv_member = true,
                    // External component members are only known at simulator
                    // load time; accept any member like a SystemVerilog
                    // blackbox.
                    SymbolKind::TbComponent(x)
                        if matches!(x.kind, TbComponentKind::External(_)) =>
                    {
                        context.sv_member = true
                    }
                    _ => {}
                }
                context.set_inner(&found);
                context.last_found_type = Some(found.id);
                context.inner = true;
                Ok(context)
            }
        }
    }

    /// Follows an alias chain (`alias module`/`interface`/`package`) to its
    /// non-alias target, resolving each link in `context` and returning the
    /// terminal symbol. `context.visiting` breaks cyclic aliases used as a type.
    fn expand_alias<'a>(
        &self,
        mut context: ResolveContext<'a>,
        path: &GenericSymbolPath,
    ) -> Result<(ResolveContext<'a>, Rc<Symbol>), ResolveError> {
        let symbol = self.resolve(
            &path.generic_path(),
            &path.generic_arguments(),
            context.push(),
        )?;
        context.generic_tables = symbol.generic_tables.clone();

        // cyclic-alias guard (alias used as a type): report unresolvable if revisited.
        if matches!(
            symbol.found.kind,
            SymbolKind::AliasModule(_)
                | SymbolKind::AliasInterface(_)
                | SymbolKind::AliasPackage(_)
        ) {
            let key = (symbol.found.id, ResolvePhase::Alias);
            if context.visiting.contains(&key) {
                return Err(ResolveError::new(
                    Some(&symbol.found),
                    ResolveErrorCause::NotFound(symbol.found.token.text),
                ));
            }
            context.visiting.push(key);
        }

        match &symbol.found.kind {
            SymbolKind::AliasModule(x) => self.expand_alias(context, &x.target),
            SymbolKind::AliasInterface(x) => self.expand_alias(context, &x.target),
            SymbolKind::AliasPackage(x) => self.expand_alias(context, &x.target),
            _ => Ok((context, Rc::clone(&symbol.found))),
        }
    }

    fn trace_generic_instance<'a>(
        &self,
        mut context: ResolveContext<'a>,
        found: &Symbol,
    ) -> Result<ResolveContext<'a>, ResolveError> {
        if let SymbolKind::GenericInstance(x) = &found.kind {
            let base = self.symbol_table.get(&x.base).unwrap();

            // The scope-tree delegation built at instance creation must point
            // the instance's member scope at the same base member scope that
            // `set_inner(base)` below redirects to.
            #[cfg(debug_assertions)]
            {
                let inst_inner = scope::inner_scope(found.scope, found.token.text);
                let base_inner = scope::inner_scope(base.scope, base.token.text);
                debug_assert_eq!(
                    scope::generic_delegation(inst_inner),
                    Some(base_inner),
                    "generic instance delegation must match the base redirect"
                );
            }

            let prev_inst = context.inst_scope;
            context.set_inner(base);
            // Shadow cursor moves to the instance-side (mangled) scope instead of
            // the base, so the reconstructed namespace carries the mangled name.
            // For nested instances the mangled scope is rebased onto the outer
            // instance cursor; otherwise it is the registered instance scope.
            let base_inner = context.scope;
            context.inst_scope = if scope::generic_delegation(prev_inst) == Some(found.scope) {
                scope::register_generic_child(prev_inst, found.token.text, base_inner)
            } else {
                scope::inner_scope(found.scope, found.token.text)
            };
            context.last_found_type = Some(base.id);
            context.inner = true;
        }
        Ok(context)
    }

    fn trace_generic_parameter<'a>(
        &self,
        mut context: ResolveContext<'a>,
        found: &Symbol,
    ) -> Result<ResolveContext<'a>, ResolveError> {
        if let SymbolKind::GenericParameter(x) = &found.kind {
            if let Some(x) = self.resolve_generic_param_const(context.clone(), found) {
                return x;
            }

            let symbol = match &x.bound {
                GenericBoundKind::Type if x.default_value.is_some() => {
                    let path = x.default_value.as_ref().unwrap().generic_path();
                    let mut ctxt = ResolveContext::new(&found.namespace);
                    ctxt.depth = context.depth + 1;
                    &self.resolve(&path, &[], ctxt)?.found
                }
                GenericBoundKind::Inst(proto) => {
                    let mut ctxt = ResolveContext::new(&found.namespace);
                    ctxt.depth = context.depth + 1;
                    &self
                        .resolve(&proto.generic_path(), &proto.generic_arguments(), ctxt)?
                        .found
                }
                GenericBoundKind::Proto(proto) => {
                    if let Some(x) = proto.get_user_defined() {
                        let mut ctxt = ResolveContext::new(&found.namespace);
                        ctxt.depth = context.depth + 1;
                        &self.resolve(&x.path.generic_path(), &[], ctxt)?.found
                    } else {
                        found
                    }
                }
                _ => found,
            };

            context.set_inner(symbol);
            context.last_found_type = Some(symbol.id);
            context.inner = true;
        }
        Ok(context)
    }

    fn trace_generic_const<'a>(
        &self,
        mut context: ResolveContext<'a>,
        found: &Symbol,
    ) -> Result<ResolveContext<'a>, ResolveError> {
        if let SymbolKind::GenericConst(x) = &found.kind {
            if let Some(x) = self.resolve_generic_param_const(context.clone(), found) {
                return x;
            }

            let symbol = match &x.bound {
                GenericBoundKind::Type => {
                    if let Some(identifier) = x.value.unwrap_identifier() {
                        let path: GenericSymbolPath = identifier.into();
                        let mut ctxt = ResolveContext::new(&found.namespace);
                        ctxt.depth = context.depth + 1;
                        &self.resolve(&path.generic_path(), &[], ctxt)?.found
                    } else {
                        found
                    }
                }
                GenericBoundKind::Proto(proto) => {
                    if let Some(x) = proto.get_user_defined() {
                        let mut ctxt = ResolveContext::new(&found.namespace);
                        ctxt.depth = context.depth + 1;
                        &self.resolve(&x.path.generic_path(), &[], ctxt)?.found
                    } else {
                        found
                    }
                }
                _ => found,
            };

            context.set_inner(symbol);
            context.last_found_type = Some(symbol.id);
            context.inner = true;
        }
        Ok(context)
    }

    fn resolve_generic_param_const<'a>(
        &self,
        mut context: ResolveContext<'a>,
        found: &Symbol,
    ) -> Option<Result<ResolveContext<'a>, ResolveError>> {
        match &found.kind {
            SymbolKind::GenericParameter(_) | SymbolKind::GenericConst(_) => {
                if let Some(generic_table) = context
                    .generic_tables
                    .get(&(found.scope, found.namespace.define_context.clone()))
                    && let Some(path) = generic_table.get(&found.token.text)
                {
                    let result = self.resolve(
                        &path.generic_path(),
                        &path.generic_arguments(),
                        context.push(),
                    );
                    if let Ok(symbol) = result {
                        context.set_inner(&symbol.found);
                        context.last_found_type = Some(symbol.found.id);
                        context.inner = true;
                        return Some(Ok(context));
                    } else {
                        return result.err().map(Err);
                    }
                }
            }
            _ => {}
        }

        None
    }

    fn trace_type_parameter<'a>(
        &self,
        mut context: ResolveContext<'a>,
        expression: &Expression,
        found: &Symbol,
    ) -> Result<ResolveContext<'a>, ResolveError> {
        if let Some(identifier) = expression.unwrap_identifier() {
            let mut ctxt = ResolveContext::new(&found.namespace);
            ctxt.depth = context.depth + 1;

            let symbol = self.resolve(&identifier.into(), &[], ctxt)?;
            match &symbol.found.kind {
                SymbolKind::Parameter(x) if !x.is_proto => {
                    if matches!(x.r#type.kind, TypeKind::Type) {
                        let value = x.value.as_ref().unwrap();
                        return self.trace_type_parameter(context, value, &symbol.found);
                    }
                }
                SymbolKind::TypeDef(x) => {
                    if let Some(ref r#type) = x.r#type {
                        return self.trace_type_kind(context, &r#type.kind);
                    }
                }
                SymbolKind::GenericParameter(x) => {
                    if matches!(x.bound, GenericBoundKind::Type)
                        && let Some(x) =
                            self.resolve_generic_param_const(context.clone(), &symbol.found)
                    {
                        return x;
                    }
                }
                SymbolKind::GenericConst(x) => {
                    if matches!(x.bound, GenericBoundKind::Type)
                        && let Some(x) =
                            self.resolve_generic_param_const(context.clone(), &symbol.found)
                    {
                        return x;
                    }
                }
                _ => {}
            }

            context.set_inner(&symbol.found);
            context.last_found_type = Some(symbol.found.id);
            context.inner = true;
            context.generic_tables = symbol.generic_tables;
        }

        Ok(context)
    }

    /// Advances the cursor from a non-final path segment `found` to the scope
    /// holding the members the next segment resolves against. Dispatches on the
    /// symbol kind: typed members trace to their type's definition, aliases
    /// follow their target, generics instantiate, and containers descend into
    /// their inner scope.
    fn navigate_member<'a>(
        &self,
        mut context: ResolveContext<'a>,
        found: &Rc<Symbol>,
    ) -> Result<ResolveContext<'a>, ResolveError> {
        match &found.kind {
            SymbolKind::Variable(x) => {
                context = self.trace_type_kind(context, &x.r#type.kind)?;
            }
            SymbolKind::StructMember(x) => {
                context = self.trace_type_kind(context, &x.r#type.kind)?;
            }
            SymbolKind::UnionMember(x) => {
                context = self.trace_type_kind(context, &x.r#type.kind)?;
            }
            SymbolKind::Parameter(x) if x.is_proto => {
                context = self.trace_type_kind(context, &x.r#type.kind)?;
            }
            SymbolKind::Parameter(x) => {
                if matches!(x.r#type.kind, TypeKind::Type) {
                    let value = x.value.as_ref().unwrap();
                    context = self.trace_type_parameter(context, value, found)?;
                } else {
                    context = self.trace_type_kind(context, &x.r#type.kind)?;
                }
            }
            SymbolKind::TypeDef(x) => {
                if let Some(ref r#type) = x.r#type {
                    context = self.trace_type_kind(context, &r#type.kind)?;
                }
            }
            SymbolKind::Port(x) => {
                context = self.trace_type_kind(context, &x.r#type.kind)?;
            }
            SymbolKind::ModportVariableMember(_) => {
                let path = SymbolPath::new(&[found.token.text]);
                context.set_namespace(
                    scope::parent(found.scope).unwrap_or_default(),
                    found.namespace.define_context.clone(),
                );
                let symbol = self.resolve(&path, &[], context.push())?;
                if let SymbolKind::Variable(x) = &symbol.found.kind {
                    context = self.trace_type_kind(context, &x.r#type.kind)?;
                }
            }
            // proto module has no inner item to trace
            SymbolKind::Module(x) if x.is_proto => (),
            SymbolKind::Module(_) | SymbolKind::Interface(_) | SymbolKind::Package(_) => {
                context.set_inner(found);
                context.inner = true;
            }
            SymbolKind::AliasModule(x) => {
                context = self.trace_type_path(context, &x.target)?;
            }
            SymbolKind::AliasInterface(x) => {
                context = self.trace_type_path(context, &x.target)?;
            }
            SymbolKind::AliasPackage(x) => {
                context = self.trace_type_path(context, &x.target)?;
            }
            SymbolKind::Enum(_) | SymbolKind::Namespace | SymbolKind::PropNamespace => {
                context.set_inner(found);
                context.inner = true;
            }
            SymbolKind::TbComponent(x) => {
                context.set_inner(found);
                context.inner = true;
                // External components have no method symbols (the interface
                // is known only at simulator load time); accept any member
                // like a SystemVerilog blackbox.
                if matches!(x.kind, TbComponentKind::External(_)) {
                    context.sv_member = true;
                }
            }
            SymbolKind::SystemVerilog => {
                context.set_inner(found);
                context.inner = true;
                context.sv_member = true;
            }
            SymbolKind::Instance(x) => {
                let mut type_name = x.type_name.clone();
                type_name.resolve_imported(context.scope, &context.define_context, None);
                type_name.unalias(None);
                context = self.trace_type_path(context, &type_name)?;
            }
            SymbolKind::GenericInstance(_) => {
                context = self.trace_generic_instance(context, found)?;
            }
            SymbolKind::GenericParameter(_) => {
                context = self.trace_generic_parameter(context, found)?;
            }
            SymbolKind::GenericConst(_) => {
                context = self.trace_generic_const(context, found)?;
            }
            // don't trace inner item
            SymbolKind::Function(_)
            | SymbolKind::Struct(_)
            | SymbolKind::Union(_)
            | SymbolKind::Modport(_)
            | SymbolKind::ModportFunctionMember(_)
            | SymbolKind::EnumMember(_)
            | SymbolKind::EnumMemberMangled
            | SymbolKind::Block
            | SymbolKind::SystemFunction(_)
            | SymbolKind::Genvar
            | SymbolKind::ClockDomain
            | SymbolKind::Test(_)
            | SymbolKind::Embed
            | SymbolKind::ProjectProperty(_) => (),
        }
        Ok(context)
    }

    /// Checks that `found` is reachable from the current cursor: public across a
    /// project boundary (`is_public`) and visible through the container just
    /// navigated (`is_visible`).
    fn check_access(&self, context: &ResolveContext, found: &Symbol) -> Result<(), ResolveError> {
        if !self.is_public(context, found) {
            Err(ResolveError::new(context.found, ResolveErrorCause::Private))
        } else if !self.is_visible(context, found) {
            Err(ResolveError::new(
                context.found,
                ResolveErrorCause::Invisible,
            ))
        } else {
            Ok(())
        }
    }

    fn is_public(&self, context: &ResolveContext, found: &Symbol) -> bool {
        match found.kind {
            SymbolKind::Module(_)
            | SymbolKind::AliasModule(_)
            | SymbolKind::Interface(_)
            | SymbolKind::AliasInterface(_)
            | SymbolKind::Package(_)
            | SymbolKind::AliasPackage(_) => !context.other_prj || found.public,
            SymbolKind::Namespace => !context.root_prj || found.public,
            _ => true,
        }
    }

    fn is_visible(&self, context: &ResolveContext, found: &Symbol) -> bool {
        if context.last_found.is_none() || matches!(found.kind, SymbolKind::SystemVerilog) {
            return true;
        }

        let last_found = context.last_found.unwrap();
        let last_found_type = context.last_found_type.map(|x| {
            let symbol = self.symbol_table.get(&x).unwrap();
            symbol.kind.clone()
        });
        let via_modport = match &last_found.kind {
            SymbolKind::Port(x) => matches!(x.direction, Direction::Modport | Direction::Interface),
            _ => false,
        };
        let via_interface_instance = match &last_found.kind {
            SymbolKind::Instance(_) => matches!(
                last_found_type,
                Some(SymbolKind::Interface(_)) | Some(SymbolKind::AliasInterface(_))
            ),
            SymbolKind::GenericParameter(x) => {
                matches!(&x.bound, GenericBoundKind::Inst(_))
                    && matches!(last_found_type, Some(SymbolKind::Interface(_)))
            }
            _ => false,
        };
        let via_interface = match &last_found.kind {
            SymbolKind::Interface(_) | SymbolKind::AliasInterface(_) => true,
            SymbolKind::GenericInstance(_) => {
                matches!(last_found_type, Some(SymbolKind::Interface(ref x)) if !x.is_proto)
            }
            SymbolKind::GenericParameter(x) => {
                matches!(&x.bound, GenericBoundKind::Proto(_))
                    && matches!(last_found_type, Some(SymbolKind::Interface(ref x)) if x.is_proto)
            }
            _ => false,
        };
        let via_pacakge = match &last_found.kind {
            SymbolKind::Package(_) | SymbolKind::AliasPackage(_) => true,
            SymbolKind::GenericInstance(_) => {
                matches!(last_found_type, Some(SymbolKind::Package(_)))
            }
            SymbolKind::GenericParameter(_) => {
                matches!(last_found_type, Some(SymbolKind::Package(_)))
            }
            _ => false,
        };
        let via_enum = match &last_found.kind {
            SymbolKind::Enum(_) => true,
            SymbolKind::TypeDef(x) => {
                x.r#type.is_some() && matches!(last_found_type, Some(SymbolKind::Enum(_)))
            }
            _ => false,
        };
        let via_namespace = matches!(last_found.kind, SymbolKind::Namespace);
        let via_prop_namespace = matches!(last_found.kind, SymbolKind::PropNamespace);
        let via_tb_component = matches!(last_found_type, Some(SymbolKind::TbComponent(_)));

        match &found.kind {
            SymbolKind::Variable(_)
            | SymbolKind::ModportFunctionMember(_)
            | SymbolKind::ModportVariableMember(_) => via_modport || via_interface_instance,
            SymbolKind::StructMember(_) | SymbolKind::UnionMember(_) => matches!(
                last_found.kind,
                SymbolKind::Port(_)
                    | SymbolKind::ModportVariableMember(_)
                    | SymbolKind::Variable(_)
                    | SymbolKind::Parameter(_)
                    | SymbolKind::StructMember(_)
                    | SymbolKind::UnionMember(_)
                    | SymbolKind::GenericParameter(_)
            ),
            SymbolKind::Parameter(_)
            | SymbolKind::TypeDef(_)
            | SymbolKind::Enum(_)
            | SymbolKind::Struct(_)
            | SymbolKind::Union(_)
            | SymbolKind::AliasModule(_)
            | SymbolKind::AliasInterface(_)
            | SymbolKind::AliasPackage(_) => via_pacakge,
            SymbolKind::Function(x) if x.is_proto => via_pacakge,
            SymbolKind::Function(x) => {
                via_modport
                    || via_interface_instance
                    || via_pacakge
                    || via_tb_component
                    || via_namespace && x.is_global()
            }
            SymbolKind::EnumMember(_) | SymbolKind::EnumMemberMangled => via_enum,
            SymbolKind::Modport(_) => via_interface || via_interface_instance,
            SymbolKind::GenericInstance(_) => {
                // A generic instance in this context is for generic type or function
                // defined in a packge or for generic component defined in other project
                via_pacakge || via_namespace
            }
            SymbolKind::ProjectProperty(_) => via_prop_namespace,
            SymbolKind::PropNamespace => !via_namespace,
            _ => via_namespace,
        }
    }

    /// Member lookup (`a.b`): among the symbols sharing the segment's name,
    /// picks the one declared directly in the cursor scope — or a matching
    /// nested generic instance — with the deepest namespace winning. Unlike
    /// `lookup_name` it does not walk parent scopes.
    fn lookup_member<'a>(
        &'a self,
        context: &ResolveContext,
        name: StrId,
    ) -> Option<&'a Rc<Symbol>> {
        // For nested generic instances the member lives in the base instance's
        // inner scope, so include those locals too.
        let mut candidates = scope::locals_get(context.scope, name);
        if let Some(last_found) = context.last_found
            && matches!(last_found.kind, SymbolKind::GenericInstance(_))
        {
            let inner = scope::inner_scope(last_found.scope, last_found.token.text);
            candidates.extend(scope::locals_get(inner, name));
        }

        let mut max_depth = 0;
        let mut found = None;
        for id in candidates {
            let Some(symbol) = self.symbol_table.get(&id) else {
                continue;
            };
            let matched = self.match_nested_generic_instance(context, symbol)
                || (context.scope == symbol.scope
                    && !context
                        .define_context
                        .exclusive(&symbol.namespace.define_context));
            if matched && symbol.namespace.depth() >= max_depth {
                found = Some(symbol);
                max_depth = symbol.namespace.depth();
            }
        }

        if found.is_some() {
            return found;
        }

        for mixin in scope::mixin_get(context.scope) {
            if context.define_context.exclusive(&mixin.define_context) {
                continue;
            }
            for id in scope::locals_get(mixin.source, name) {
                let Some(symbol) = self.symbol_table.get(&id) else {
                    continue;
                };
                if !symbol
                    .namespace
                    .define_context
                    .exclusive(&mixin.source_define_context)
                {
                    return Some(symbol);
                }
            }
        }

        None
    }

    /// Lexical name lookup over the scope tree: walk from `scope` up the parent
    /// chain and resolve `name` in the nearest scope that binds it. Within a
    /// scope, explicit bindings (local declarations and explicit imports) take
    /// precedence over wildcard imports, matching SystemVerilog import rules; a
    /// binding in an inner scope shadows everything above it. Candidates whose
    /// define context is mutually exclusive with the query are not visible.
    fn lookup_name(
        &self,
        scope: scope::ScopeId,
        name: StrId,
        query_dctx: &DefineContext,
        prefer_container: bool,
    ) -> LexicalLookup {
        let candidate = |id: SymbolId, symbol: &Symbol, define_context, imported| LookupCandidate {
            site: (symbol.token.source, symbol.token.line, symbol.token.column),
            define_context,
            depth: symbol.namespace.depth(),
            id,
            imported,
            can_have_member: symbol.kind.can_have_path_member(),
        };

        // A non-final segment prefers a container: a nearer same-named leaf is
        // kept only as a fallback while the walk continues outward for a
        // container (the first one found is the deepest).
        let mut fallback: Option<LexicalLookup> = None;
        let mut current = Some(scope);
        while let Some(scope) = current {
            // A generic-instance scope holds no members of its own: resolve names
            // in the base template it delegates to, and continue up the base's
            // parent chain. For non-instance scopes this is the scope itself.
            let scope = scope::generic_delegation(scope).unwrap_or(scope);

            // Tier 1: explicit bindings — local declarations and explicit imports.
            let mut tier = Vec::new();
            for id in scope::locals_get(scope, name) {
                if let Some(symbol) = self.symbol_table.get(&id)
                    && !query_dctx.exclusive(&symbol.namespace.define_context)
                {
                    let dctx = symbol.namespace.define_context.clone();
                    tier.push(candidate(id, symbol, dctx, false));
                }
            }
            for binding in scope::imports_get(scope, name) {
                if !query_dctx.exclusive(&binding.define_context)
                    && let Some(symbol) = self.symbol_table.get(&binding.symbol)
                {
                    tier.push(candidate(
                        binding.symbol,
                        symbol,
                        binding.define_context,
                        true,
                    ));
                }
            }
            if !tier.is_empty()
                && let Some(result) = self.container_or_stash(
                    resolve_tier(&tier, prefer_container),
                    prefer_container,
                    &mut fallback,
                )
            {
                return result;
            }

            // Tier 2: wildcard imports, only when no explicit binding shadows them.
            let mut tier = Vec::new();
            for wildcard in scope::wildcards_get(scope) {
                if query_dctx.exclusive(&wildcard.define_context) {
                    continue;
                }
                for id in scope::locals_get(wildcard.source, name) {
                    if let Some(symbol) = self.symbol_table.get(&id)
                        && !symbol
                            .namespace
                            .define_context
                            .exclusive(&wildcard.source_define_context)
                    {
                        let dctx = symbol.namespace.define_context.clone();
                        tier.push(candidate(id, symbol, dctx, true));
                    }
                }
            }
            if !tier.is_empty()
                && let Some(result) = self.container_or_stash(
                    resolve_tier(&tier, prefer_container),
                    prefer_container,
                    &mut fallback,
                )
            {
                return result;
            }

            // Tier 3: Mixin
            let mut tier = Vec::new();
            for mixin in scope::mixin_get(scope) {
                if query_dctx.exclusive(&mixin.define_context) {
                    continue;
                }
                for id in scope::locals_get(mixin.source, name) {
                    if let Some(symbol) = self.symbol_table.get(&id)
                        && !symbol
                            .namespace
                            .define_context
                            .exclusive(&mixin.source_define_context)
                    {
                        let dctx = symbol.namespace.define_context.clone();
                        tier.push(candidate(id, symbol, dctx, true));
                    }
                }
            }
            if !tier.is_empty()
                && let Some(result) = self.container_or_stash(
                    resolve_tier(&tier, prefer_container),
                    prefer_container,
                    &mut fallback,
                )
            {
                return result;
            }

            current = scope::parent(scope);
        }
        fallback.unwrap_or(LexicalLookup::NotFound)
    }

    /// For a non-final path segment (`prefer_container`), a same-named leaf that
    /// is nearer than a container must not shadow it: such a leaf is stashed as
    /// the fallback (the first/nearest one) and the caller keeps walking outward.
    /// A container result, or any result for a final segment, is returned as-is.
    fn container_or_stash(
        &self,
        result: LexicalLookup,
        prefer_container: bool,
        fallback: &mut Option<LexicalLookup>,
    ) -> Option<LexicalLookup> {
        if prefer_container
            && let LexicalLookup::Found { symbol, .. } = &result
            && !self
                .symbol_table
                .get(symbol)
                .is_some_and(|s| s.kind.can_have_path_member())
        {
            if fallback.is_none() {
                *fallback = Some(result);
            }
            return None;
        }
        Some(result)
    }

    /// Registers the generic instantiation for `found` built from this segment's
    /// generic arguments, after normalizing them into the base component's
    /// namespace.
    fn instantiate_generic(
        &self,
        context: &mut ResolveContext,
        found: &Symbol,
        mut arguments: Vec<GenericSymbolPath>,
        namespace_generic_map: &NamespaceGenericMap,
        entry_scope: scope::ScopeId,
        entry_define_context: &DefineContext,
    ) {
        for arg in &mut arguments {
            // Generic arguments will be resolved in the namespace of base component.
            // Therefore, generic parameters given as generic arguments should be replaced
            // with their types.
            // See: https://github.com/veryl-lang/veryl/issues/1714#issuecomment-2967149726
            if let Some(map) = namespace_generic_map {
                arg.apply_map(map.as_slice());
            }

            // Path to generic arg should have its project prefix to make it visible from
            // the namespace of base component. An empty query namespace carries no project
            // to prepend, so there is nothing to append.
            // The comparison uses the base component's declaration scope rather than
            // the resolution cursor: a head reached through an import binding (or
            // its synthetic token scope) leaves the cursor in the importing project,
            // which would suppress the prefix and leave the argument unresolvable
            // from the base component's namespace.
            if let Some(prj) = scope::project_of(entry_scope)
                && Some(prj) != scope::project_of(found.scope)
            {
                self.append_project_path(arg, entry_scope, entry_define_context);
            }
        }

        context.generic_tables.insert(
            (
                scope::inner_scope(found.scope, found.token.text),
                found.namespace.define_context.clone(),
            ),
            found.generic_table(&arguments),
        );
    }

    /// Re-homes `found` to the namespace of the delegation it was reached
    /// through: a generic instance's mangled namespace, or the interface a mixin
    /// was mixed into. Members reached from elsewhere keep their own namespace.
    fn reconstruct_found_namespace(
        found: &Rc<Symbol>,
        inst_scope: scope::ScopeId,
        current_scope: scope::ScopeId,
        define_context: &DefineContext,
    ) -> Rc<Symbol> {
        let mixin_target = scope::get_mixin_target_scope(current_scope, found.scope);
        let via_generic_instance = if mixin_target.is_some() {
            scope::generic_delegation(inst_scope) == mixin_target
        } else {
            scope::generic_delegation(inst_scope) == Some(found.scope)
        };

        if via_generic_instance {
            // A member reached through a generic instance (a direct member, or one
            // mixed into it) takes the instance's mangled namespace.
            let mut found = (**found).clone();
            found.namespace = scope::namespace(inst_scope, define_context);
            Rc::new(found)
        } else if let Some(scope) = mixin_target {
            // A member mixed into a non-generic interface takes the mixed-into
            // interface's namespace.
            let mut found = (**found).clone();
            found.namespace = scope::namespace(scope, define_context);
            Rc::new(found)
        } else {
            // Members reached from elsewhere (aliases, imports, the instance's
            // own base) keep their own (table-owned) namespace.
            Rc::clone(found)
        }
    }

    fn resolve<'a>(
        &'a self,
        path: &SymbolPath,
        generic_arguments: &[Vec<GenericSymbolPath>],
        mut context: ResolveContext<'a>,
    ) -> Result<ResolveResult, ResolveError> {
        let entry_scope = context.scope;
        let entry_define_context = context.define_context.clone();
        let mut path = path.clone();

        // Replace project-local names. An empty namespace carries no project
        // context (e.g. resolving a numeric or builtin-type generic argument),
        // so there is no project-local aliasing to apply.
        if let Some(prj) = scope::project_of(entry_scope) {
            let path_head = path.0[0];
            if let Some(map) = self.project_local_table.get(&prj) {
                context.root_prj = false;
                if let Some(id) = map.get(&path_head) {
                    path.0[0] = *id;
                }
            }
        }

        trace!("symbol_table: {}resolve   '{}'", context.indent(), path);

        let namespace_generic_map = if self.skip_generic_args {
            None
        } else {
            self.get_namespace_generic_map(entry_scope, &context.define_context)
        };
        // Recursion entries pushed while navigating one segment's type must not
        // leak into the next segment: each segment's traversal starts from this
        // base (the outer call-path carried in via `push`).
        let visiting_base = context.visiting.len();
        for (i, name) in path.as_slice().iter().enumerate() {
            // For a non-final path segment, prefer a container (a kind that can
            // hold `::member`) over a same-named leaf, so an item imported under
            // its package's name cannot shadow the package as a prefix.
            let prefer_container = (i + 1) != path.len();
            context.found = None;

            let generic_argument = if self.skip_generic_args {
                None
            } else {
                generic_arguments.get(i).cloned()
            };

            if context.sv_member {
                let token = Token::new(&name.to_string(), 0, 0, 0, 0, TokenSource::External);
                let symbol = Symbol::new(
                    &token,
                    SymbolKind::SystemVerilog,
                    &context.namespace(),
                    false,
                    DocComment::default(),
                );
                return Ok(ResolveResult {
                    found: std::rc::Rc::new(symbol),
                    full_path: context.full_path,
                    imported: context.imported,
                    generic_tables: context.generic_tables,
                });
            }

            if self
                .name_table
                .contains_key(&resource_table::canonical_str_id(*name))
            {
                if context.inner {
                    if let Some(symbol) = self.lookup_member(&context, *name) {
                        context.found = Some(symbol);
                        context.imported = false;
                    }
                } else {
                    match self.lookup_name(
                        context.scope,
                        *name,
                        &context.define_context,
                        prefer_container,
                    ) {
                        LexicalLookup::Found { symbol, imported } => {
                            context.found = self.symbol_table.get(&symbol);
                            context.imported = imported;
                        }
                        LexicalLookup::Ambiguous => {
                            trace!("symbol_table: {}ambiguous '{}'", context.indent(), path);
                            return Err(ResolveError::new(
                                None,
                                ResolveErrorCause::Ambiguous(*name),
                            ));
                        }
                        LexicalLookup::NotFound => {}
                    }
                }

                if let Some(found) = context.found {
                    self.check_access(&context, found).map_err(|err| {
                        let kind = if matches!(err.cause, ResolveErrorCause::Private) {
                            "private"
                        } else {
                            "invisible"
                        };
                        trace!("symbol_table: {}{} '{}'", context.indent(), kind, path);
                        err
                    })?;

                    if let Some(arguments) = generic_argument {
                        self.instantiate_generic(
                            &mut context,
                            found,
                            arguments,
                            &namespace_generic_map,
                            entry_scope,
                            &entry_define_context,
                        );
                    }

                    context.last_found = context.found;
                    context.full_path.push(found.id);

                    trace!(
                        "symbol_table: {}- path    '{}' : {} @ {}",
                        context.indent(),
                        name,
                        found.kind,
                        context.namespace(),
                    );

                    if (i + 1) < path.len() {
                        context = self.navigate_member(context, found)?;
                        context.visiting.truncate(visiting_base);
                    }
                } else {
                    trace!(
                        "symbol_table: {}not found '{}' @ {}",
                        context.indent(),
                        path,
                        context.namespace()
                    );

                    return Err(ResolveError::new(
                        context.last_found,
                        ResolveErrorCause::NotFound(*name),
                    ));
                }
            } else {
                // If symbol is not found, the name is treated as namespace
                context.set_namespace(
                    scope::inner_scope(scope::ScopeId::default(), *name),
                    DefineContext::default(),
                );
                context.inner = true;
                context.other_prj = true;
            }
        }
        if let Some(found) = context.found {
            let found = Self::reconstruct_found_namespace(
                found,
                context.inst_scope,
                context.scope,
                &context.define_context,
            );

            trace!(
                "symbol_table: {}found     '{}' : {}",
                context.indent(),
                path,
                found.kind
            );

            Ok(ResolveResult {
                found,
                full_path: context.full_path,
                imported: context.imported,
                generic_tables: context.generic_tables,
            })
        } else {
            trace!("symbol_table: {}not found '{}'", context.indent(), path);

            let cause = ResolveErrorCause::NotFound(
                scope::name_path(context.scope).last().copied().unwrap(),
            );
            Err(ResolveError::new(context.last_found, cause))
        }
    }

    /// Structural counterpart of [`Self::resolve`] for a fully-formed generic
    /// instance path. Walks the segments reusing the same member-lookup and
    /// navigation machinery, but resolves a generic segment by looking up its
    /// *un-mangled* base template and navigating to the instance through the
    /// structural index — never constructing a mangled name. Returns a
    /// [`ResolveResult`] carrying the fields generic-instance callers consume;
    /// `generic_tables` is empty, matching the mangled resolution of an instance
    /// path (which passes no generic arguments, so it instantiates none). Returns
    /// `None` for cases this walk does not model (synthesized SystemVerilog
    /// members, pre-mangled degenerate paths), where the caller falls back to the
    /// mangled resolution.
    fn resolve_generic_structural<'a>(
        &'a self,
        path: &GenericSymbolPath,
        scope: scope::ScopeId,
        define_context: DefineContext,
    ) -> Option<ResolveResult> {
        let mut context = ResolveContext::from_scope(scope, define_context);
        let visiting_base = context.visiting.len();
        let segments = &path.paths;
        for (i, segment) in segments.iter().enumerate() {
            context.found = None;
            let prefer_container = (i + 1) != segments.len();

            let mut name = segment.base();
            if i == 0
                && let Some(prj) = scope::project_of(scope)
                && let Some(map) = self.project_local_table.get(&prj)
            {
                context.root_prj = false;
                if let Some(id) = map.get(&name) {
                    name = *id;
                }
            }

            // Synthesized SystemVerilog members carry a freshly allocated id each
            // time they are built, so they are neither structurally indexed nor
            // id-comparable. Defer such paths to the mangled-name fallback.
            if context.sv_member {
                return None;
            }

            if !self
                .name_table
                .contains_key(&resource_table::canonical_str_id(name))
            {
                context.set_namespace(
                    scope::inner_scope(scope::ScopeId::default(), name),
                    DefineContext::default(),
                );
                context.inner = true;
                context.other_prj = true;
                continue;
            }

            // Look up the (un-mangled) base name with the same lexical/member rules.
            let base: &'a Rc<Symbol> = if context.inner {
                let member = self.lookup_member(&context, name)?;
                context.imported = false;
                member
            } else {
                match self.lookup_name(
                    context.scope,
                    name,
                    &context.define_context,
                    prefer_container,
                ) {
                    LexicalLookup::Found { symbol, imported } => {
                        context.imported = imported;
                        self.symbol_table.get(&symbol)?
                    }
                    LexicalLookup::Ambiguous | LexicalLookup::NotFound => return None,
                }
            };
            self.check_access(&context, base).ok()?;

            // A segment whose arguments do not mangle to a distinct name (none, or
            // unresolved generic parameters) carries no instantiation — the mangled
            // walk resolves its base, so the structural walk does too. A testbench
            // component also resolves to its base: its generic arguments are
            // instance parameters validated against the interface manifest, not a
            // monomorphization. Otherwise navigate to the instance through the
            // structural index keyed by (enclosing scope, base template,
            // arguments), the identity the mangled name encodes.
            let found: &'a Rc<Symbol> = if segment.mangled() == segment.base()
                || matches!(base.kind, SymbolKind::TbComponent(_))
            {
                base
            } else {
                // When the base template is reached through a generic-instance
                // delegation (a nested instance, e.g. `Pkg::<1>::Struct::<2>`), the
                // enclosing scope keying the index is the parent instance's rebased
                // scope (the instance-side cursor), not the template's declaration
                // scope — mirroring the namespace rebasing applied to the final
                // found. Otherwise it is the base template's own enclosing scope.
                let enclosing = if scope::generic_delegation(context.inst_scope) == Some(base.scope)
                {
                    context.inst_scope
                } else {
                    scope::intern_namespace(&base.namespace)
                };
                let key = generic_instance_key(enclosing, base.id, &segment.arguments);
                let inst = GENERIC_INSTANCE_INDEX.with(|f| f.borrow().get(&key).copied())?;
                self.symbol_table.get(&inst)?
            };

            context.found = Some(found);
            context.last_found = context.found;
            context.full_path.push(found.id);

            if (i + 1) < segments.len() {
                context = self.navigate_member(context, found).ok()?;
                context.visiting.truncate(visiting_base);
            }
        }

        let found = context.found?;
        let found = Self::reconstruct_found_namespace(
            found,
            context.inst_scope,
            context.scope,
            &context.define_context,
        );
        Some(ResolveResult {
            found,
            full_path: context.full_path,
            imported: context.imported,
            generic_tables: context.generic_tables,
        })
    }

    fn get_namespace_generic_map(
        &self,
        scope: scope::ScopeId,
        define_context: &DefineContext,
    ) -> Option<Rc<Vec<GenericMap>>> {
        if scope::depth(scope) <= 1 {
            return None;
        }
        let key = (scope, define_context.clone());
        if let Some(cached) = NS_GENERIC_MAP_CACHE.with(|f| f.borrow().get(&key).cloned()) {
            return cached;
        }
        let namespace = scope::namespace(scope, define_context);
        let ret = self
            .get_namespace_generic_map_inner(&namespace)
            .map(Rc::new);
        NS_GENERIC_MAP_CACHE.with(|f| f.borrow_mut().insert(key, ret.clone()));
        ret
    }

    fn get_namespace_generic_map_inner(&self, namespace: &Namespace) -> Option<Vec<GenericMap>> {
        let mut namespace = namespace.clone();
        namespace.strip_anonymous_path();

        let path = namespace.pop().map(|x| SymbolPath::new(&[x]))?;
        let context = ResolveContext::new(&namespace);
        let param_list = self
            .resolve(&path, &[], context)
            .map(|x| self.collect_generic_bounds(&x.found))
            .ok()?;

        if param_list.is_empty() {
            return None;
        }

        let mut maps = Vec::new();
        for params in param_list {
            let mut map = GenericTable::default();
            for (key, bound) in params {
                if let GenericBoundKind::Proto(x) = bound {
                    let TypeKind::UserDefined(x) = x.kind else {
                        continue;
                    };
                    map.insert(key, x.path);
                }
            }

            maps.push(GenericMap { id: None, map });
        }

        Some(maps)
    }

    fn collect_generic_bounds(&self, symbol: &Symbol) -> Vec<Vec<(StrId, GenericBoundKind)>> {
        fn collect_generic_params(
            symbol_table: &SymbolTable,
            generic_params: &[SymbolId],
        ) -> Vec<(StrId, GenericBoundKind)> {
            generic_params
                .iter()
                .map(|param| {
                    let symbol = symbol_table.get(*param).unwrap();
                    let SymbolKind::GenericParameter(x) = symbol.kind else {
                        unreachable!();
                    };
                    (symbol.token.text, x.bound)
                })
                .collect()
        }

        // Namespace::get_symbol (used in Symbol::get_parent) uses symbol_table::resolve.
        // This causes 'RefCell already mutably borrowed' error.
        // The function below is to prevent this error.
        fn get_parent_symbol(symbol_table: &SymbolTable, symbol: &Symbol) -> Option<Symbol> {
            let mut namespace = symbol.namespace.clone();
            namespace.strip_anonymous_path();

            if let Some(path) = namespace.pop()
                && namespace.depth() >= 1
            {
                let context = ResolveContext::new(&namespace);
                let symbol_path = SymbolPath::new(&[path]);
                symbol_table
                    .resolve(&symbol_path, &[], context)
                    .map(|x| (*x.found).clone())
                    .ok()
            } else {
                None
            }
        }

        match &symbol.kind {
            SymbolKind::Module(x) => vec![collect_generic_params(self, &x.generic_parameters)],
            SymbolKind::Interface(x) => vec![collect_generic_params(self, &x.generic_parameters)],
            SymbolKind::Package(x) if !x.is_proto => {
                vec![collect_generic_params(self, &x.generic_parameters)]
            }
            SymbolKind::GenericInstance(x) => {
                let symbol = self.get(x.base).unwrap();
                self.collect_generic_bounds(&symbol)
            }
            SymbolKind::Function(x) if !x.is_proto => {
                let mut bounds = if let Some(parent) = get_parent_symbol(self, symbol) {
                    self.collect_generic_bounds(&parent)
                } else {
                    vec![]
                };
                bounds.push(collect_generic_params(self, &x.generic_parameters));
                bounds
            }
            SymbolKind::Struct(x) => {
                let mut bounds = if let Some(parent) = get_parent_symbol(self, symbol) {
                    self.collect_generic_bounds(&parent)
                } else {
                    vec![]
                };
                bounds.push(collect_generic_params(self, &x.generic_parameters));
                bounds
            }
            SymbolKind::Union(x) => {
                let mut bounds = if let Some(parent) = get_parent_symbol(self, symbol) {
                    self.collect_generic_bounds(&parent)
                } else {
                    vec![]
                };
                bounds.push(collect_generic_params(self, &x.generic_parameters));
                bounds
            }
            SymbolKind::Block => {
                if let Some(parent) = get_parent_symbol(self, symbol) {
                    self.collect_generic_bounds(&parent)
                } else {
                    vec![]
                }
            }
            _ => vec![],
        }
    }

    fn append_project_path(
        &self,
        path: &mut GenericSymbolPath,
        scope: scope::ScopeId,
        define_context: &DefineContext,
    ) {
        let namespace = scope::namespace(scope, define_context);
        let context = ResolveContext::new(&namespace);
        let Ok(symbol) = self.resolve(&path.base_path(0), &[], context) else {
            return;
        };
        if !matches!(
            symbol.found.kind,
            SymbolKind::Module(_)
                | SymbolKind::AliasModule(_)
                | SymbolKind::Interface(_)
                | SymbolKind::AliasInterface(_)
                | SymbolKind::Package(_)
                | SymbolKind::AliasPackage(_)
        ) {
            return;
        }

        // A head reached through an import binding is declared in the exporting
        // project, not in the one the path is written in.
        if let Some(prj) = scope::project_of(symbol.found.scope)
            && let Some(project_symbol) = self.find_project_symbol(prj)
        {
            let project_path = GenericSymbol {
                base: project_symbol.token,
                arguments: vec![],
            };
            path.paths.insert(0, project_path);
        }
    }

    pub fn get_all(&self) -> Vec<Symbol> {
        let mut ret = Vec::new();
        for symbol in self.symbol_table.values() {
            ret.push((**symbol).clone());
        }
        ret
    }

    pub fn dump(&self) -> String {
        format!("{self}")
    }

    pub fn drop(&mut self, file_path: PathId, prj: Option<StrId>) {
        fn is_drop_symbol(symbol: &Symbol, file_path: PathId, prj: Option<StrId>) -> bool {
            if symbol.token.source != file_path {
                return false;
            }

            if let Some(prj) = prj {
                symbol
                    .namespace
                    .paths
                    .first()
                    .is_some_and(|x| resource_table::canonical_str_id(*x) == prj)
            } else {
                true
            }
        }

        fn is_drop_token(token: &Token, file_path: PathId, prj: Option<StrId>) -> bool {
            token.source == file_path && (prj.is_none() || scope::token_project(token.id) == prj)
        }

        let prj = prj.map(resource_table::canonical_str_id);

        let drop_list: Vec<_> = self
            .symbol_table
            .iter()
            .filter(|x| is_drop_symbol(x.1, file_path, prj))
            .map(|x| *x.0)
            .collect();

        // Read while the symbols are still in the table.
        let dropped: Vec<_> = drop_list
            .iter()
            .filter_map(|id| {
                self.symbol_table
                    .get(id)
                    .map(|symbol| scope::DroppedSymbol {
                        scope: symbol.scope,
                        name: symbol.token.text,
                        id: *id,
                    })
            })
            .collect();

        for id in &drop_list {
            if let Some(symbol) = self.symbol_table.get(id)
                && let Some(ids) = self.namespace_index.get_mut(&symbol.namespace.paths)
            {
                ids.retain(|x| x != id);
            }
            self.symbol_table.remove(id);
            self.reference_table.remove(id);
        }

        for symbols in self.name_table.values_mut() {
            symbols.retain(|x| !drop_list.contains(x));
        }

        for tokens in self.reference_table.values_mut() {
            tokens.retain(|x| !is_drop_token(x, file_path, prj));
        }

        self.sv_shadows.retain(|x| x.token.source != file_path);

        scope::drop_symbols(&dropped);
    }

    pub fn add_reference(&mut self, target: SymbolId, token: &Token) {
        if self.symbol_table.contains_key(&target) {
            self.reference_table
                .entry(target)
                .or_default()
                .push(token.to_owned());
        }
    }

    /// Records the pending-list lengths before one file's pass1, so the
    /// file's additions can be exported afterwards for fragment caching.
    pub fn pending_watermark(&self) -> PendingWatermark {
        PendingWatermark {
            import: self.import_list.len(),
            bind: self.bind_list.len(),
            msb: self.msb_list.len(),
            connect: self.connect_list.len(),
        }
    }

    /// Exports everything one file's pass1 wrote into the symbol table:
    /// the symbols in the file's ID window plus the pending entries added
    /// since the watermark. Must be called before `analyze_post_pass1`
    /// (which drains the pending lists and mutates symbols).
    pub fn export_fragment(
        &self,
        symbol_window_start: usize,
        symbol_window_end: usize,
        watermark: &PendingWatermark,
    ) -> SymbolTableFragment {
        let in_window = |id: &SymbolId| id.0 > symbol_window_start && id.0 <= symbol_window_end;

        let mut symbols: Vec<Symbol> = self
            .symbol_table
            .iter()
            .filter(|(id, _)| in_window(id))
            .map(|(_, symbol)| (**symbol).clone())
            .collect();
        // Shadowed `$sv::` members too, deduped: a file usually mentions the
        // same member many times.
        let sv_member_key = |x: &Symbol| {
            (
                x.namespace.paths.clone(),
                resource_table::canonical_str_id(x.token.text),
            )
        };
        let mut defined: HashSet<_> = symbols
            .iter()
            .filter(|x| matches!(x.kind, SymbolKind::SystemVerilog))
            .map(sv_member_key)
            .collect();
        symbols.extend(
            self.sv_shadows
                .iter()
                .filter(|x| in_window(&x.id) && defined.insert(sv_member_key(x)))
                .cloned(),
        );
        symbols.sort_unstable_by_key(|x| x.id);

        let mut reference_functions: Vec<_> = self
            .reference_func_table
            .iter()
            .filter(|(id, _)| in_window(id))
            .map(|(id, x)| (*id, x.clone()))
            .collect();
        reference_functions.sort_unstable_by_key(|(id, _)| *id);

        let mut references: Vec<_> = self
            .reference_table
            .iter()
            .filter(|(id, _)| in_window(id))
            .map(|(id, x)| (*id, x.clone()))
            .collect();
        references.sort_unstable_by_key(|(id, _)| *id);

        SymbolTableFragment {
            symbols,
            imports: self.import_list[watermark.import..].to_vec(),
            binds: self.bind_list[watermark.bind..].to_vec(),
            msbs: self.msb_list[watermark.msb..].to_vec(),
            connects: self.connect_list[watermark.connect..].to_vec(),
            reference_functions,
            references,
        }
    }

    /// Re-inserts a previously exported fragment. Symbol IDs must already
    /// be rebased onto fresh ranges by the fragment codec. Fails if any
    /// symbol conflicts with an existing one; the caller is expected to
    /// fall back to a regular parse + pass1 after `drop`ping the file.
    pub fn restore_fragment(&mut self, fragment: SymbolTableFragment) -> Result<(), Box<Symbol>> {
        for mut symbol in fragment.symbols {
            // `scope` is not serialized (runtime-only intern handle); re-derive
            // it from the namespace so the restored binding lands in the right
            // scope instead of the default root.
            symbol.scope = scope::intern_namespace(&symbol.namespace);
            let token = symbol.token;
            let id = symbol.id;
            let scope = symbol.scope;
            let owned_scope_kind = scope::scope_kind_of(&symbol.kind);
            if self.insert(&token, symbol.clone()).is_none() {
                // `$sv::` members are shared: another file having registered
                // the same one is not a conflict.
                if matches!(symbol.kind, SymbolKind::SystemVerilog) {
                    continue;
                }
                return Err(Box::new(symbol));
            }
            // Re-establish the owned inner scope's kind/owner, which pass1 sets
            // in `insert_symbol` but the serialized fragment does not carry.
            // Without this, `scope::owner_of` is `None` for restored
            // declarations and structural navigation falls back to name
            // resolution on warm builds.
            if let Some(kind) = owned_scope_kind {
                let owned = scope::intern_child(scope, token.text, kind);
                scope::set_kind_owner(owned, kind, id);
            }
        }
        self.import_list.extend(fragment.imports);
        self.bind_list.extend(fragment.binds);
        self.msb_list.extend(fragment.msbs);
        self.connect_list.extend(fragment.connects);
        for (id, functions) in fragment.reference_functions {
            self.reference_func_table.insert(id, functions);
        }
        for (id, tokens) in fragment.references {
            self.reference_table.entry(id).or_default().extend(tokens);
        }
        Ok(())
    }

    pub fn add_generic_instance(&mut self, target: SymbolId, instance: SymbolId) {
        if let Some(symbol) = self.symbol_table.get_mut(&target).map(Rc::make_mut)
            && !symbol.generic_instances.contains(&instance)
        {
            symbol.generic_instances.push(instance);
        }
    }

    pub fn update_generic_instance_affiliation(&mut self, target: SymbolId, instance: &Symbol) {
        let Some(target_inst_ids) = self
            .symbol_table
            .get(&target)
            .map(|x| x.generic_instances.clone())
        else {
            return;
        };
        for target_inst_id in &target_inst_ids {
            if let Some(target_inst_symbol) =
                self.symbol_table.get_mut(target_inst_id).map(Rc::make_mut)
                && target_inst_symbol.token.text == instance.token.text
            {
                let SymbolKind::GenericInstance(target_inst) = &mut target_inst_symbol.kind else {
                    unreachable!();
                };
                let SymbolKind::GenericInstance(inst) = &instance.kind else {
                    unreachable!();
                };
                if let Some(affiliation_symbol) = inst.affiliation_symbols.first()
                    && !target_inst.affiliation_symbols.contains(affiliation_symbol)
                {
                    target_inst.affiliation_symbols.push(*affiliation_symbol);
                }
                break;
            }
        }
    }

    pub fn add_import(&mut self, import: Import) {
        self.import_list.push(import);
    }

    pub fn apply_import(&mut self) {
        // Set skip_generic_args to true to skip applying generic args during resolving the path.
        // symbol_table::get is used when applying generic args but it is forbidden in
        // apply import which borrows `&mut self`.
        self.skip_generic_args = true;

        let import_list: Vec<_> = std::mem::take(&mut self.import_list);
        for import in &import_list {
            let context = ResolveContext::new(&import.path.1);
            let Ok((symbol, imported)) = self
                .resolve(&import.path.0.generic_path(), &[], context)
                .map(|x| ((*x.found).clone(), x.imported))
            else {
                continue;
            };

            // The import target scope records the binding; resolution and
            // imported-path expansion read it from the scope tree.
            let target_scope = scope::intern_namespace(&import.namespace);
            let define_context = import.namespace.define_context.clone();

            if import.wildcard {
                let wildcard_target = if matches!(symbol.kind, SymbolKind::Enum(_)) {
                    Some(symbol.clone())
                } else {
                    self.get_package(&symbol, false, imported)
                };
                if let Some(target_symbol) = wildcard_target {
                    let target = target_symbol.inner_namespace();
                    let source_scope = scope::intern_namespace(&target);
                    scope::add_wildcard(
                        target_scope,
                        source_scope,
                        define_context,
                        target.define_context.clone(),
                        import.path.0.clone(),
                    );
                }
            } else if !matches!(symbol.kind, SymbolKind::SystemVerilog) {
                let mut package_path = import.path.0.clone();
                package_path.paths.pop();
                scope::add_import(
                    target_scope,
                    symbol.token.text,
                    symbol.id,
                    define_context,
                    package_path,
                );
            }
        }

        self.skip_generic_args = false;
    }

    fn get_package(
        &self,
        symbol: &Symbol,
        include_proto: bool,
        include_proto_alias: bool,
    ) -> Option<Symbol> {
        match &symbol.kind {
            SymbolKind::Package(x) if x.is_proto => {
                if include_proto {
                    return Some(symbol.clone());
                }
            }
            SymbolKind::Package(_) => return Some(symbol.clone()),
            SymbolKind::AliasPackage(x) if !x.is_proto || include_proto_alias => {
                let context = ResolveContext::new(&symbol.namespace);
                if let Ok(symbol) = self.resolve(&x.target.generic_path(), &[], context) {
                    let include_proto = if x.is_proto { true } else { include_proto };
                    return self.get_package(&symbol.found, include_proto, false);
                }
            }
            SymbolKind::GenericInstance(x) => {
                let symbol = self.get(x.base).unwrap();
                return self.get_package(&symbol, false, false);
            }
            SymbolKind::GenericParameter(x) => {
                if let GenericBoundKind::Proto(proto) = &x.bound
                    && let Some(x) = proto.get_user_defined()
                {
                    let context = ResolveContext::new(&symbol.namespace);
                    if let Ok(symbol) = self.resolve(&x.path.generic_path(), &[], context) {
                        return self.get_package(&symbol.found, true, false);
                    }
                }
            }
            _ => {}
        }

        None
    }

    pub fn resolve_interfaces(&mut self) -> Vec<AnalyzerError> {
        let mut errors = Vec::new();
        let mut visited = Vec::new();

        let interface_list: Vec<_> = self
            .symbol_table
            .values()
            .filter_map(|x| {
                if matches!(x.kind, SymbolKind::Interface(_)) {
                    Some(x.id)
                } else {
                    None
                }
            })
            .collect();

        self.skip_generic_args = true;
        for id in interface_list {
            let if_symbol = self.get(id).unwrap();
            self.resolve_interface(&if_symbol, &mut errors, &mut visited);
        }
        self.skip_generic_args = false;

        errors
    }

    fn resolve_interface(
        &mut self,
        if_symbol: &Symbol,
        errors: &mut Vec<AnalyzerError>,
        visited: &mut Vec<SymbolId>,
    ) {
        if visited.contains(&if_symbol.id) {
            // This interface has already been resolved.
            return;
        }
        visited.push(if_symbol.id);

        let mut members = HashMap::default();
        let mut modports = Vec::new();

        self.collect_interface_members(if_symbol, true, &mut members, &mut modports);
        self.apply_mixin_interfaces(if_symbol, &mut members, &mut modports, errors, visited);

        for modport in &modports {
            self.link_modport_members(*modport, &members);
        }
        self.link_modports(if_symbol, &members, &modports, errors);
    }

    fn collect_interface_members(
        &self,
        symbol: &Symbol,
        is_own_member: bool,
        members: &mut HashMap<StrId, SymbolId>,
        modports: &mut Vec<SymbolId>,
    ) {
        if let SymbolKind::Interface(x) = &symbol.kind {
            for id in &x.members {
                let symbol = self.symbol_table.get(id).unwrap();
                members.insert(symbol.token.text, symbol.id);
                if is_own_member && matches!(symbol.kind, SymbolKind::Modport(_)) {
                    modports.push(symbol.id);
                }
            }
        }
    }

    fn apply_mixin_interfaces(
        &mut self,
        symbol: &Symbol,
        members: &mut HashMap<StrId, SymbolId>,
        modports: &mut Vec<SymbolId>,
        errors: &mut Vec<AnalyzerError>,
        visited: &mut Vec<SymbolId>,
    ) {
        if !symbol.kind.has_mixin_sources() {
            return;
        }

        let if_namespace = symbol.inner_namespace();
        for mixin_source in symbol.kind.get_mixin_sources() {
            let Some(mixin_symbol) = self.resolve_mixin_interface(mixin_source, &if_namespace)
            else {
                continue;
            };

            if !self.is_valid_mixin_interface(symbol, &mixin_symbol, members, errors) {
                continue;
            }

            let target_scope = scope::intern_namespace(&if_namespace);
            let target_define_context = if_namespace.define_context.clone();
            let source_namespace = mixin_symbol.inner_namespace();
            let source_scope = scope::intern_namespace(&source_namespace);
            scope::add_mixin_source(
                target_scope,
                source_scope,
                target_define_context,
                source_namespace.define_context.clone(),
                mixin_source.clone(),
            );

            // The mixin source interface needs to be resolved before collecting its members.
            self.resolve_interface(&mixin_symbol, errors, visited);
            self.collect_interface_members(&mixin_symbol, false, members, modports);
        }
    }

    fn resolve_mixin_interface(
        &self,
        source_path: &GenericSymbolPath,
        namespace: &Namespace,
    ) -> Option<Rc<Symbol>> {
        let Ok(symbol) = self.resolve_generic_path(source_path, namespace) else {
            return None;
        };
        if let SymbolKind::AliasInterface(x) = &symbol.found.kind {
            self.resolve_mixin_interface(&x.target, namespace)
        } else {
            Some(symbol.found)
        }
    }

    fn is_valid_mixin_interface(
        &self,
        if_symbol: &Symbol,
        mixin_symbol: &Symbol,
        members: &HashMap<StrId, SymbolId>,
        errors: &mut Vec<AnalyzerError>,
    ) -> bool {
        if matches!(mixin_symbol.kind, SymbolKind::GenericParameter(_))
            || !mixin_symbol.is_interface(false)
        {
            errors.push(AnalyzerError::invalid_mixin(
                &mixin_symbol.token.to_string(),
                "it is not interface",
                &mixin_symbol.token.into(),
            ));
            return false;
        }

        if mixin_symbol.id == if_symbol.id {
            errors.push(AnalyzerError::invalid_mixin(
                &mixin_symbol.token.to_string(),
                "it mixes in itself",
                &mixin_symbol.token.into(),
            ));
            return false;
        }

        if mixin_symbol.kind.has_parameters() {
            errors.push(AnalyzerError::invalid_mixin(
                &mixin_symbol.token.to_string(),
                "it is parameterized",
                &mixin_symbol.token.into(),
            ));
            return false;
        }

        if mixin_symbol.kind.has_mixin_sources() {
            errors.push(AnalyzerError::invalid_mixin(
                &mixin_symbol.token.to_string(),
                "it mixes in other interfaces",
                &mixin_symbol.token.into(),
            ));
            return false;
        }

        let SymbolKind::Interface(mixin_prop) = &mixin_symbol.kind else {
            unreachable!();
        };

        for member in &mixin_prop.members {
            let member_symbol = self.symbol_table.get(member).unwrap();
            if members.contains_key(&member_symbol.token.text) {
                errors.push(AnalyzerError::invalid_mixin(
                    &mixin_symbol.token.to_string(),
                    &format!("{} is already defined", member_symbol.token.text),
                    &mixin_symbol.token.into(),
                ));
                return false;
            }
        }

        true
    }

    fn link_modport_members(&mut self, modport: SymbolId, members: &HashMap<StrId, SymbolId>) {
        let mp_symbol = self.get(modport).unwrap();
        let SymbolKind::Modport(mp) = &mp_symbol.kind else {
            unreachable!();
        };

        for mp_member_id in &mp.members {
            let mut mp_member = self.get(*mp_member_id).unwrap();
            let Some(target_id) = members.get(&mp_member.token.text) else {
                continue;
            };
            match mp_member.kind {
                SymbolKind::ModportFunctionMember(x) => {
                    mp_member.kind =
                        SymbolKind::ModportFunctionMember(ModportFunctionMemberProperty {
                            function: *target_id,
                            generated_from: x.generated_from,
                        });
                    self.update(mp_member);
                }
                SymbolKind::ModportVariableMember(x) => {
                    mp_member.kind =
                        SymbolKind::ModportVariableMember(ModportVariableMemberProperty {
                            variable: *target_id,
                            direction: x.direction,
                            generated_from: x.generated_from,
                        });
                    self.update(mp_member);
                }
                _ => unreachable!(),
            }
        }
    }

    fn link_modports(
        &mut self,
        if_symbol: &Symbol,
        members: &HashMap<StrId, SymbolId>,
        modports: &Vec<SymbolId>,
        errors: &mut Vec<AnalyzerError>,
    ) {
        for mp_id in modports {
            if let Some(mut mp_symbol) = self.get(*mp_id)
                && let SymbolKind::Modport(mp) = &mp_symbol.kind
            {
                let mut default_members = self.collect_modport_default_members(&mp_symbol, members);
                let mut mp_members = mp.members.clone();
                mp_members.append(&mut default_members);

                // The last member has no trailing comma to drop with it, so a
                // guarded one there would strand the previous member's comma.
                // Same rule `last_item_with_define` applies to a written list.
                if let Some(last) = mp_members.last()
                    && let Some(last_symbol) = self.get(*last)
                    && matches!(last_symbol.token.source, TokenSource::Generated(_))
                    && let Some(source) = self.guard_source(&last_symbol)
                {
                    // The declaration the guard came from is legal on its own;
                    // only the modport says which generated list ends with it.
                    let token: TokenRange = (&mp_symbol.token).into();
                    let member_source: TokenRange = (&source.token).into();
                    errors.push(AnalyzerError::last_item_with_define_in_modport(
                        &source.token.to_string(),
                        &mp_symbol.token.to_string(),
                        &token,
                        &member_source,
                    ));
                }

                mp_symbol.kind = SymbolKind::Modport(ModportProperty {
                    interface: if_symbol.id,
                    members: mp_members,
                    default: mp.default.clone(),
                });
                self.update(mp_symbol);
            }
        }
    }

    /// The declaration a modport member takes its guard from, if any. Resolves
    /// through `self`, so it can run while the table is borrowed mutably.
    fn guard_source(&self, member: &Symbol) -> Option<Symbol> {
        collect_guard_sources(member, |id| self.get(id))
            .into_iter()
            .find(|x| !attribute_table::ifdef_conditions(&x.token).is_empty())
    }

    fn collect_modport_default_members(
        &mut self,
        modport_symbol: &Symbol,
        members: &HashMap<StrId, SymbolId>,
    ) -> Vec<SymbolId> {
        let symbol_table = self;

        let mut ret = Vec::new();

        if let SymbolKind::Modport(x) = &modport_symbol.kind
            && let Some(default) = &x.default
        {
            let default_member_directions =
                symbol_table.collect_modport_default_member_target_directions(default, members);
            let explicit_members: HashSet<_> = x
                .members
                .iter()
                .map(|x| symbol_table.get(*x).unwrap().token.text)
                .collect();
            let mut default_members: Vec<_> = members
                .iter()
                .filter(|(text, id)| {
                    if explicit_members.contains(text) {
                        false
                    } else if matches!(default, ModportDefault::Same(_)) {
                        true
                    } else {
                        symbol_table
                            .get(**id)
                            .map(|x| matches!(x.kind, SymbolKind::Variable(_)))
                            .unwrap_or(false)
                    }
                })
                .collect();
            // Sort by SymbolId to keep inserting order as the same as definition order
            default_members.sort_by(|x, y| x.1.cmp(y.1));

            let namespace = modport_symbol.inner_namespace();
            for (text, id) in default_members {
                let target = default_member_directions.get(text);
                let direction = match default {
                    ModportDefault::Input => Some(Direction::Input),
                    ModportDefault::Output => Some(Direction::Output),
                    ModportDefault::Same(_) => target.map(|x| x.0),
                    ModportDefault::Converse(_) => target.map(|x| x.0.converse()),
                };
                let Some(direction) = direction else {
                    continue;
                };
                let generated_from = target.map(|x| x.1);

                let source_path = modport_symbol.token.source.get_path().unwrap();
                let token = Token::generate(*text, source_path);
                scope::insert_token(token.id, source_path, &namespace);
                symbol_table.add_reference(*id, &token);

                let kind = if matches!(direction, Direction::Import) {
                    SymbolKind::ModportFunctionMember(ModportFunctionMemberProperty {
                        function: *id,
                        generated_from,
                    })
                } else {
                    SymbolKind::ModportVariableMember(ModportVariableMemberProperty {
                        direction,
                        variable: *id,
                        generated_from,
                    })
                };
                let symbol = Symbol::new(&token, kind, &namespace, false, DocComment::default());
                if let Some(id) = symbol_table.insert(&token, symbol) {
                    ret.push(id);
                }
            }
        }

        ret
    }

    /// The direction each member of the `..same`/`..converse` targets is declared
    /// with, paired with the target member so its guard can be inherited.
    fn collect_modport_default_member_target_directions(
        &self,
        default: &ModportDefault,
        members: &HashMap<StrId, SymbolId>,
    ) -> HashMap<StrId, (Direction, SymbolId)> {
        let mut ret = HashMap::default();

        match default {
            ModportDefault::Same(targets) | ModportDefault::Converse(targets) => {
                for target in targets {
                    let Some(mp_id) = members.get(&target.text) else {
                        continue;
                    };
                    let Some(mp_symbol) = self.get(*mp_id) else {
                        continue;
                    };
                    let SymbolKind::Modport(mp) = mp_symbol.kind else {
                        continue;
                    };

                    for member in &mp.members {
                        let Some(member_symbol) = self.get(*member) else {
                            continue;
                        };

                        if let SymbolKind::ModportVariableMember(ref member) = member_symbol.kind {
                            ret.insert(
                                member_symbol.token.text,
                                (member.direction, member_symbol.id),
                            );
                        } else if matches!(default, ModportDefault::Same(_))
                            && matches!(member_symbol.kind, SymbolKind::ModportFunctionMember(_))
                        {
                            ret.insert(
                                member_symbol.token.text,
                                (Direction::Import, member_symbol.id),
                            );
                        }
                    }
                }
            }
            _ => {}
        }

        ret
    }

    pub fn add_bind(&mut self, bind: Bind) {
        self.bind_list.push(bind);
    }

    pub fn apply_bind(&mut self) -> Vec<AnalyzerError> {
        let mut errors = Vec::new();

        let bind_list: Vec<Bind> = std::mem::take(&mut self.bind_list);
        for bind in bind_list {
            let Ok(target) = self.resolve_generic_path(&bind.target.0, &bind.target.1) else {
                continue;
            };

            let Some(namespace) = self.resolve_bind_target_namespace(&target.found) else {
                continue;
            };
            let symbol = Symbol::new(
                &bind.token,
                SymbolKind::Instance(bind.property.clone()),
                &namespace,
                false,
                bind.doc_comment.clone(),
            );

            if self.insert(&bind.token, symbol).is_some() {
                if let TokenSource::File { path, .. } = bind.token.source {
                    scope::insert_token(bind.token.id, path, &namespace);

                    for target in bind.property.parameter_connects.values() {
                        Self::update_connect_target_namespace(target, path, &namespace);
                    }
                    for target in bind.property.port_connects.values() {
                        Self::update_connect_target_namespace(target, path, &namespace);
                    }
                }
            } else {
                errors.push(AnalyzerError::duplicated_identifier(
                    &bind.token.to_string(),
                    DuplicatedIdentifierKind::Normal,
                    &bind.token.into(),
                ));
            }
        }

        errors
    }

    fn add_msb(&mut self, msb: Msb) {
        self.msb_list.push(msb);
    }

    fn get_msb(&mut self) -> Vec<Msb> {
        std::mem::take(&mut self.msb_list)
    }

    fn add_connect(&mut self, connect: Connect) {
        self.connect_list.push(connect);
    }

    fn get_connect(&mut self) -> Vec<Connect> {
        std::mem::take(&mut self.connect_list)
    }

    fn resolve_generic_path(
        &self,
        path: &GenericSymbolPath,
        namespace: &Namespace,
    ) -> Result<ResolveResult, ResolveError> {
        let context = ResolveContext::new(namespace);
        self.resolve(&path.generic_path(), &[], context)
    }

    fn resolve_bind_target_namespace(&mut self, target: &Symbol) -> Option<Namespace> {
        match &target.kind {
            SymbolKind::Module(_) => Some(target.inner_namespace()),
            SymbolKind::AliasModule(x) => {
                let Ok(target) = self.resolve_generic_path(&x.target, &target.namespace) else {
                    return None;
                };
                self.resolve_bind_target_namespace(&target.found)
            }
            SymbolKind::Interface(_) => Some(target.inner_namespace()),
            SymbolKind::AliasInterface(x) => {
                let Ok(target) = self.resolve_generic_path(&x.target, &target.namespace) else {
                    return None;
                };
                self.resolve_bind_target_namespace(&target.found)
            }
            _ => None,
        }
    }

    fn update_connect_target_namespace(
        target: &ConnectTarget,
        path: PathId,
        namespace: &Namespace,
    ) {
        let mut collector = TokenCollector::new(false);
        collector.expression(&target.expression);

        for token in &collector.tokens {
            scope::insert_token(token.id, path, namespace);
        }
    }

    pub fn resolve_user_defined(&self) -> Vec<(SymbolId, SymbolId)> {
        let mut resolved = Vec::new();
        for symbol in self.symbol_table.values() {
            if let Some(x) = symbol.kind.get_type()
                && let TypeKind::UserDefined(x) = &x.kind
            {
                let context = ResolveContext::new(&symbol.namespace);
                if let Ok(type_symbol) =
                    self.resolve(&x.path.generic_path(), &x.path.generic_arguments(), context)
                {
                    resolved.push((symbol.id, type_symbol.found.id));
                }
            }
        }
        resolved
    }

    pub fn set_user_defined(&mut self, resolved: Vec<(SymbolId, SymbolId)>) {
        for (id, type_id) in resolved {
            let symbol = Rc::make_mut(self.symbol_table.get_mut(&id).unwrap());
            if let Some(x) = symbol.kind.get_type_mut()
                && let TypeKind::UserDefined(x) = &mut x.kind
            {
                x.symbol = Some(type_id);
            }
        }
    }

    pub fn get_function_symbols(&self) -> Vec<Symbol> {
        self.symbol_table
            .values()
            .filter_map(|symbol| {
                if matches!(symbol.kind, SymbolKind::Function(_)) {
                    Some((**symbol).clone())
                } else {
                    None
                }
            })
            .collect()
    }

    pub fn get_enum_symbols(&self) -> Vec<Symbol> {
        self.symbol_table
            .values()
            .filter_map(|symbol| {
                if matches!(symbol.kind, SymbolKind::Enum(_)) {
                    Some((**symbol).clone())
                } else {
                    None
                }
            })
            .collect()
    }

    pub fn find_project_symbol(&self, prj: StrId) -> Option<Symbol> {
        for symbol in self.symbol_table.values() {
            if matches!(symbol.kind, SymbolKind::Namespace) && symbol.token.text == prj {
                return Some((**symbol).clone());
            }
        }

        None
    }

    pub fn add_project_local(&mut self, prj: StrId, from: StrId, to: StrId) {
        self.project_local_table
            .entry(prj)
            .and_modify(|x| {
                x.insert(from, to);
            })
            .or_insert(HashMap::from_iter([(from, to)]));
    }

    pub fn add_reference_functions(&mut self, id: SymbolId, functions: Vec<GenericSymbolPath>) {
        self.reference_func_table.insert(id, functions);
    }

    pub fn get_reference_functions(&self, id: SymbolId) -> Option<Vec<GenericSymbolPath>> {
        self.reference_func_table.get(&id).cloned()
    }

    pub fn get_references(&self, id: SymbolId) -> Option<Vec<Token>> {
        self.reference_table.get(&id).cloned()
    }

    pub fn clear(&mut self) {
        // The scope arena must be reset before `Self::new` re-registers builtin
        // symbols (which intern their scopes), so the two tables stay in sync.
        scope::clear();
        self.clone_from(&Self::new());
    }

    fn check_unused_variable(&self) -> Vec<AnalyzerError> {
        let mut ret = vec![];
        for symbol in self.symbol_table.values() {
            if let SymbolKind::Variable(_) = symbol.kind
                && self
                    .reference_table
                    .get(&symbol.id)
                    .is_none_or(|v| v.is_empty())
                && !symbol.allow_unused
            {
                let name = symbol.token.to_string();
                if !name.starts_with('_') {
                    ret.push(AnalyzerError::unused_variable(
                        &symbol.token.to_string(),
                        &symbol.token.into(),
                    ));
                }
            }
        }
        ret
    }

    fn get_tests(&self, project_name: &str) -> Vec<(StrId, TestProperty)> {
        self.symbol_table
            .values()
            .filter(|s| s.namespace.to_string() == project_name)
            .filter_map(|symbol| match &symbol.kind {
                SymbolKind::Module(x) if x.test.is_some() => {
                    Some((symbol.token.text, x.test.clone().unwrap()))
                }
                SymbolKind::Test(x) => Some((symbol.token.text, x.clone())),
                _ => None,
            })
            .collect()
    }

    fn get_doc_tests(&self, project_name: &str) -> Vec<DocTestTarget> {
        self.symbol_table
            .values()
            .filter(|s| s.namespace.to_string() == project_name)
            .filter_map(|symbol| {
                if let SymbolKind::Module(ref module_prop) = symbol.kind {
                    let wavedrom_json = symbol.doc_comment.extract_wavedrom_test()?;
                    let ports = module_prop
                        .ports
                        .iter()
                        .map(|p| {
                            let prop = p.property();
                            let name = veryl_parser::resource_table::get_str_value(p.name())
                                .unwrap_or_default();
                            let dir = match prop.direction {
                                Direction::Input => "input",
                                Direction::Output => "output",
                                Direction::Inout => "inout",
                                _ => "unknown",
                            };
                            (name, dir.to_string())
                        })
                        .collect();
                    let path = symbol.token.source.get_path()?;
                    Some(DocTestTarget {
                        module_name: symbol.token.text,
                        wavedrom_json,
                        ports,
                        path,
                    })
                } else {
                    None
                }
            })
            .collect()
    }

    fn check_wavedrom(&self) -> Vec<AnalyzerError> {
        let mut ret = vec![];
        for symbol in self.symbol_table.values() {
            if let SymbolKind::Module(ref module_prop) = symbol.kind {
                let port_names: Vec<String> = module_prop
                    .ports
                    .iter()
                    .map(|p| {
                        veryl_parser::resource_table::get_str_value(p.name()).unwrap_or_default()
                    })
                    .collect();
                ret.extend(wavedrom::check_wavedrom(
                    &symbol.token,
                    symbol.doc_comment.extract_wavedrom_block(false),
                    symbol.doc_comment.extract_wavedrom_block(true),
                    &port_names,
                ));
            }
        }
        ret
    }
}

impl fmt::Display for SymbolTable {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "SymbolTable [")?;
        let mut symbol_width = 0;
        let mut namespace_width = 0;
        let mut reference_width = 0;
        let mut vec: Vec<_> = self.name_table.iter().collect();
        vec.sort_by(|x, y| format!("{}", x.0).cmp(&format!("{}", y.0)));
        for (k, v) in &vec {
            symbol_width = symbol_width.max(format!("{k}").len());
            for id in *v {
                let symbol = self.symbol_table.get(id).unwrap();
                namespace_width = namespace_width.max(format!("{}", symbol.namespace).len());
                reference_width = reference_width
                    .max(format!("{}", self.reference_table.get(id).map_or(0, |v| v.len())).len());
            }
        }
        for (k, v) in &vec {
            for id in *v {
                let symbol = self.symbol_table.get(id).unwrap();
                writeln!(
                    f,
                    "    {:symbol_width$} @ {:namespace_width$} {{ref: {:reference_width$}}}: {},",
                    k,
                    symbol.namespace,
                    self.reference_table.get(id).map_or(0, |v| v.len()),
                    symbol.kind,
                    symbol_width = symbol_width,
                    namespace_width = namespace_width,
                    reference_width = reference_width,
                )?;
            }
        }
        writeln!(f, "]")?;

        Ok(())
    }
}

/// Kind of recursion a symbol is being re-entered through, paired with its
/// `SymbolId` on `ResolveContext::visiting` to terminate cycles. Distinct
/// phases let the same symbol legitimately appear once per phase.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ResolvePhase {
    /// Following an alias (`alias module`/`interface`/`package`) to its target.
    Alias,
    /// Tracing a user-defined type to the scope holding its members.
    TypeTrace,
}

#[derive(Clone)]
struct ResolveContext<'a> {
    found: Option<&'a Rc<Symbol>>,
    last_found: Option<&'a Rc<Symbol>>,
    last_found_type: Option<SymbolId>,
    full_path: Vec<SymbolId>,
    /// Scope-tree cursor: the scope reference resolution searches from. Derived
    /// structurally (a symbol's `scope`/`inner_scope`) rather than by carrying a
    /// `Namespace`, which the cursor used to hold.
    scope: scope::ScopeId,
    /// Instance-side counterpart of `scope`: members are looked up in `scope`
    /// (where the base template's members physically live), but their emission
    /// namespace is reconstructed from `inst_scope`, which carries the mangled
    /// generic-instance prefix through navigation. This is the delegating view —
    /// members are not cloned per instance.
    inst_scope: scope::ScopeId,
    /// ifdef context of the cursor, kept alongside `scope` because it is not
    /// part of the scope's interned identity.
    define_context: DefineContext,
    generic_tables: GenericTables,
    /// Symbols currently being resolved through (alias expansion / type
    /// tracing). Re-entering a `(SymbolId, ResolvePhase)` already present is a
    /// cycle. Entries are pushed while descending and truncated back to the
    /// segment's base in the resolve loop, giving call-path (not monotonic)
    /// scope. Carried into nested resolves via `push`.
    visiting: SVec<(SymbolId, ResolvePhase)>,
    inner: bool,
    other_prj: bool,
    root_prj: bool,
    sv_member: bool,
    imported: bool,
    depth: usize,
}

impl ResolveContext<'_> {
    fn from_scope(scope: scope::ScopeId, define_context: DefineContext) -> Self {
        Self {
            found: None,
            last_found: None,
            last_found_type: None,
            full_path: vec![],
            scope,
            inst_scope: scope,
            define_context,
            generic_tables: GenericTables::default(),
            visiting: SVec::new(),
            inner: false,
            other_prj: false,
            root_prj: true,
            sv_member: false,
            imported: false,
            depth: 0,
        }
    }

    fn new(namespace: &Namespace) -> Self {
        Self::from_scope(
            scope::intern_namespace(namespace),
            namespace.define_context.clone(),
        )
    }

    fn push(&self) -> Self {
        // A nested resolve does not inherit the instance context: `inst_scope`
        // starts from the (base-side) cursor, scoped to a single resolve call.
        let mut ret = Self::from_scope(self.scope, self.define_context.clone());
        ret.generic_tables = self.generic_tables.clone();
        ret.visiting = self.visiting.clone();
        ret.depth = self.depth + 1;
        ret
    }

    /// Moves the cursor to `scope` under `define_context`. These jumps (type
    /// tracing, name-as-namespace) do not preserve a generic-instance context, so
    /// the shadow cursor follows `scope` directly.
    fn set_namespace(&mut self, scope: scope::ScopeId, define_context: DefineContext) {
        self.scope = scope;
        self.inst_scope = scope;
        self.define_context = define_context;
    }

    /// Moves the cursor into a symbol's inner scope (where its members live).
    fn set_inner(&mut self, symbol: &Symbol) {
        let base_inner = scope::inner_scope(symbol.scope, symbol.token.text);
        // Shadow cursor: rebase onto the instance-side cursor only when the symbol
        // is a direct member of the delegated base scope (it really lives in the
        // instance's template). Symbols reached from elsewhere (e.g. imports) keep
        // their own home; only the base segment is renamed.
        self.inst_scope = if scope::generic_delegation(self.inst_scope) == Some(symbol.scope) {
            scope::register_generic_child(self.inst_scope, symbol.token.text, base_inner)
        } else {
            base_inner
        };
        self.scope = base_inner;
        self.define_context = symbol.namespace.define_context.clone();
    }

    /// Reconstructs the cursor namespace from the scope tree on demand. Used by
    /// the few consumers that still need a `Namespace` value (import expansion,
    /// synthesized SystemVerilog members, trace logging).
    fn namespace(&self) -> Namespace {
        scope::namespace(self.scope, &self.define_context)
    }

    fn indent(&self) -> String {
        "  ".repeat(self.depth)
    }
}

const DEFINED_NAMESPACES: [&str; 4] = ["$sv", "$std", "$tb", "$comp"];

// Refer IEEE Std 1800-2023 Table B.1 - Reserved keywords
// This list must be sorted to enable binary search
const SYSTEMVERILOG_KEYWORDS: [&str; 248] = [
    "accept_on",
    "alias",
    "always",
    "always_comb",
    "always_ff",
    "always_latch",
    "and",
    "assert",
    "assign",
    "assume",
    "automatic",
    "before",
    "begin",
    "bind",
    "bins",
    "binsof",
    "bit",
    "break",
    "buf",
    "bufif0",
    "bufif1",
    "byte",
    "case",
    "casex",
    "casez",
    "cell",
    "chandle",
    "checker",
    "class",
    "clocking",
    "cmos",
    "config",
    "const",
    "constraint",
    "context",
    "continue",
    "cover",
    "covergroup",
    "coverpoint",
    "cross",
    "deassign",
    "default",
    "defparam",
    "design",
    "disable",
    "dist",
    "do",
    "edge",
    "else",
    "end",
    "endcase",
    "endchecker",
    "endclass",
    "endclocking",
    "endconfig",
    "endfunction",
    "endgenerate",
    "endgroup",
    "endinterface",
    "endmodule",
    "endpackage",
    "endprimitive",
    "endprogram",
    "endproperty",
    "endspecify",
    "endsequence",
    "endtable",
    "endtask",
    "enum",
    "event",
    "eventually",
    "expect",
    "export",
    "extends",
    "extern",
    "final",
    "first_match",
    "for",
    "force",
    "foreach",
    "forever",
    "fork",
    "forkjoin",
    "function",
    "generate",
    "genvar",
    "global",
    "highz0",
    "highz1",
    "if",
    "iff",
    "ifnone",
    "ignore_bins",
    "illegal_bins",
    "implements",
    "implies",
    "import",
    "incdir",
    "include",
    "initial",
    "inout",
    "input",
    "inside",
    "instance",
    "int",
    "integer",
    "interconnect",
    "interface",
    "intersect",
    "join",
    "join_any",
    "join_none",
    "large",
    "let",
    "liblist",
    "library",
    "local",
    "localparam",
    "logic",
    "longint",
    "macromodule",
    "matches",
    "medium",
    "modport",
    "module",
    "nand",
    "negedge",
    "nettype",
    "new",
    "nexttime",
    "nmos",
    "nor",
    "noshowcancelled",
    "not",
    "notif0",
    "notif1",
    "null",
    "or",
    "output",
    "package",
    "packed",
    "parameter",
    "pmos",
    "posedge",
    "primitive",
    "priority",
    "program",
    "property",
    "protected",
    "pull0",
    "pull1",
    "pulldown",
    "pullup",
    "pulsestyle_ondetect",
    "pulsestyle_onevent",
    "pure",
    "rand",
    "randc",
    "randcase",
    "randsequence",
    "rcmos",
    "real",
    "realtime",
    "ref",
    "reg",
    "reject_on",
    "release",
    "repeat",
    "restrict",
    "return",
    "rnmos",
    "rpmos",
    "rtran",
    "rtranif0",
    "rtranif1",
    "s_always",
    "s_eventually",
    "s_nexttime",
    "s_until",
    "s_until_with",
    "scalared",
    "sequence",
    "shortint",
    "shortreal",
    "showcancelled",
    "signed",
    "small",
    "soft",
    "solve",
    "specify",
    "specparam",
    "static",
    "string",
    "strong",
    "strong0",
    "strong1",
    "struct",
    "super",
    "supply0",
    "supply1",
    "sync_accept_on",
    "sync_reject_on",
    "table",
    "tagged",
    "task",
    "this",
    "throughout",
    "time",
    "timeprecision",
    "timeunit",
    "tran",
    "tranif0",
    "tranif1",
    "tri",
    "tri0",
    "tri1",
    "triand",
    "trior",
    "trireg",
    "type",
    "typedef",
    "union",
    "unique",
    "unique0",
    "unsigned",
    "until",
    "until_with",
    "untyped",
    "use",
    "uwire",
    "var",
    "vectored",
    "virtual",
    "void",
    "wait",
    "wait_order",
    "wand",
    "weak",
    "weak0",
    "weak1",
    "while",
    "wildcard",
    "wire",
    "with",
    "within",
    "wor",
    "xnor",
    "xor",
];

pub fn is_sv_keyword(s: &str) -> bool {
    SYSTEMVERILOG_KEYWORDS.binary_search(&s).is_ok()
}

thread_local!(static SYMBOL_TABLE: RefCell<SymbolTable> = RefCell::new(SymbolTable::new()));
// Resolve caches are keyed by the resolution start (scope + ifdef context)
// rather than a materialized namespace, so a reference's scope is enough to hit
// the cache without reconstructing its namespace path.
type ResolveCacheKey = (SymbolPath, scope::ScopeId, DefineContext);
thread_local!(static SYMBOL_CACHE: RefCell<HashMap<ResolveCacheKey, Rc<ResolveResult>>> = RefCell::new(HashMap::default()));

// Cache for get_namespace_generic_map; its result only depends on the symbol
// table state, so it is invalidated together with SYMBOL_CACHE.
type NamespaceGenericMap = Option<Rc<Vec<GenericMap>>>;
thread_local!(static NS_GENERIC_MAP_CACHE: RefCell<HashMap<(scope::ScopeId, DefineContext), NamespaceGenericMap>> = RefCell::new(HashMap::default()));

// Cache for resolve failures. A new symbol can turn a cached NotFound into a
// successful resolution, so `insert` invalidates this cache even while cache
// clear is suppressed.
thread_local!(static SYMBOL_ERR_CACHE: RefCell<HashMap<ResolveCacheKey, ResolveError>> = RefCell::new(HashMap::default()));

// Structural identity index for generic instances. An instance is keyed by its
// enclosing scope, its base template symbol, and its argument signature instead
// of the mangled string `__Foo__8`. The enclosing scope distinguishes nested
// instances of the same `base::<args>` living under different parent instances
// (e.g. `Func::<1>` in `PkgB::<PkgA::<1>>` vs `PkgB::<PkgA::<2>>`), which the
// mangled identity encodes via the namespace. Built during `insert_generic_instance`
// (instances are never restored from fragments — they are post-pass1, outside the
// pass1 capture window — so the index is complete on cold and warm builds) and
// queried by `resolve_generic_structural` to reach an instance without resolving
// its mangled name.
type GenericInstanceKey = (scope::ScopeId, SymbolId, Vec<SymbolPath>);
thread_local!(static GENERIC_INSTANCE_INDEX: RefCell<HashMap<GenericInstanceKey, SymbolId>> = RefCell::new(HashMap::default()));

fn generic_instance_key(
    enclosing: scope::ScopeId,
    base: SymbolId,
    arguments: &[GenericSymbolPath],
) -> GenericInstanceKey {
    (
        enclosing,
        base,
        arguments.iter().map(|a| a.mangled_path()).collect(),
    )
}

/// Registers a generic instance under its structural identity key, asserting the
/// key is injective: no two distinct instances may share
/// `(enclosing_scope, base, args)`.
pub fn index_generic_instance(
    enclosing: scope::ScopeId,
    base: SymbolId,
    arguments: &[GenericSymbolPath],
    instance: SymbolId,
) {
    let key = generic_instance_key(enclosing, base, arguments);
    GENERIC_INSTANCE_INDEX.with(|f| {
        let mut index = f.borrow_mut();
        if let Some(prev) = index.get(&key) {
            debug_assert_eq!(
                *prev, instance,
                "structural generic-instance key collides with a distinct instance"
            );
        }
        index.insert(key, instance);
    });
}

fn clear_resolve_caches() {
    SYMBOL_CACHE.with(|f| f.borrow_mut().clear());
    SYMBOL_ERR_CACHE.with(|f| f.borrow_mut().clear());
    NS_GENERIC_MAP_CACHE.with(|f| f.borrow_mut().clear());
}

/// Suppress resolve-cache invalidation for bulk mutations that modify symbol
/// metadata without affecting name resolution results. Must be paired with
/// `resume_cache_clear`. `insert` still invalidates the caches.
pub fn suppress_cache_clear() {
    SYMBOL_TABLE.with(|f| f.borrow_mut().suppress_cache_clear = true);
}

/// Resume resolve-cache invalidation after `suppress_cache_clear`.
pub fn resume_cache_clear() {
    SYMBOL_TABLE.with(|f| f.borrow_mut().suppress_cache_clear = false);
}

fn clear_cache() {
    let suppress = SYMBOL_TABLE.with(|f| f.borrow().suppress_cache_clear);
    if !suppress {
        clear_resolve_caches();
    }
}

pub fn insert(token: &Token, symbol: Symbol) -> Option<SymbolId> {
    let ret = SYMBOL_TABLE.with(|f| f.borrow_mut().insert(token, symbol));
    if ret.is_some() {
        clear_resolve_caches();
    }
    ret
}

pub fn insert_sv_member(token: &Token, symbol: Symbol) {
    let ret = SYMBOL_TABLE.with(|f| f.borrow_mut().insert_sv_member(token, symbol));
    if ret.is_some() {
        clear_resolve_caches();
    }
}

pub fn get(id: SymbolId) -> Option<Symbol> {
    SYMBOL_TABLE.with(|f| f.borrow().get(id))
}

/// The declarations whose guards a modport member is subject to, outermost
/// first. `..same`/`..converse` can chain, so `generated_from` is followed to
/// the end.
fn collect_guard_sources(member: &Symbol, get: impl Fn(SymbolId) -> Option<Symbol>) -> Vec<Symbol> {
    let mut ret = Vec::new();
    let mut visited = Vec::new();
    let mut current = Some(member.clone());

    while let Some(member) = current {
        if visited.contains(&member.id) {
            break;
        }
        visited.push(member.id);

        let (target, generated_from) = match member.kind {
            SymbolKind::ModportVariableMember(ref x) => (x.variable, x.generated_from),
            SymbolKind::ModportFunctionMember(ref x) => (x.function, x.generated_from),
            _ => break,
        };
        ret.push(member);
        ret.extend(get(target));
        current = generated_from.and_then(&get);
    }

    ret
}

/// The conditions a modport member must be emitted under, outermost first.
pub fn modport_member_conditions(member: &Symbol) -> Vec<IfdefCondition> {
    let mut ret: Vec<IfdefCondition> = Vec::new();
    for source in collect_guard_sources(member, get) {
        for condition in attribute_table::ifdef_conditions(&source.token) {
            if !ret.contains(&condition) {
                ret.push(condition);
            }
        }
    }
    ret
}

pub fn get_rc(id: SymbolId) -> Option<Rc<Symbol>> {
    SYMBOL_TABLE.with(|f| f.borrow().get_rc(id))
}

pub fn update(symbol: Symbol) {
    clear_resolve_caches();
    SYMBOL_TABLE.with(|f| f.borrow_mut().update(symbol))
}

pub fn resolve<T: Into<SymbolPathNamespace>>(path: T) -> Result<Rc<ResolveResult>, ResolveError> {
    let path: SymbolPathNamespace = path.into();
    let scope = path.2.unwrap_or_else(|| scope::intern_namespace(&path.1));
    let define_context = path.1.define_context.clone();
    let key: ResolveCacheKey = (path.0, scope, define_context.clone());

    if let Some(x) = SYMBOL_CACHE.with(|f| f.borrow().get(&key).cloned()) {
        Ok(x)
    } else if let Some(e) = SYMBOL_ERR_CACHE.with(|f| f.borrow().get(&key).cloned()) {
        Err(e)
    } else {
        match SYMBOL_TABLE.with(|f| {
            f.borrow().resolve(
                &key.0,
                &[],
                ResolveContext::from_scope(scope, define_context),
            )
        }) {
            Ok(x) => {
                let x = Rc::new(x);
                SYMBOL_CACHE.with(|f| f.borrow_mut().insert(key, Rc::clone(&x)));
                Ok(x)
            }
            Err(e) => {
                SYMBOL_ERR_CACHE.with(|f| f.borrow_mut().insert(key, e.clone()));
                Err(e)
            }
        }
    }
}

/// How a structural generic resolution is rooted: at an explicit scope, or at a
/// token or namespace it is derived from. Mirrors the general [`resolve`]
/// accepting an `Into<SymbolPathNamespace>`.
pub enum StructuralRoot {
    Scope(scope::ScopeId, DefineContext),
    Token(resource_table::TokenId),
}

impl From<(scope::ScopeId, DefineContext)> for StructuralRoot {
    fn from((scope, define_context): (scope::ScopeId, DefineContext)) -> Self {
        StructuralRoot::Scope(scope, define_context)
    }
}

impl From<resource_table::TokenId> for StructuralRoot {
    fn from(token: resource_table::TokenId) -> Self {
        StructuralRoot::Token(token)
    }
}

impl From<&Namespace> for StructuralRoot {
    fn from(namespace: &Namespace) -> Self {
        StructuralRoot::Scope(
            scope::intern_namespace(namespace),
            namespace.define_context.clone(),
        )
    }
}

impl StructuralRoot {
    /// The scope (and ifdef context) the structural walk starts from, if known.
    fn structural_scope(&self) -> Option<(scope::ScopeId, DefineContext)> {
        match self {
            StructuralRoot::Scope(scope, define_context) => Some((*scope, define_context.clone())),
            StructuralRoot::Token(token) => scope::token_scope(*token),
        }
    }

    /// The mangled-name path the structural walk falls back to when it declines.
    fn fallback_path(&self, path: SymbolPath) -> SymbolPathNamespace {
        match self {
            StructuralRoot::Scope(scope, define_context) => {
                SymbolPathNamespace::from_scope(path, *scope, define_context.clone())
            }
            StructuralRoot::Token(token) => SymbolPathNamespace::from_token(path, *token),
        }
    }
}

/// Resolve a generic instance path structurally — navigating generic segments
/// through the scope-tree index instead of a mangled name — rooted at a scope,
/// token, or namespace. Falls back to the mangled resolution for the paths the
/// structural walk does not model (synthesized SystemVerilog members). General
/// resolve sites pass arbitrary (possibly non-generic or already-mangled) paths;
/// a degenerate path keeps the mangled behaviour (e.g. double-mangle → not found)
/// these sites' diagnostics rely on.
pub fn resolve_generic_structural(
    path: &GenericSymbolPath,
    root: impl Into<StructuralRoot>,
) -> Result<Rc<ResolveResult>, ResolveError> {
    let root = root.into();
    let structural = root.structural_scope().and_then(|(scope, define_context)| {
        SYMBOL_TABLE.with(|f| {
            f.borrow()
                .resolve_generic_structural(path, scope, define_context)
        })
    });
    match structural {
        Some(structural) => Ok(Rc::new(structural)),
        None => resolve(root.fallback_path(path.mangled_path())),
    }
}

/// Resolve the symbol at depth `i` of `path` — segment `i` taken as a template
/// (its arguments ignored), reached by navigating the prefix `[0..i)` through the
/// instance index, never constructing a mangled prefix name. The structural
/// replacement for the `resolve(path.base_path(i), ..)` idiom: `base_path(i)`
/// mangled the prefix and dropped segment `i`'s arguments, which this reproduces
/// by slicing to `[0..=i]` and clearing the last segment's arguments.
pub fn resolve_base_path(
    path: &GenericSymbolPath,
    i: usize,
    root: impl Into<StructuralRoot>,
) -> Result<Rc<ResolveResult>, ResolveError> {
    let mut sliced = path.slice(i);
    if let Some(last) = sliced.paths.last_mut() {
        last.arguments.clear();
    }
    resolve_generic_structural(&sliced, root)
}

/// Resolve the symbol that `namespace` points to (its deepest segment resolved
/// in the enclosing namespace).
pub fn get_namespace_symbol(namespace: &Namespace) -> Option<Symbol> {
    let mut namespace = namespace.clone();
    namespace.strip_anonymous_path();

    if let Some(path) = namespace.pop()
        && namespace.depth() >= 1
    {
        resolve((path, &namespace)).map(|x| (*x.found).clone()).ok()
    } else {
        None
    }
}

pub fn get_all() -> Vec<Symbol> {
    SYMBOL_TABLE.with(|f| f.borrow().get_all())
}

pub fn dump() -> String {
    SYMBOL_TABLE.with(|f| f.borrow().dump())
}

pub fn drop(file_path: PathId, prj: Option<StrId>) {
    clear_resolve_caches();
    SYMBOL_TABLE.with(|f| f.borrow_mut().drop(file_path, prj))
}

pub fn add_reference(target: SymbolId, token: &Token) {
    SYMBOL_TABLE.with(|f| f.borrow_mut().add_reference(target, token))
}

pub fn add_generic_instance(target: SymbolId, instance: SymbolId) {
    clear_cache();
    SYMBOL_TABLE.with(|f| f.borrow_mut().add_generic_instance(target, instance))
}

pub fn update_generic_instance_affiliation(target: SymbolId, instance: &Symbol) {
    clear_cache();
    SYMBOL_TABLE.with(|f| {
        f.borrow_mut()
            .update_generic_instance_affiliation(target, instance)
    })
}

pub fn add_import(import: Import) {
    clear_resolve_caches();
    SYMBOL_TABLE.with(|f| f.borrow_mut().add_import(import))
}

pub fn apply_import() {
    clear_resolve_caches();
    SYMBOL_TABLE.with(|f| f.borrow_mut().apply_import());
}

pub fn resolve_interfaces() -> Vec<AnalyzerError> {
    clear_resolve_caches();
    SYMBOL_TABLE.with(|f| f.borrow_mut().resolve_interfaces())
}

pub fn add_bind(bind: Bind) {
    clear_resolve_caches();
    SYMBOL_TABLE.with(|f| f.borrow_mut().add_bind(bind))
}

pub fn apply_bind() -> Vec<AnalyzerError> {
    clear_resolve_caches();
    SYMBOL_TABLE.with(|f| f.borrow_mut().apply_bind())
}

pub fn add_msb(msb: Msb) {
    SYMBOL_TABLE.with(|f| f.borrow_mut().add_msb(msb))
}

pub fn apply_msb() -> Vec<AnalyzerError> {
    let msb_list = SYMBOL_TABLE.with(|f| f.borrow_mut().get_msb());
    check_msb(msb_list)
}

pub fn add_connect(connect: Connect) {
    SYMBOL_TABLE.with(|f| f.borrow_mut().add_connect(connect))
}

pub fn apply_connect() -> Vec<AnalyzerError> {
    let connect_list = SYMBOL_TABLE.with(|f| f.borrow_mut().get_connect());
    check_connect(connect_list)
}

pub fn resolve_user_defined() {
    clear_resolve_caches();
    let resolved = SYMBOL_TABLE.with(|f| f.borrow().resolve_user_defined());
    SYMBOL_TABLE.with(|f| f.borrow_mut().set_user_defined(resolved));
}

pub fn resolve_function() {
    let list = SYMBOL_TABLE.with(|f| f.borrow().get_function_symbols());
    function::resolve_function(&list);
}

pub fn resolve_enum() -> Vec<AnalyzerError> {
    let list = SYMBOL_TABLE.with(|f| f.borrow().get_enum_symbols());
    r#enum::resolve_enum(&list)
}

pub fn add_project_local(prj: StrId, from: StrId, to: StrId) {
    clear_resolve_caches();
    SYMBOL_TABLE.with(|f| f.borrow_mut().add_project_local(prj, from, to))
}

pub fn add_reference_functions(id: SymbolId, functions: Vec<GenericSymbolPath>) {
    clear_resolve_caches();
    SYMBOL_TABLE.with(|f| f.borrow_mut().add_reference_functions(id, functions))
}

pub fn get_reference_functions(id: SymbolId) -> Option<Vec<GenericSymbolPath>> {
    SYMBOL_TABLE.with(|f| f.borrow().get_reference_functions(id))
}

pub fn get_references(id: SymbolId) -> Option<Vec<Token>> {
    SYMBOL_TABLE.with(|f| f.borrow().get_references(id))
}

/// See [`SymbolTable::pending_watermark`].
pub fn pending_watermark() -> PendingWatermark {
    SYMBOL_TABLE.with(|f| f.borrow().pending_watermark())
}

/// See [`SymbolTable::export_fragment`].
pub fn export_fragment(
    symbol_window_start: usize,
    symbol_window_end: usize,
    watermark: &PendingWatermark,
) -> SymbolTableFragment {
    SYMBOL_TABLE.with(|f| {
        f.borrow()
            .export_fragment(symbol_window_start, symbol_window_end, watermark)
    })
}

/// See [`SymbolTable::restore_fragment`].
pub fn restore_fragment(fragment: SymbolTableFragment) -> Result<(), Box<Symbol>> {
    let ret = SYMBOL_TABLE.with(|f| f.borrow_mut().restore_fragment(fragment));
    clear_resolve_caches();
    ret
}

pub fn clear() {
    clear_resolve_caches();
    GENERIC_INSTANCE_INDEX.with(|f| f.borrow_mut().clear());
    SYMBOL_TABLE.with(|f| f.borrow_mut().clear())
}

pub fn check_unused_variable() -> Vec<AnalyzerError> {
    SYMBOL_TABLE.with(|f| f.borrow().check_unused_variable())
}

pub fn get_tests(project_name: &str) -> Vec<(StrId, TestProperty)> {
    SYMBOL_TABLE.with(|f| f.borrow().get_tests(project_name))
}

pub fn get_doc_tests(project_name: &str) -> Vec<DocTestTarget> {
    SYMBOL_TABLE.with(|f| f.borrow().get_doc_tests(project_name))
}

pub fn check_wavedrom() -> Vec<AnalyzerError> {
    SYMBOL_TABLE.with(|f| f.borrow().check_wavedrom())
}

#[cfg(test)]
mod tests {
    use crate::namespace::Namespace;
    use crate::symbol_table::{ResolveError, ResolveResult, SymbolPath};
    use crate::{Analyzer, symbol_table};
    use veryl_metadata::Metadata;
    use veryl_parser::{Parser, resource_table};

    const CODE: &str = r##"
    module ModuleA #(
        param paramA: u32 = 1,
        param paramB: PackageA::StructA = 1,
    ) (
        portA: input logic<10>,
        portB: modport InterfaceA::modportA,
    ) {
        const localA: u32 = 1;
        const localB: PackageA::StructA = 1;

        type TypeA = PackageA::StructA;

        var memberA: logic;
        var memberB: PackageA::StructA;
        var memberC: TypeA;
        var memberD: $sv::SvTypeA;
        var memberE: PackageA::UnionA;

        inst instA: InterfaceA;
    }

    interface InterfaceA #(
        param paramA: u32 = 1,
        param paramB: PackageA::StructA = 1,
    ) {
        const localA: u32 = 1;
        const localB: PackageA::StructA = 1;

        type TypeA = PackageA::StructA;

        var memberA: logic;
        var memberB: PackageA::StructA;
        var memberC: TypeA;

        modport modportA {
            memberA: input,
            memberB: output,
            memberC: output,
        }
    }

    package PackageA {
        const localA: u32 = 1;

        struct StructA {
            memberA: logic,
            memberB: StructB,
        }

        struct StructB {
            memberA: logic,
        }

        enum EnumA: logic<2> {
            memberA,
        }

        union UnionA {
            memberA: logic<2>,
            memberB: EnumA,
        }
    }
    "##;

    fn parse() {
        let metadata = Metadata::create_default("prj").unwrap();
        let parser = Parser::parse(CODE, &"").unwrap();
        let analyzer = Analyzer::new(&metadata);
        analyzer.analyze_pass1("prj", &parser.veryl);
    }

    #[track_caller]
    fn check_found(result: Result<std::rc::Rc<ResolveResult>, ResolveError>, expect: &str) {
        assert_eq!(format!("{}", result.unwrap().found.namespace), expect);
    }

    #[track_caller]
    fn check_not_found(result: Result<std::rc::Rc<ResolveResult>, ResolveError>) {
        assert!(result.is_err());
    }

    fn create_path(paths: &[&str]) -> SymbolPath {
        let mut ret = SymbolPath::default();

        for path in paths {
            ret.push(resource_table::insert_str(path));
        }

        ret
    }

    fn create_namespace(paths: &[&str]) -> Namespace {
        // The fixture is analyzed under project "prj", so anchor queries at that
        // project root, matching the namespace pass1 builds for its symbols.
        let mut ret = Namespace::new();
        ret.push(resource_table::insert_str("prj"));

        for path in paths {
            ret.push(resource_table::insert_str(path));
        }

        ret
    }

    fn resolve(
        paths: &[&str],
        namespace: &[&str],
    ) -> Result<std::rc::Rc<ResolveResult>, ResolveError> {
        let path = create_path(paths);
        let namespace = create_namespace(namespace);
        symbol_table::resolve((&path, &namespace))
    }

    #[test]
    fn module() {
        parse();

        let symbol = resolve(&["ModuleA"], &[]);
        check_found(symbol, "prj");

        let symbol = resolve(&["ModuleA"], &["ModuleA"]);
        check_found(symbol, "prj");

        let symbol = resolve(&["ModuleA"], &["InterfaceA"]);
        check_found(symbol, "prj");

        let symbol = resolve(&["ModuleA"], &["PackageA"]);
        check_found(symbol, "prj");
    }

    #[test]
    fn interface() {
        parse();

        let symbol = resolve(&["InterfaceA"], &[]);
        check_found(symbol, "prj");

        let symbol = resolve(&["InterfaceA"], &["ModuleA"]);
        check_found(symbol, "prj");

        let symbol = resolve(&["InterfaceA"], &["InterfaceA"]);
        check_found(symbol, "prj");

        let symbol = resolve(&["InterfaceA"], &["PackageA"]);
        check_found(symbol, "prj");
    }

    #[test]
    fn package() {
        parse();

        let symbol = resolve(&["PackageA"], &[]);
        check_found(symbol, "prj");

        let symbol = resolve(&["InterfaceA"], &["ModuleA"]);
        check_found(symbol, "prj");

        let symbol = resolve(&["InterfaceA"], &["InterfaceA"]);
        check_found(symbol, "prj");

        let symbol = resolve(&["InterfaceA"], &["PackageA"]);
        check_found(symbol, "prj");
    }

    #[test]
    fn param() {
        parse();

        let symbol = resolve(&["paramA"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["paramA"], &["ModuleA"]);
        check_found(symbol, "prj::ModuleA");

        let symbol = resolve(&["paramA"], &["InterfaceA"]);
        check_found(symbol, "prj::InterfaceA");

        let symbol = resolve(&["paramA"], &["PackageA"]);
        check_not_found(symbol);

        let symbol = resolve(&["paramB", "memberB"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["paramB", "memberB"], &["InterfaceA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["paramB", "memberB", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructB");

        let symbol = resolve(&["paramB", "memberB", "memberA"], &["InterfaceA"]);
        check_found(symbol, "prj::PackageA::StructB");
    }

    #[test]
    fn local() {
        parse();

        let symbol = resolve(&["localA"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["localA"], &["ModuleA"]);
        check_found(symbol, "prj::ModuleA");

        let symbol = resolve(&["localA"], &["InterfaceA"]);
        check_found(symbol, "prj::InterfaceA");

        let symbol = resolve(&["localA"], &["PackageA"]);
        check_found(symbol, "prj::PackageA");

        let symbol = resolve(&["localB", "memberB"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["localB", "memberB"], &["InterfaceA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["localB", "memberB", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructB");

        let symbol = resolve(&["localB", "memberB", "memberA"], &["InterfaceA"]);
        check_found(symbol, "prj::PackageA::StructB");
    }

    #[test]
    fn port() {
        parse();

        let symbol = resolve(&["portA"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["portA"], &["ModuleA"]);
        check_found(symbol, "prj::ModuleA");

        let symbol = resolve(&["portA"], &["InterfaceA"]);
        check_not_found(symbol);

        let symbol = resolve(&["portA"], &["PackageA"]);
        check_not_found(symbol);
    }

    #[test]
    fn variable() {
        parse();

        let symbol = resolve(&["memberA"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["memberA"], &["ModuleA"]);
        check_found(symbol, "prj::ModuleA");

        let symbol = resolve(&["memberA"], &["InterfaceA"]);
        check_found(symbol, "prj::InterfaceA");

        let symbol = resolve(&["memberA"], &["PackageA"]);
        check_not_found(symbol);
    }

    #[test]
    fn r#struct() {
        parse();

        let symbol = resolve(&["StructA"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["StructA"], &["ModuleA"]);
        check_not_found(symbol);

        let symbol = resolve(&["StructA"], &["InterfaceA"]);
        check_not_found(symbol);

        let symbol = resolve(&["StructA"], &["PackageA"]);
        check_found(symbol, "prj::PackageA");
    }

    #[test]
    fn struct_member() {
        parse();

        let symbol = resolve(&["memberA"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["memberA"], &["PackageA", "StructA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["memberB", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["memberB", "memberX"], &["ModuleA"]);
        check_not_found(symbol);
    }

    #[test]
    fn r#enum() {
        parse();

        let symbol = resolve(&["EnumA"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["EnumA"], &["ModuleA"]);
        check_not_found(symbol);

        let symbol = resolve(&["EnumA"], &["InterfaceA"]);
        check_not_found(symbol);

        let symbol = resolve(&["EnumA"], &["PackageA"]);
        check_found(symbol, "prj::PackageA");
    }

    #[test]
    fn enum_member() {
        parse();

        let symbol = resolve(&["EnumA", "memberA"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["EnumA", "memberA"], &["ModuleA"]);
        check_not_found(symbol);

        let symbol = resolve(&["EnumA", "memberA"], &["InterfaceA"]);
        check_not_found(symbol);

        let symbol = resolve(&["EnumA", "memberA"], &["PackageA"]);
        check_found(symbol, "prj::PackageA::EnumA");
    }

    #[test]
    fn union() {
        parse();

        let symbol = resolve(&["UnionA"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["UnionA"], &["ModuleA"]);
        check_not_found(symbol);

        let symbol = resolve(&["UnionA"], &["InterfaceA"]);
        check_not_found(symbol);

        let symbol = resolve(&["UnionA"], &["PackageA"]);
        check_found(symbol, "prj::PackageA");
    }

    #[test]
    fn union_member() {
        parse();

        let symbol = resolve(&["memberE"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["memberE"], &["ModuleA"]);
        check_found(symbol, "prj::ModuleA");

        let symbol = resolve(&["memberE", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::UnionA");

        let symbol = resolve(&["memberE", "memberB"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::UnionA");
    }

    #[test]
    fn modport() {
        parse();

        let symbol = resolve(&["portB"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["portB"], &["ModuleA"]);
        check_found(symbol, "prj::ModuleA");

        let symbol = resolve(&["portB", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::InterfaceA::modportA");

        let symbol = resolve(&["portB", "memberB"], &["ModuleA"]);
        check_found(symbol, "prj::InterfaceA::modportA");

        let symbol = resolve(&["portB", "memberB", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["portB", "memberB", "memberB"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["portB", "memberB", "memberB", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructB");

        let symbol = resolve(&["portB", "memberC"], &["ModuleA"]);
        check_found(symbol, "prj::InterfaceA::modportA");

        let symbol = resolve(&["portB", "memberC", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["portB", "memberC", "memberB"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["portB", "memberC", "memberB", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructB");
    }

    #[test]
    fn typedef() {
        parse();

        let symbol = resolve(&["memberC"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["memberC"], &["ModuleA"]);
        check_found(symbol, "prj::ModuleA");

        let symbol = resolve(&["memberC", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructA");

        let symbol = resolve(&["memberC", "memberX"], &["ModuleA"]);
        check_not_found(symbol);
    }

    #[test]
    fn sv_member() {
        parse();

        let symbol = resolve(&["memberD"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["memberD"], &["ModuleA"]);
        check_found(symbol, "prj::ModuleA");

        let symbol = resolve(&["memberD", "memberA"], &["ModuleA"]);
        check_found(symbol, "$sv::SvTypeA");

        let symbol = resolve(&["memberD", "memberA", "memberA", "memberA"], &["ModuleA"]);
        check_found(symbol, "$sv::SvTypeA");
    }

    #[test]
    fn inst() {
        parse();

        let symbol = resolve(&["instA"], &[]);
        check_not_found(symbol);

        let symbol = resolve(&["instA"], &["ModuleA"]);
        check_found(symbol, "prj::ModuleA");

        let symbol = resolve(&["instA", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::InterfaceA");

        let symbol = resolve(&["instA", "memberB", "memberB", "memberA"], &["ModuleA"]);
        check_found(symbol, "prj::PackageA::StructB");
    }

    const IMPORT_PRECEDENCE_CODE: &str = r##"
    package PkgA {
        enum EnumA: u32 {
            val = 100,
        }
    }
    package PkgB {
        const val: u32 = 200;
    }
    module ModLocal {
        import PkgA::EnumA::*;
        const val: u32 = 7;
    }
    module ModExplicit {
        import PkgA::EnumA::*;
        import PkgB::val;
    }
    module ModAmbiguous {
        import PkgA::EnumA::*;
        import PkgB::*;
    }
    "##;

    /// SystemVerilog import precedence: a local declaration or an explicit
    /// import shadows a wildcard import in the same scope without error, while
    /// two wildcard imports of the same name are ambiguous.
    #[test]
    fn import_precedence() {
        let handle = std::thread::Builder::new()
            .stack_size(16 * 1024 * 1024)
            .spawn(|| {
                let metadata = Metadata::create_default("prj").unwrap();
                let parser = Parser::parse(IMPORT_PRECEDENCE_CODE, &"").unwrap();
                let analyzer = Analyzer::new(&metadata);
                analyzer.analyze_pass1("prj", &parser.veryl);
                Analyzer::analyze_post_pass1();

                // Local declaration wins over the wildcard-imported enum member.
                check_found(resolve(&["val"], &["ModLocal"]), "prj::ModLocal");
                // Explicit import wins over the wildcard import.
                check_found(resolve(&["val"], &["ModExplicit"]), "prj::PkgB");
                // Two wildcard imports of the same name are ambiguous.
                check_not_found(resolve(&["val"], &["ModAmbiguous"]));
            })
            .unwrap();
        handle.join().unwrap();
    }
}