c2rust-transpile 0.22.1

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

use dtoa;
use failure::{err_msg, format_err, Fail};
use indexmap::indexmap;
use indexmap::{IndexMap, IndexSet};
use itertools::Itertools;
use log::{error, info, trace, warn};
use proc_macro2::{Punct, Spacing::*, Span, TokenStream, TokenTree};
use syn::spanned::Spanned as _;
use syn::{
    AttrStyle, BareVariadic, Block, Expr, ExprBinary, ExprBlock, ExprBreak, ExprCast, ExprField,
    ExprIndex, ExprParen, ExprUnary, FnArg, ForeignItem, ForeignItemFn, ForeignItemMacro,
    ForeignItemStatic, ForeignItemType, Ident, Item, ItemConst, ItemEnum, ItemExternCrate, ItemFn,
    ItemForeignMod, ItemImpl, ItemMacro, ItemMod, ItemStatic, ItemStruct, ItemTrait,
    ItemTraitAlias, ItemType, ItemUnion, ItemUse, Lit, MacroDelimiter, PathSegment, ReturnType,
    Stmt, Type, TypeTuple, UseTree, Visibility,
};
use syn::{BinOp, UnOp}; // To override `c_ast::{BinOp,UnOp}` from glob import.

use crate::diagnostics::TranslationResult;
use crate::rust_ast::comment_store::CommentStore;
use crate::rust_ast::item_store::ItemStore;
use crate::rust_ast::set_span::SetSpan;
use crate::rust_ast::{pos_to_span, SpanExt};
use crate::translator::named_references::NamedReference;
use c2rust_ast_builder::{mk, properties::*, Builder};
use c2rust_ast_printer::pprust;

use crate::c_ast::iterators::{DFExpr, SomeId};
use crate::cfg;
use crate::convert_type::TypeConverter;
use crate::renamer::Renamer;
use crate::with_stmts::WithStmts;
use crate::{c_ast, format_translation_err};
use crate::{c_ast::*, TranslateMacros};
use crate::{ExternCrate, TranspilerConfig};
use c2rust_ast_exporter::clang_ast::LRValue;

mod assembly;
mod atomics;
mod builtins;
mod comments;
mod literals;
mod main_function;
mod named_references;
mod operators;
mod pointers;
mod simd;
mod structs;
mod variadic;

pub use crate::diagnostics::{TranslationError, TranslationErrorKind};
use crate::CrateSet;
use crate::PragmaVec;

pub const INNER_SUFFIX: &str = "_Inner";
pub const PADDING_SUFFIX: &str = "_PADDING";

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct Import {
    decl_id: CDeclId,
    ident_name: String,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum DecayRef {
    Yes,
    Default,
    No,
}

impl DecayRef {
    // Here we give intrinsic meaning to default to equate to yes/true
    // when actually evaluated
    pub fn is_yes(&self) -> bool {
        match self {
            DecayRef::Yes => true,
            DecayRef::Default => true,
            DecayRef::No => false,
        }
    }

    #[inline]
    pub fn is_no(&self) -> bool {
        !self.is_yes()
    }

    pub fn set_default_to_no(&mut self) {
        if *self == DecayRef::Default {
            *self = DecayRef::No;
        }
    }
}

impl From<bool> for DecayRef {
    fn from(b: bool) -> Self {
        match b {
            true => DecayRef::Yes,
            false => DecayRef::No,
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub enum ReplaceMode {
    None,
    Extern,
}

/// Options that impact an expression and all of its subexpressions.
#[derive(Copy, Clone, Debug)]
pub struct ExprContext {
    used: bool,
    is_static: bool,
    is_const: bool,
    decay_ref: DecayRef,
    is_bitfield_write: bool,

    // We will be referring to the expression by address. In this context we
    // can't index arrays because they may legally go out of bounds. We also
    // need to explicitly cast function references to fn() so we get their
    // address in function pointer literals.
    needs_address: bool,

    ternary_needs_parens: bool,
    expanding_macro: Option<CDeclId>,
}

impl ExprContext {
    pub fn used(self) -> Self {
        ExprContext { used: true, ..self }
    }
    pub fn unused(self) -> Self {
        ExprContext {
            used: false,
            ..self
        }
    }
    pub fn is_used(&self) -> bool {
        self.used
    }
    pub fn is_unused(&self) -> bool {
        !self.used
    }
    pub fn decay_ref(self) -> Self {
        ExprContext {
            decay_ref: DecayRef::Yes,
            ..self
        }
    }
    pub fn not_static(self) -> Self {
        ExprContext {
            is_static: false,
            ..self
        }
    }
    pub fn static_(self) -> Self {
        ExprContext {
            is_static: true,
            ..self
        }
    }
    pub fn set_static(self, is_static: bool) -> Self {
        ExprContext { is_static, ..self }
    }
    pub fn set_const(self, is_const: bool) -> Self {
        ExprContext { is_const, ..self }
    }
    pub fn is_bitfield_write(&self) -> bool {
        self.is_bitfield_write
    }
    pub fn set_bitfield_write(self, is_bitfield_write: bool) -> Self {
        ExprContext {
            is_bitfield_write,
            ..self
        }
    }
    pub fn needs_address(&self) -> bool {
        self.needs_address
    }
    pub fn set_needs_address(self, needs_address: bool) -> Self {
        ExprContext {
            needs_address,
            ..self
        }
    }

    /// Are we expanding the given macro in the current context?
    pub fn expanding_macro(&self, mac: &CDeclId) -> bool {
        match self.expanding_macro {
            Some(expanding) => expanding == *mac,
            None => false,
        }
    }
    pub fn set_expanding_macro(self, mac: CDeclId) -> Self {
        ExprContext {
            expanding_macro: Some(mac),
            ..self
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct FuncContext {
    /// The name of the function we're currently translating
    name: Option<String>,
    /// The name we give to the Rust function argument corresponding
    /// to the ellipsis in variadic C functions.
    va_list_arg_name: Option<String>,
    /// The va_list decls that are either `va_start`ed or `va_copy`ed.
    va_list_decl_ids: Option<IndexSet<CDeclId>>,
    /// The name we give to the Rust variable holding all allocations made with `alloca`.
    alloca_allocations_name: Option<String>,
}

impl FuncContext {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn enter_new(&mut self, fn_name: &str) {
        *self = Self {
            name: Some(fn_name.to_string()),
            ..Default::default()
        };
    }

    pub fn get_name(&self) -> &str {
        self.name.as_ref().unwrap()
    }

    pub fn get_va_list_arg_name(&self) -> &str {
        self.va_list_arg_name.as_ref().unwrap()
    }
}

#[derive(Clone)]
struct MacroExpansion {
    ty: CTypeId,
}

type ZeroInits = IndexMap<CDeclId, (WithStmts<Box<Expr>>, IndexSet<Import>)>;

pub struct Translation<'c> {
    // Translation environment
    pub ast_context: TypedAstContext,
    pub tcfg: &'c TranspilerConfig,

    // Accumulated outputs
    pub features: RefCell<IndexSet<&'static str>>,
    sectioned_static_initializers: RefCell<Vec<Stmt>>,
    extern_crates: RefCell<CrateSet>,

    // Translation state and utilities
    type_converter: RefCell<TypeConverter>,
    renamer: RefCell<Renamer<CDeclId>>,
    zero_inits: RefCell<ZeroInits>,
    function_context: RefCell<FuncContext>,
    potential_flexible_array_members: RefCell<IndexSet<CDeclId>>,
    macro_expansions: RefCell<IndexMap<CDeclId, Option<MacroExpansion>>>,
    /// Sets of imports deferred while translating nested expressions for caching. Imports are
    /// deferred when caching translations to make them pure and thus cache the translation
    /// alongside its required imports. Each additional nested level of caching translation
    /// causes an additional set to be pushed onto the `deferred_imports` vector.
    deferred_imports: RefCell<Vec<IndexSet<Import>>>,

    // Comment support
    pub comment_context: CommentContext,      // Incoming comments
    pub comment_store: RefCell<CommentStore>, // Outgoing comments

    spans: HashMap<SomeId, Span>,

    // Items indexed by file id of the source
    items: RefCell<IndexMap<FileId, ItemStore>>,

    // Mod names to try to stop collisions from happening
    mod_names: RefCell<IndexMap<String, PathBuf>>,

    // The main file id that the translator is operating on
    main_file: FileId,

    // While expanding an item, store the current file id that item is
    // expanded from. This is needed in order to note imports in items when
    // encountering DeclRefs.
    cur_file: Cell<Option<FileId>>,
}

fn cast_int(val: Box<Expr>, name: &str, need_lit_suffix: bool) -> Box<Expr> {
    let opt_literal_val = match &*val {
        Expr::Lit(ref l) => match &l.lit {
            Lit::Int(i) => Some(i.base10_digits().parse().unwrap()),
            _ => None,
        },
        _ => None,
    };
    match opt_literal_val {
        Some(i) if !need_lit_suffix => mk().lit_expr(mk().int_unsuffixed_lit(i)),
        Some(i) => mk().lit_expr(mk().int_lit(i, name)),
        None => mk().cast_expr(val, mk().path_ty(vec![name])),
    }
}

/// Given an expression with type Option<fn(...)->...>, unwrap
/// the Option and return the function.
fn unwrap_function_pointer(ptr: Box<Expr>) -> Box<Expr> {
    let err_msg = mk().lit_expr("non-null function pointer");
    mk().method_call_expr(ptr, "expect", vec![err_msg])
}

fn transmute_expr(source_ty: Box<Type>, target_ty: Box<Type>, expr: Box<Expr>) -> Box<Expr> {
    let type_args = match (&*source_ty, &*target_ty) {
        (Type::Infer(_), Type::Infer(_)) => Vec::new(),
        _ => vec![source_ty, target_ty],
    };
    let mut path = vec![mk().path_segment("core"), mk().path_segment("mem")];

    if type_args.is_empty() {
        path.push(mk().path_segment("transmute"));
    } else {
        path.push(mk().path_segment_with_args("transmute", mk().angle_bracketed_args(type_args)));
    }

    mk().call_expr(mk().abs_path_expr(path), vec![expr])
}

fn vec_expr(val: Box<Expr>, count: Box<Expr>) -> Box<Expr> {
    let from_elem = mk().abs_path_expr(vec!["std", "vec", "from_elem"]);
    mk().call_expr(from_elem, vec![val, count])
}

pub fn stmts_block(mut stmts: Vec<Stmt>) -> Block {
    match stmts.pop() {
        None => {}
        Some(Stmt::Expr(
            Expr::Block(ExprBlock {
                block, label: None, ..
            }),
            None,
        )) if stmts.is_empty() => return block,
        Some(mut s) => {
            if let Stmt::Expr(e, None) = s {
                s = Stmt::Expr(e, Some(Default::default()));
            }
            stmts.push(s);
        }
    }
    mk().block(stmts)
}

/// Generate link attributes needed to ensure that the generated Rust libraries have the right symbol values.
fn mk_linkage(in_extern_block: bool, new_name: &str, old_name: &str) -> Builder {
    if new_name == old_name {
        if in_extern_block {
            mk() // There is no mangling by default in extern blocks anymore
        } else {
            mk().single_attr("no_mangle") // Don't touch my name Rust!
        }
    } else if in_extern_block {
        mk().str_attr("link_name", old_name) // Look for this name
    } else {
        mk().str_attr("export_name", old_name) // Make sure you actually name it this
    }
}

pub fn signed_int_expr(value: i64) -> Box<Expr> {
    if value < 0 {
        mk().unary_expr(
            UnOp::Neg(Default::default()),
            mk().lit_expr(mk().int_lit(u128::from(value.unsigned_abs()), "")),
        )
    } else {
        mk().lit_expr(mk().int_lit(value as u128, ""))
    }
}

// This should only be used for tests
fn prefix_names(translation: &mut Translation, prefix: &str) {
    for (&decl_id, ref mut decl) in translation.ast_context.iter_mut_decls() {
        match decl.kind {
            CDeclKind::Function {
                ref mut name,
                ref body,
                ..
            } if body.is_some() => {
                // SIMD types are imported and do not need to be renamed
                if name.starts_with("_mm") {
                    continue;
                }

                name.insert_str(0, prefix);

                translation.renamer.borrow_mut().insert(decl_id, name);
            }
            CDeclKind::Variable {
                ref mut ident,
                has_static_duration,
                has_thread_duration,
                ..
            } if has_static_duration || has_thread_duration => ident.insert_str(0, prefix),
            _ => (),
        }
    }
}

// This function is meant to create module names, for modules being created with the
// `--reorganize-modules` flag. So what is done is, change '.' && '-' to '_', and depending
// on whether there is a collision or not prepend the prior directory name to the path name.
// To check for collisions, a IndexMap with the path name(key) and the path(value) associated with
// the name. If the path name is in use, but the paths differ there is a collision.
fn clean_path(mod_names: &RefCell<IndexMap<String, PathBuf>>, path: Option<&Path>) -> String {
    fn path_to_str(path: &Path) -> String {
        path.file_name()
            .unwrap()
            .to_str()
            .unwrap()
            .replace(['.', '-'], "_")
    }

    let mut file_path: String = path.map_or("internal".to_string(), path_to_str);
    let path = path.unwrap_or_else(|| Path::new(""));
    let mut mod_names = mod_names.borrow_mut();
    if !mod_names.contains_key(&file_path.clone()) {
        mod_names.insert(file_path.clone(), path.to_path_buf());
    } else {
        let mod_path = mod_names.get(&file_path.clone()).unwrap();
        // A collision in the module names has occurred.
        // Ex: types.h can be included from
        // /usr/include/bits and /usr/include/sys
        if mod_path != path {
            let split_path: Vec<PathBuf> = path
                .to_path_buf()
                .parent()
                .unwrap()
                .iter()
                .map(PathBuf::from)
                .collect();

            let mut to_prepend = path_to_str(split_path.last().unwrap());
            to_prepend.push('_');
            file_path.insert_str(0, &to_prepend);
        }
    }
    file_path
}

pub fn emit_c_decl_map(
    t: &Translation,
    converted_decls: &HashMap<CDeclId, ConvertedDecl>,
    decl_source_ranges: IndexMap<CDeclId, (SrcLoc, SrcLoc)>,
) -> DeclMap {
    let mut path_to_c_source_range: HashMap<&Ident, (SrcLoc, SrcLoc)> = Default::default();
    for (decl, source_range) in decl_source_ranges {
        match converted_decls.get(&decl) {
            Some(ConvertedDecl::ForeignItem(item)) => {
                path_to_c_source_range
                    .insert(foreign_item_ident_vis(item).unwrap().0, source_range);
            }
            Some(ConvertedDecl::Item(item)) => {
                path_to_c_source_range.insert(item_ident(item).unwrap(), source_range);
            }
            Some(ConvertedDecl::Items(items)) => {
                for item in items {
                    path_to_c_source_range.insert(item_ident(item).unwrap(), source_range);
                }
            }
            Some(ConvertedDecl::NoItem) => {}
            None => log::debug!(
                "no converted form to add to C decl map for top-level decl {decl:?}: {:?}!",
                t.ast_context.get_decl(&decl)
            ),
        }
    }

    let file_content = std::fs::read(t.ast_context.get_file_path(t.main_file).unwrap()).unwrap();
    let line_end_offsets = //memchr::memchr_iter(file_content, '\n')
                file_content.iter().positions(|c| *c == b'\n')
                .collect::<Vec<_>>();

    /// Convert a source location line/column into a byte offset, given the positions of each newline in the file.
    fn src_loc_to_byte_offset(line_end_offsets: &[usize], loc: SrcLoc) -> usize {
        let line_offset = loc
            .line
            .checked_sub(2) // lines are 1-indexed, and we want end of the previous line
            .and_then(|line| line_end_offsets.get(line as usize))
            .map(|x| x + 1) // increment end of the prev line to find start of this one
            .unwrap_or(0); // if we indexed out of bounds (e.g. for line 1), start at byte 0
        line_offset + (loc.column as usize).saturating_sub(1)
    }

    // Slice into the source file, fixing up the ends to account for Clang AST quirks.
    let slice_decl_with_fixups = |begin: SrcLoc, end: SrcLoc| -> &[u8] {
        assert!(begin.line <= end.line, "{} <= {}", begin.line, end.line);
        let mut begin_offset = src_loc_to_byte_offset(&line_end_offsets, begin);
        let mut end_offset = src_loc_to_byte_offset(&line_end_offsets, end);
        assert!(begin_offset <= end_offset);
        const VT: u8 = 11; // Vertical Tab
                           // Skip whitespace and any trailing semicolons after the previous decl.
        while let Some(b'\t' | b'\n' | &VT | b'\r' | b' ' | b';') = file_content.get(begin_offset) {
            begin_offset += 1;
        }

        assert!(begin_offset <= end_offset);

        // Extend to include a single trailing semicolon if this decl is not a block
        // (e.g., a variable declaration).
        if file_content.get(end_offset - 1) != Some(&b'}')
            && file_content.get(end_offset) == Some(&b';')
        {
            end_offset += 1;
        }

        assert!(begin_offset <= end_offset);

        &file_content[begin_offset..end_offset]
    };

    let item_path_to_c_source: IndexMap<_, _> = path_to_c_source_range
        .into_iter()
        .map(|(ident, (begin, end))| {
            let path = ident.to_string();
            let c_src = std::str::from_utf8(slice_decl_with_fixups(begin, end)).unwrap();
            (path, c_src.to_owned())
        })
        .collect();
    item_path_to_c_source
}

pub fn translate_failure(tcfg: &TranspilerConfig, msg: &str) {
    error!("{}", msg);
    if tcfg.fail_on_error {
        error!("Translation failed, exiting");
        std::process::exit(1);
    }
}

type DeclMap = IndexMap<String, String>;

pub fn translate(
    ast_context: TypedAstContext,
    tcfg: &TranspilerConfig,
    main_file: &Path,
) -> (String, Option<DeclMap>, PragmaVec, CrateSet) {
    let mut t = Translation::new(ast_context, tcfg, main_file);
    let ctx = ExprContext {
        used: true,
        is_static: false,
        is_const: false,
        decay_ref: DecayRef::Default,
        is_bitfield_write: false,
        needs_address: false,
        ternary_needs_parens: false,
        expanding_macro: None,
    };

    {
        t.locate_comments();

        // Compute source ranges of top decls before pruning any, because pruned
        // decls may help inform the ranges of kept ones.
        let decl_source_ranges = if tcfg.emit_c_decl_map {
            Some(t.ast_context.top_decl_locs())
        } else {
            None
        };

        // Headers often pull in declarations that are unused;
        // we simplify the translator output by omitting those.
        t.ast_context
            .prune_unwanted_decls(tcfg.preserve_unused_functions);

        // Normalize AST types between Clang < 16 and later versions. Ensures that
        // binary and unary operators' expr types agree with their argument types
        // in the presence of typedefs.
        t.ast_context.bubble_expr_types();

        enum Name<'a> {
            Var(&'a str),
            Type(&'a str),
            Anonymous,
            None,
        }

        fn some_type_name(s: Option<&str>) -> Name<'_> {
            match s {
                None => Name::Anonymous,
                Some(r) => Name::Type(r),
            }
        }

        // Used for testing; so that we don't overlap with C function names
        if let Some(ref prefix) = t.tcfg.prefix_function_names {
            prefix_names(&mut t, prefix);
        }

        // Identify typedefs that name unnamed types and collapse the two declarations
        // into a single name and declaration, eliminating the typedef altogether.
        let mut prenamed_decls: IndexMap<CDeclId, CDeclId> = IndexMap::new();
        for (&decl_id, decl) in t.ast_context.iter_decls() {
            if let CDeclKind::Typedef { ref name, typ, .. } = decl.kind {
                if let Some(subdecl_id) = t
                    .ast_context
                    .resolve_type(typ.ctype)
                    .kind
                    .as_underlying_decl()
                {
                    use CDeclKind::*;
                    let is_unnamed = match t.ast_context[subdecl_id].kind {
                        Struct { name: None, .. }
                        | Union { name: None, .. }
                        | Enum { name: None, .. } => true,

                        // Detect case where typedef and struct share the same name.
                        // In this case the purpose of the typedef was simply to eliminate
                        // the need for the 'struct' tag when referring to the type name.
                        Struct {
                            name: Some(ref target_name),
                            ..
                        }
                        | Union {
                            name: Some(ref target_name),
                            ..
                        }
                        | Enum {
                            name: Some(ref target_name),
                            ..
                        } => name == target_name,

                        _ => false,
                    };

                    if is_unnamed
                        && !prenamed_decls
                            .values()
                            .any(|decl_id| *decl_id == subdecl_id)
                    {
                        prenamed_decls.insert(decl_id, subdecl_id);

                        t.type_converter
                            .borrow_mut()
                            .declare_decl_name(decl_id, name);
                        t.type_converter
                            .borrow_mut()
                            .alias_decl_name(subdecl_id, decl_id);
                    }
                }
            }
        }

        t.ast_context.prenamed_decls = prenamed_decls;

        // Helper function that returns true if there is either a matching typedef or its
        // corresponding struct/union/enum
        fn contains(prenamed_decls: &IndexMap<CDeclId, CDeclId>, decl_id: &CDeclId) -> bool {
            prenamed_decls.contains_key(decl_id)
                || prenamed_decls.values().any(|id| *id == *decl_id)
        }

        // Populate renamer with top-level names
        for (&decl_id, decl) in t.ast_context.iter_decls() {
            use CDeclKind::*;
            let decl_name = match decl.kind {
                _ if contains(&t.ast_context.prenamed_decls, &decl_id) => Name::None,
                Struct { ref name, .. } => some_type_name(name.as_ref().map(String::as_str)),
                Enum { ref name, .. } => some_type_name(name.as_ref().map(String::as_str)),
                Union { ref name, .. } => some_type_name(name.as_ref().map(String::as_str)),
                Typedef { ref name, .. } => Name::Type(name),
                Function { ref name, .. } => Name::Var(name),
                EnumConstant { ref name, .. } => Name::Var(name),
                Variable { ref ident, .. } if t.ast_context.c_decls_top.contains(&decl_id) => {
                    Name::Var(ident)
                }
                MacroObject { ref name, .. } => Name::Var(name),
                _ => Name::None,
            };
            match decl_name {
                Name::None => (),
                Name::Anonymous => {
                    t.type_converter
                        .borrow_mut()
                        .declare_decl_name(decl_id, "C2RustUnnamed");
                }
                Name::Type(name) => {
                    t.type_converter
                        .borrow_mut()
                        .declare_decl_name(decl_id, name);
                }
                Name::Var(name) => {
                    t.renamer.borrow_mut().insert(decl_id, name);
                }
            }
        }

        {
            let export_type = |decl_id: CDeclId, decl: &CDecl| {
                let decl_file_id = t.ast_context.file_id(decl);
                if t.tcfg.reorganize_definitions {
                    t.cur_file.set(decl_file_id);
                }
                match t.convert_decl(ctx, decl_id) {
                    Err(e) => {
                        let k = &t.ast_context.get_decl(&decl_id).map(|x| &x.kind);
                        let msg = format!("Skipping declaration {:?} due to error: {}", k, e);
                        translate_failure(t.tcfg, &msg);
                    }
                    Ok(converted_decl) => {
                        use ConvertedDecl::*;
                        match converted_decl {
                            Item(item) => {
                                t.insert_item(item, decl);
                            }
                            ForeignItem(item) => {
                                t.insert_foreign_item(*item, decl);
                            }
                            Items(items) => {
                                for item in items {
                                    t.insert_item(item, decl);
                                }
                            }
                            NoItem => {}
                        }
                    }
                }
                t.cur_file.take();

                if t.tcfg.reorganize_definitions
                    && decl_file_id.map_or(false, |id| id != t.main_file)
                {
                    let name = t
                        .ast_context
                        .get_decl(&decl_id)
                        .and_then(|x| x.kind.get_name());
                    log::debug!(
                        "emitting submodule imports for exported type {}",
                        name.unwrap_or(&"unknown".to_owned())
                    );
                    t.generate_submodule_imports(decl_id, decl_file_id);
                }
            };

            // Export all types
            for (&decl_id, decl) in t.ast_context.iter_decls() {
                use CDeclKind::*;
                let needs_export = match decl.kind {
                    Struct { .. } => true,
                    Enum { .. } => true,
                    EnumConstant { .. } => true,
                    Union { .. } => true,
                    Typedef { .. } => {
                        // Only check the key as opposed to `contains`
                        // because the key should be the typedef id
                        !t.ast_context.prenamed_decls.contains_key(&decl_id)
                    }
                    _ => false,
                };
                if needs_export {
                    export_type(decl_id, decl);
                }
            }
        }

        // Export top-level value declarations.
        // We do this in a conversion pass and then an insertion pass
        // so that the conversion order can differ from the order they're emitted in.
        let mut converted_decls = t
            .ast_context
            .c_decls_top
            .iter()
            .filter_map(|&top_id| {
                use CDeclKind::*;
                let needs_export = match t.ast_context[top_id].kind {
                    Function { is_implicit, .. } => !is_implicit,
                    Variable { .. } => true,
                    MacroObject { .. } => true, // Depends on `tcfg.translate_const_macros`, but handled in `fn convert_const_macro_expansion`.
                    MacroFunction { .. } => true, // Depends on `tcfg.translate_fn_macros`, but handled in `fn convert_fn_macro_invocation`.
                    _ => false,
                };
                if !needs_export {
                    return None;
                }

                let decl = t.ast_context.get_decl(&top_id).unwrap();
                let decl_file_id = t.ast_context.file_id(decl);

                if t.tcfg.reorganize_definitions
                    && decl_file_id.map_or(false, |id| id != t.main_file)
                {
                    t.cur_file.set(decl_file_id);
                }

                // TODO use `.inspect_err` once stabilized in Rust 1.76.
                let converted = match t.convert_decl(ctx, top_id) {
                    Err(e) => {
                        let decl_identifier = decl.kind.get_name().map_or_else(
                            || {
                                t.ast_context
                                    .display_loc(&decl.loc)
                                    .map_or("Unknown".to_string(), |l| format!("at {}", l))
                            },
                            |name| name.clone(),
                        );
                        let msg = format!("Failed to translate {}: {}", decl_identifier, e);
                        translate_failure(t.tcfg, &msg);
                        Err(e)
                    }
                    Ok(converted) => Ok(converted),
                }
                .ok()?;

                t.cur_file.take();

                Some((top_id, converted))
            })
            .collect::<HashMap<_, _>>();

        // Generate a map from Rust items to the source code of their C declarations.
        let decl_map =
            decl_source_ranges.map(|ranges| emit_c_decl_map(&t, &converted_decls, ranges));

        t.ast_context.sort_top_decls_for_emitting();

        for top_id in &t.ast_context.c_decls_top {
            let decl = t.ast_context.get_decl(top_id).unwrap();
            let decl_file_id = t.ast_context.file_id(decl);
            // TODO use `let else` when it stabilizes.
            let converted_decl = match converted_decls.remove(top_id) {
                Some(converted) => converted,
                None => continue,
            };

            use ConvertedDecl::*;
            match converted_decl {
                Item(item) => {
                    t.insert_item(item, decl);
                }
                ForeignItem(item) => {
                    t.insert_foreign_item(*item, decl);
                }
                Items(items) => {
                    for item in items {
                        t.insert_item(item, decl);
                    }
                }
                NoItem => {}
            };

            if t.tcfg.reorganize_definitions && decl_file_id.map_or(false, |id| id != t.main_file) {
                log::debug!("emitting any imports needed by {:?}", decl.kind.get_name());
                t.generate_submodule_imports(*top_id, decl_file_id);
            }
        }

        // Add the main entry point
        if let Some(main_id) = t.ast_context.c_main {
            match t.convert_main(main_id) {
                Ok(item) => t.items.borrow_mut()[&t.main_file].add_item(item),
                Err(e) => {
                    let msg = format!("Failed to translate main: {}", e);
                    translate_failure(t.tcfg, &msg)
                }
            }
        }

        // Initialize global statics when necessary
        if !t.sectioned_static_initializers.borrow().is_empty() {
            let (initializer_fn, initializer_static) = t.generate_global_static_init();
            let store = &mut t.items.borrow_mut()[&t.main_file];

            store.add_item(initializer_fn);
            store.add_item(initializer_static);
        }

        let mut mod_items: Vec<Box<Item>> = Vec::new();

        // Keep track of new uses we need while building header submodules
        let mut new_uses = ItemStore::new();

        // Header Reorganization: Submodule Item Stores
        for (file_id, ref mut mod_item_store) in t.items.borrow_mut().iter_mut() {
            if *file_id != t.main_file {
                if tcfg.reorganize_definitions {
                    t.use_feature("register_tool");
                }
                let mut submodule = make_submodule(
                    &t.ast_context,
                    mod_item_store,
                    *file_id,
                    &mut new_uses,
                    &t.mod_names,
                    tcfg.reorganize_definitions,
                );
                let comments = t.comment_context.get_remaining_comments(*file_id);
                submodule.set_span(match t.comment_store.borrow_mut().add_comments(&comments) {
                    Some(pos) => submodule.span().with_hi(pos),
                    None => submodule.span(),
                });
                mod_items.push(submodule);
            }
        }

        // Main file item store
        let (items, foreign_items, uses) = t.items.borrow_mut()[&t.main_file].drain();

        // Re-order comments
        // FIXME: We shouldn't have to replace with an empty comment store here, that's bad design
        let traverser = t
            .comment_store
            .replace(CommentStore::new())
            .into_comment_traverser();

        /*
        // Add a comment mapping span to each node that should have a
        // comment printed before it. The pretty printer picks up these
        // spans and uses them to decide when to emit comments.
        mod_items = mod_items
            .into_iter()
            .map(|i| traverser.traverse_item(*i)).map(Box::new)
            .collect();
        let foreign_items: Vec<ForeignItem> = foreign_items
            .into_iter()
            .map(|fi| traverser.traverse_foreign_item(fi))
            .collect();
        let items: Vec<Box<Item>> = items
            .into_iter()
            .map(|i| traverser.traverse_item(*i)).map(Box::new)
            .collect();
        */

        let mut reordered_comment_store = traverser.into_comment_store();
        let remaining_comments = t.comment_context.get_remaining_comments(t.main_file);
        reordered_comment_store.add_comments(&remaining_comments);

        // We need a dummy SourceMap with a dummy file so that pprust can try to
        // look up source line numbers for Spans. This is needed to be able to
        // print trailing comments after exprs/stmts/etc. on the same line. The
        // SourceMap will think that all Spans are invalid, but will return line
        // 0 for all of them.

        // FIXME: Use or delete this code
        // let comments = Comments::new(reordered_comment_store.into_comments());

        // pass all converted items to the Rust pretty printer
        let translation = pprust::to_string(|| {
            let (attrs, mut all_items) = arrange_header(&t, t.tcfg.is_binary(main_file));

            all_items.extend(mod_items);

            // Before consuming `uses`, remove them from the uses from submodules to avoid duplicates.
            let (_, _, mut new_uses) = new_uses.drain();
            new_uses.remove(&uses);

            // This could have been merged in with items below; however, it's more idiomatic to have
            // imports near the top of the file than randomly scattered about. Also, there is probably
            // no reason to have comments associated with imports so it doesn't need to go through
            // the above comment store process
            all_items.extend(uses.into_items());

            // Print new uses from submodules
            all_items.extend(new_uses.into_items());

            if !foreign_items.is_empty() {
                all_items.push(mk().extern_("C").foreign_items(foreign_items));
            }

            // Add the items accumulated
            all_items.extend(items);

            //s.print_remaining_comments();
            syn::File {
                shebang: None,
                attrs,
                items: all_items.into_iter().map(|x| *x).collect(),
            }
        });

        let pragmas = t.get_pragmas();
        let extern_crates = t.extern_crates.borrow();
        let type_converter = t.type_converter.borrow();
        let crates = extern_crates
            .union(type_converter.extern_crates_used())
            .copied()
            .collect();

        (translation, decl_map, pragmas, crates)
    }
}

/// Represent the set of names made visible by a `use`: either a set of specific names, or a glob.
enum IdentsOrGlob<'a> {
    Idents(Vec<&'a Ident>),
    Glob,
}

impl<'a> IdentsOrGlob<'a> {
    fn join(self, other: Self) -> Self {
        use IdentsOrGlob::*;
        match (self, other) {
            (Glob, _) => Glob,
            (_, Glob) => Glob,
            (Idents(mut own), Idents(other)) => Idents({
                own.extend(other);
                own
            }),
        }
    }
}

/// Extract the set of names made visible by a `use`.
fn use_idents(i: &UseTree) -> IdentsOrGlob<'_> {
    use UseTree::*;
    match i {
        Path(up) => use_idents(&up.tree),
        Name(un) => IdentsOrGlob::Idents(vec![&un.ident]),
        Rename(ur) => IdentsOrGlob::Idents(vec![&ur.rename]),
        Glob(_ugl) => IdentsOrGlob::Glob,
        Group(ugr) => ugr
            .items
            .iter()
            .map(use_idents)
            .reduce(IdentsOrGlob::join)
            .unwrap_or(IdentsOrGlob::Idents(vec![])),
    }
}

fn item_ident(i: &Item) -> Option<&Ident> {
    use Item::*;
    Some(match i {
        Const(ic) => &ic.ident,
        Enum(ie) => &ie.ident,
        ExternCrate(iec) => &iec.ident,
        Fn(ifn) => &ifn.sig.ident,
        ForeignMod(_ifm) => return None,
        Impl(_ii) => return None,
        Macro(im) => return im.ident.as_ref(),
        Mod(im) => &im.ident,
        Static(is) => &is.ident,
        Struct(is) => &is.ident,
        Trait(it) => &it.ident,
        TraitAlias(ita) => &ita.ident,
        Type(it) => &it.ident,
        Union(iu) => &iu.ident,
        Use(ItemUse { tree: _, .. }) => unimplemented!(),
        Verbatim(_tokenstream) => {
            warn!("cannot determine name of tokenstream item");
            return None;
        }
        _ => {
            warn!("cannot determine name of unknown item kind");
            return None;
        }
    })
}

fn item_vis(i: &Item) -> Option<Visibility> {
    use Item::*;
    Some(
        match i {
            Const(ic) => &ic.vis,
            Enum(ie) => &ie.vis,
            ExternCrate(iec) => &iec.vis,
            Fn(ifn) => &ifn.vis,
            ForeignMod(_ifm) => return None,
            Impl(_ii) => return None,
            Macro(_im) => return None,
            Mod(im) => &im.vis,
            Static(is) => &is.vis,
            Struct(is) => &is.vis,
            Trait(it) => &it.vis,
            TraitAlias(ita) => &ita.vis,
            Type(it) => &it.vis,
            Union(iu) => &iu.vis,
            Use(ItemUse { vis, .. }) => vis,
            Verbatim(_tokenstream) => {
                warn!("cannot determine visibility of tokenstream item");
                return None;
            }
            _ => {
                warn!("cannot determine visibility of unknown item kind");
                return None;
            }
        }
        .clone(),
    )
}

fn foreign_item_ident_vis(fi: &ForeignItem) -> Option<(&Ident, Visibility)> {
    use ForeignItem::*;
    Some(match fi {
        Fn(ifn) => (&ifn.sig.ident, ifn.vis.clone()),
        Static(is) => (&is.ident, is.vis.clone()),
        Type(it) => (&it.ident, it.vis.clone()),
        Macro(_im) => return None,
        Verbatim(_tokenstream) => {
            warn!("cannot determine name and visibility of tokenstream foreign item");
            return None;
        }
        _ => {
            warn!("cannot determine name and visibility of unknown foreign item kind");
            return None;
        }
    })
}

/// Create a submodule containing the items in `item_store`. Populates `use_item_store` with the set
/// of `use`s to import the submodule's exports.
fn make_submodule(
    ast_context: &TypedAstContext,
    item_store: &mut ItemStore,
    file_id: FileId,
    use_item_store: &mut ItemStore,
    mod_names: &RefCell<IndexMap<String, PathBuf>>,
    reorganize_definitions: bool,
) -> Box<Item> {
    let (mut items, foreign_items, uses) = item_store.drain();
    let file_path = ast_context.get_file_path(file_id);
    let include_line_number = ast_context
        .get_file_include_line_number(file_id)
        .unwrap_or(0);
    let mod_name = clean_path(mod_names, file_path);
    let use_path = || vec!["self".into(), mod_name.clone()];

    for item in items.iter() {
        let ident_name = match item_ident(item) {
            Some(i) => i.to_string(),
            None => continue,
        };

        let vis = match item_vis(item) {
            Some(Visibility::Public(_)) => mk().pub_(),
            Some(_) => mk(),
            None => continue,
        };

        use_item_store.add_use_with_attr(false, use_path(), &ident_name, vis);
    }

    for foreign_item in foreign_items.iter() {
        let ident_name = match foreign_item_ident_vis(foreign_item) {
            Some((ident, _vis)) => ident.to_string(),
            None => continue,
        };

        use_item_store.add_use(false, use_path(), &ident_name);
    }

    // Consumers will `use` reexported items at their exported locations.
    for item in uses.into_items() {
        if let Item::Use(ItemUse {
            vis: Visibility::Public(_),
            tree,
            ..
        }) = &*item
        {
            match use_idents(tree) {
                IdentsOrGlob::Idents(idents) => {
                    for ident in idents {
                        fn is_simd_type_name(name: &str) -> bool {
                            const SIMD_TYPE_NAMES: &[&str] = &[
                                "__m128i", "__m128", "__m128d", "__m64", "__m256", "__m256d",
                                "__m256i",
                            ];
                            SIMD_TYPE_NAMES.contains(&name) || name.starts_with("_mm_")
                        }
                        let name = &*ident.to_string();
                        if is_simd_type_name(name) {
                            // Import vector type/operation names from the stdlib, as we also generate
                            // other uses for them from that location and can't easily reason about
                            // the ultimate target of reexported names when avoiding duplicate imports
                            // (which are verboten).
                            simd::add_arch_use(use_item_store, "x86", name);
                            simd::add_arch_use(use_item_store, "x86_64", name);
                        } else {
                            // Add a `use` for `self::this_module::exported_name`.
                            use_item_store.add_use(false, use_path(), name);
                        }
                    }
                }
                IdentsOrGlob::Glob => {}
            }
        }
        items.push(item);
    }

    if !foreign_items.is_empty() {
        items.push(mk().extern_("C").foreign_items(foreign_items));
    }

    let module_builder = mk().pub_();
    let module_builder = if reorganize_definitions {
        let file_path_str = file_path.map_or(mod_name.as_str(), |path| {
            path.to_str().expect("Found invalid unicode")
        });
        module_builder.str_attr(
            vec!["c2rust", "header_src"],
            format!("{}:{}", file_path_str, include_line_number),
        )
    } else {
        module_builder
    };
    module_builder.mod_item(mod_name, Some(mk().mod_(items)))
}

// TODO(kkysen) shouldn't need `extern crate`
/// Pretty-print the leading pragmas and extern crate declarations
// Fixing this would require major refactors for marginal benefit.
#[allow(clippy::vec_box)]
fn arrange_header(t: &Translation, is_binary: bool) -> (Vec<syn::Attribute>, Vec<Box<Item>>) {
    let mut out_attrs = vec![];
    let mut out_items = vec![];
    if t.tcfg.emit_modules && !is_binary {
        for c in t.extern_crates.borrow().iter() {
            out_items.push(mk().use_simple_item(
                mk().abs_path(vec![c.with_details(t.tcfg.c2rust_dir.as_deref()).ident]),
                None::<Ident>,
            ))
        }
    } else {
        let pragmas = t.get_pragmas();
        for (key, mut values) in pragmas {
            values.sort_unstable();
            // generate #[key(values)]
            let meta = mk().meta_list(vec![key], values);
            let attr = mk().attribute(AttrStyle::Inner(Default::default()), meta);
            out_attrs.push(attr);
        }

        if t.tcfg.cross_checks {
            let xcheck_plugin_args = t
                .tcfg
                .cross_check_configs
                .iter()
                .map(|config_file| mk().meta_namevalue("config_file", mk().str_lit(config_file)))
                .collect::<Vec<_>>();
            let xcheck_plugin_item = mk().meta_list("c2rust_xcheck_plugin", xcheck_plugin_args);
            let plugin_args = vec![xcheck_plugin_item];
            let plugin_item = mk().meta_list("plugin", plugin_args);
            let attr = mk().attribute(AttrStyle::Inner(Default::default()), plugin_item);
            out_attrs.push(attr);
        }

        if t.tcfg.emit_no_std {
            let meta = mk().meta_path("no_std");
            let attr = mk().attribute(AttrStyle::Inner(Default::default()), meta);
            out_attrs.push(attr);
        }

        if is_binary {
            // TODO(kkysen) shouldn't need `extern crate`
            // Add `extern crate X;` to the top of the file
            for extern_crate in t.extern_crates.borrow().iter() {
                let extern_crate = extern_crate.with_details(t.tcfg.c2rust_dir.as_deref());
                if extern_crate.macro_use {
                    out_items.push(
                        mk().single_attr("macro_use")
                            .extern_crate_item(extern_crate.ident.clone(), None),
                    );
                }
            }

            if t.tcfg.cross_checks {
                out_items.push(
                    mk().single_attr("macro_use")
                        .extern_crate_item("c2rust_xcheck_derive", None),
                );
                out_items.push(
                    mk().single_attr("macro_use")
                        .extern_crate_item("c2rust_xcheck_runtime", None),
                );
                // When cross-checking, always use the system allocator
                let sys_alloc_path = vec!["", "std", "alloc", "System"];
                out_items.push(mk().single_attr("global_allocator").static_item(
                    "C2RUST_ALLOC",
                    mk().path_ty(sys_alloc_path.clone()),
                    mk().path_expr(sys_alloc_path),
                ));
            }

            // TODO: switch to `#[expect(unused_imports, reason = ...)]` once
            // we upgrade to a newer nightly (Rust 1.81) that supports it.
            out_items.push(
                mk().call_attr("allow", vec!["unused_imports"])
                    .use_simple_item(mk().abs_path(vec![t.tcfg.crate_name()]), None::<Ident>),
            )
        }
    }
    (out_attrs, out_items)
}

/// Convert a boolean expression to a c_int
fn bool_to_int(val: Box<Expr>) -> Box<Expr> {
    mk().cast_expr(val, mk().abs_path_ty(vec!["core", "ffi", "c_int"]))
}

/// Add a src_loc = "line:col" attribute to an item/foreign_item
fn add_src_loc_attr(attrs: &mut Vec<syn::Attribute>, src_loc: &Option<SrcLoc>) {
    if let Some(src_loc) = src_loc.as_ref() {
        let loc_str = format!("{}:{}", src_loc.line, src_loc.column);
        let meta = mk().meta_namevalue(vec!["c2rust", "src_loc"], loc_str);
        let attr = mk().attribute(AttrStyle::Outer, meta);
        attrs.push(attr);
    }
}

/// Get a mutable reference to the attributes of a ForeignItem
fn foreign_item_attrs(item: &mut ForeignItem) -> Option<&mut Vec<syn::Attribute>> {
    use ForeignItem::*;
    Some(match item {
        Fn(ForeignItemFn { ref mut attrs, .. }) => attrs,
        Static(ForeignItemStatic { ref mut attrs, .. }) => attrs,
        Type(ForeignItemType { ref mut attrs, .. }) => attrs,
        Macro(ForeignItemMacro { ref mut attrs, .. }) => attrs,
        Verbatim(TokenStream { .. }) => return None,
        _ => return None,
    })
}

/// Get a mutable reference to the attributes of an Item
fn item_attrs(item: &mut Item) -> Option<&mut Vec<syn::Attribute>> {
    use Item::*;
    Some(match item {
        Const(ItemConst { ref mut attrs, .. }) => attrs,
        Enum(ItemEnum { ref mut attrs, .. }) => attrs,
        ExternCrate(ItemExternCrate { ref mut attrs, .. }) => attrs,
        Fn(ItemFn { ref mut attrs, .. }) => attrs,
        ForeignMod(ItemForeignMod { ref mut attrs, .. }) => attrs,
        Impl(ItemImpl { ref mut attrs, .. }) => attrs,
        Macro(ItemMacro { ref mut attrs, .. }) => attrs,
        Mod(ItemMod { ref mut attrs, .. }) => attrs,
        Static(ItemStatic { ref mut attrs, .. }) => attrs,
        Struct(ItemStruct { ref mut attrs, .. }) => attrs,
        Trait(ItemTrait { ref mut attrs, .. }) => attrs,
        TraitAlias(ItemTraitAlias { ref mut attrs, .. }) => attrs,
        Type(ItemType { ref mut attrs, .. }) => attrs,
        Union(ItemUnion { ref mut attrs, .. }) => attrs,
        Use(ItemUse { ref mut attrs, .. }) => attrs,
        Verbatim(TokenStream { .. }) => return None,
        _ => return None,
    })
}

/// Unwrap a layer of parenthesization from an Expr, if present
pub(crate) fn unparen(expr: &Expr) -> &Expr {
    match *expr {
        Expr::Paren(ExprParen { ref expr, .. }) => expr,
        _ => expr,
    }
}

/// Declarations can be converted into a normal item, or into a foreign item.
/// Foreign items are called out specially because we'll combine all of them
/// into a single extern block at the end of translation.
#[derive(Debug)]
pub enum ConvertedDecl {
    /// [`ForeignItem`] is large (472 bytes), so [`Box`] it.
    ForeignItem(Box<ForeignItem>), // would be 472 bytes
    Item(Box<Item>),       // 24 bytes
    Items(Vec<Box<Item>>), // 24 bytes
    NoItem,
}

struct ConvertedVariable {
    pub ty: Box<Type>,
    pub mutbl: Mutability,
    pub init: TranslationResult<WithStmts<Box<Expr>>>,
}

struct ConvertedFunctionParam {
    pub ty: Box<Type>,
    pub mutbl: Mutability,
}

impl<'c> Translation<'c> {
    pub fn new(
        mut ast_context: TypedAstContext,
        tcfg: &'c TranspilerConfig,
        main_file: &Path,
    ) -> Self {
        let comment_context = CommentContext::new(&mut ast_context);
        let mut type_converter = TypeConverter::new();

        if tcfg.translate_valist {
            type_converter.translate_valist = true
        }

        let main_file = ast_context.find_file_id(main_file).unwrap_or(0);
        let items = indexmap! {main_file => ItemStore::new()};

        Translation {
            features: RefCell::new(IndexSet::new()),
            type_converter: RefCell::new(type_converter),
            ast_context,
            tcfg,
            renamer: RefCell::new(Renamer::new(&[
                // Keywords currently in use
                "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false",
                "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut",
                "pub", "ref", "return", "Self", "self", "static", "struct", "super", "trait",
                "true", "type", "unsafe", "use", "where", "while", "dyn",
                // Keywords reserved for future use
                "abstract", "alignof", "become", "box", "do", "final", "macro", "offsetof",
                "override", "priv", "proc", "pure", "sizeof", "typeof", "unsized", "virtual",
                "async", "try", "yield", // Prevent use for other reasons
                "main",  // prelude names
                "drop", "Some", "None", "Ok", "Err",
            ])),
            zero_inits: RefCell::new(IndexMap::new()),
            function_context: RefCell::new(FuncContext::new()),
            potential_flexible_array_members: RefCell::new(IndexSet::new()),
            macro_expansions: RefCell::new(IndexMap::new()),
            deferred_imports: RefCell::new(Vec::new()),
            comment_context,
            comment_store: RefCell::new(CommentStore::new()),
            spans: HashMap::new(),
            sectioned_static_initializers: RefCell::new(Vec::new()),
            items: RefCell::new(items),
            mod_names: RefCell::new(IndexMap::new()),
            main_file,
            extern_crates: RefCell::new(IndexSet::new()),
            cur_file: Default::default(),
        }
    }

    fn use_crate(&self, extern_crate: ExternCrate) {
        self.extern_crates.borrow_mut().insert(extern_crate);
    }

    pub fn cur_file(&self) -> FileId {
        self.cur_file.get().unwrap_or(self.main_file)
    }

    fn with_cur_file_item_store<F, T>(&self, f: F) -> T
    where
        F: FnOnce(&mut ItemStore) -> T,
    {
        let mut item_stores = self.items.borrow_mut();
        let item_store = item_stores.entry(Self::cur_file(self)).or_default();
        f(item_store)
    }

    /// Called when translation makes use of a language feature that will require a feature-gate.
    pub fn use_feature(&self, feature: &'static str) {
        self.features.borrow_mut().insert(feature);
    }

    pub fn get_pragmas(&self) -> PragmaVec {
        let mut features = vec![];
        features.extend(self.features.borrow().iter());
        features.extend(self.type_converter.borrow().features_used());
        let mut pragmas: PragmaVec = vec![(
            "allow",
            vec![
                "non_upper_case_globals",
                "non_camel_case_types",
                "non_snake_case",
                "dead_code",
                "unused_mut",
                "unused_assignments",
            ],
        )];
        if self.tcfg.cross_checks {
            features.append(&mut vec!["plugin"]);
            pragmas.push(("cross_check", vec!["yes"]));
        }

        if self.features.borrow().contains("register_tool") {
            pragmas.push(("register_tool", vec!["c2rust"]));
        }

        if !features.is_empty() {
            pragmas.push(("feature", features));
        }
        pragmas
    }

    // This node should _never_ show up in the final generated code. This is an easy way to notice
    // if it does.
    pub fn panic_or_err(&self, msg: &str) -> Box<Expr> {
        self.panic_or_err_helper(msg, self.tcfg.panic_on_translator_failure)
    }

    pub fn panic(&self, msg: &str) -> Box<Expr> {
        self.panic_or_err_helper(msg, true)
    }

    fn panic_or_err_helper(&self, msg: &str, panic: bool) -> Box<Expr> {
        let macro_name = if panic { "panic" } else { "compile_error" };
        let macro_msg = vec![TokenTree::Literal(proc_macro2::Literal::string(msg))]
            .into_iter()
            .collect::<TokenStream>();
        mk().mac_expr(mk().mac(
            mk().path(vec![macro_name]),
            macro_msg,
            MacroDelimiter::Paren(Default::default()),
        ))
    }

    fn mk_cross_check(&self, mk: Builder, args: Vec<&str>) -> Builder {
        if self.tcfg.cross_checks {
            mk.call_attr("cross_check", args)
        } else {
            mk
        }
    }

    fn static_initializer_is_unsafe(&self, expr_id: Option<CExprId>, qty: CQualTypeId) -> bool {
        // SIMD types are always unsafe in statics
        match self.ast_context.resolve_type(qty.ctype).kind {
            CTypeKind::Vector(..) => return true,
            CTypeKind::ConstantArray(ctype, ..) => {
                let kind = &self.ast_context.resolve_type(ctype).kind;

                if let CTypeKind::Vector(..) = kind {
                    return true;
                }
            }
            _ => {}
        }

        // Get the initializer if there is one
        let expr_id = match expr_id {
            Some(expr_id) => expr_id,
            None => return false,
        };

        // Look for code which can only be translated unsafely
        let iter = DFExpr::new(&self.ast_context, expr_id.into());

        for i in iter {
            let expr_id = match i {
                SomeId::Expr(expr_id) => expr_id,
                _ => unreachable!("Found static initializer type other than expr"),
            };

            use CExprKind::*;
            match self.ast_context[expr_id].kind {
                DeclRef(_, _, LRValue::LValue) => return true,
                ImplicitCast(_, _, cast_kind, _, _) | ExplicitCast(_, _, cast_kind, _, _) => {
                    use CastKind::*;
                    match cast_kind {
                        IntegralToPointer | FunctionToPointerDecay | PointerToIntegral => {
                            return true;
                        }
                        _ => {}
                    }
                }
                _ => {}
            }
        }

        false
    }

    /// The purpose of this function is to decide on whether or not a static initializer's
    /// translation is able to be compiled as a valid rust static initializer
    fn static_initializer_is_uncompilable(
        &self,
        expr_id: Option<CExprId>,
        qtype: CQualTypeId,
    ) -> bool {
        use crate::c_ast::BinOp::{Add, Divide, Modulus, Multiply, Subtract};
        use crate::c_ast::CastKind::{IntegralToPointer, PointerToIntegral};
        use crate::c_ast::UnOp::{AddressOf, Negate};

        let expr_id = match expr_id {
            Some(expr_id) => expr_id,
            None => return false,
        };

        // The f128 crate doesn't currently provide a way to const initialize
        // values, except for common mathematical constants
        if let CTypeKind::LongDouble = self.ast_context[qtype.ctype].kind {
            return true;
        }

        let iter = DFExpr::new(&self.ast_context, expr_id.into());

        for i in iter {
            let expr_id = match i {
                SomeId::Expr(expr_id) => expr_id,
                _ => unreachable!("Found static initializer type other than expr"),
            };

            use CExprKind::*;
            match self.ast_context[expr_id].kind {
                // Technically we're being conservative here, but it's only the most
                // contrived array indexing initializers that would be accepted
                ArraySubscript(..) => return true,
                Member(..) => return true,

                Conditional(..) => return true,
                Unary(typ, Negate, _, _) => {
                    if self
                        .ast_context
                        .resolve_type(typ.ctype)
                        .kind
                        .is_unsigned_integral_type()
                    {
                        return true;
                    }
                }

                // PointerToIntegral is no longer allowed, const-eval throws an
                // error: "pointer-to-integer cast" needs an rfc before being
                // allowed inside constants
                ImplicitCast(_, _, PointerToIntegral, _, _)
                | ExplicitCast(_, _, PointerToIntegral, _, _) => return true,

                Binary(typ, op, _, _, _, _) => {
                    let problematic_op = matches!(op, Add | Subtract | Multiply | Divide | Modulus);

                    if problematic_op {
                        let k = &self.ast_context.resolve_type(typ.ctype).kind;
                        if k.is_unsigned_integral_type() || k.is_pointer() {
                            return true;
                        }
                    }
                }
                Unary(_, AddressOf, expr_id, _) => {
                    if let Member(_, expr_id, _, _, _) = self.ast_context[expr_id].kind {
                        if let DeclRef(..) = self.ast_context[expr_id].kind {
                            return true;
                        }
                    }
                }
                InitList(qtype, _, _, _) => {
                    let ty = &self.ast_context.resolve_type(qtype.ctype).kind;

                    if let &CTypeKind::Struct(decl_id) = ty {
                        let decl = &self.ast_context[decl_id].kind;

                        if let CDeclKind::Struct {
                            fields: Some(fields),
                            ..
                        } = decl
                        {
                            for field_id in fields {
                                let field_decl = &self.ast_context[*field_id].kind;

                                if let CDeclKind::Field {
                                    bitfield_width: Some(_),
                                    ..
                                } = field_decl
                                {
                                    return true;
                                }
                            }
                        }
                    }
                }
                ImplicitCast(qtype, _, IntegralToPointer, _, _)
                | ExplicitCast(qtype, _, IntegralToPointer, _, _) => {
                    if let CTypeKind::Pointer(qtype) =
                        self.ast_context.resolve_type(qtype.ctype).kind
                    {
                        if let CTypeKind::Function(..) =
                            self.ast_context.resolve_type(qtype.ctype).kind
                        {
                            return true;
                        }
                    }
                }
                _ => {}
            }
        }

        false
    }

    fn add_static_initializer_to_section(
        &self,
        name: &str,
        typ: CQualTypeId,
        init: &mut Box<Expr>,
    ) -> TranslationResult<()> {
        let mut default_init = self.implicit_default_expr(typ.ctype, true)?.to_expr();

        std::mem::swap(init, &mut default_init);

        let root_lhs_expr = mk().path_expr(vec![name]);
        let assign_expr = mk().assign_expr(root_lhs_expr, default_init);
        let stmt = mk().expr_stmt(assign_expr);

        self.sectioned_static_initializers.borrow_mut().push(stmt);

        Ok(())
    }

    fn generate_global_static_init(&mut self) -> (Box<Item>, Box<Item>) {
        // If we don't want to consume self.sectioned_static_initializers for some reason, we could clone the vec
        let sectioned_static_initializers = self.sectioned_static_initializers.replace(Vec::new());

        let fn_name = self
            .renamer
            .borrow_mut()
            .pick_name("run_static_initializers");
        let fn_ty = ReturnType::Default;
        let fn_decl = mk().fn_decl(fn_name.clone(), vec![], None, fn_ty.clone());
        let fn_bare_decl = (vec![], None, fn_ty);
        let fn_block = mk().block(sectioned_static_initializers);
        let fn_attributes = self.mk_cross_check(mk(), vec!["none"]);
        let fn_item = fn_attributes
            .unsafe_()
            .extern_("C")
            .fn_item(fn_decl, fn_block);

        let static_attributes = mk()
            .single_attr("used")
            .call_attr(
                "cfg_attr",
                vec![
                    mk().meta_namevalue("target_os", "linux"),
                    mk().meta_namevalue("link_section", ".init_array"),
                ],
            )
            .call_attr(
                "cfg_attr",
                vec![
                    mk().meta_namevalue("target_os", "windows"),
                    mk().meta_namevalue("link_section", ".CRT$XIB"),
                ],
            )
            .call_attr(
                "cfg_attr",
                vec![
                    mk().meta_namevalue("target_os", "macos"),
                    mk().meta_namevalue("link_section", "__DATA,__mod_init_func"),
                ],
            );
        let static_array_size = mk().lit_expr(mk().int_unsuffixed_lit(1));
        let static_ty = mk().array_ty(
            mk().unsafe_().extern_("C").barefn_ty(fn_bare_decl),
            static_array_size,
        );
        let static_val = mk().array_expr(vec![mk().path_expr(vec![fn_name])]);
        let static_item = static_attributes.static_item("INIT_ARRAY", static_ty, static_val);

        (fn_item, static_item)
    }

    fn convert_decl(&self, ctx: ExprContext, decl_id: CDeclId) -> TranslationResult<ConvertedDecl> {
        let decl = self
            .ast_context
            .get_decl(&decl_id)
            .ok_or_else(|| format_err!("Missing decl {:?}", decl_id))?;

        let mut span = self
            .get_span(SomeId::Decl(decl_id))
            .unwrap_or_else(Span::call_site);

        use CDeclKind::*;
        match decl.kind {
            Struct { fields: None, .. }
            | Union { fields: None, .. }
            | Enum {
                integral_type: None,
                ..
            } => {
                self.use_feature("extern_types");
                let name = self
                    .type_converter
                    .borrow()
                    .resolve_decl_name(decl_id)
                    .unwrap();

                let extern_item = mk().span(span).pub_().ty_foreign_item(name);
                Ok(ConvertedDecl::ForeignItem(extern_item))
            }

            Struct {
                fields: Some(ref fields),
                is_packed,
                manual_alignment,
                max_field_alignment,
                platform_byte_size,
                ..
            } => self.convert_struct(
                decl_id,
                span,
                fields,
                is_packed,
                platform_byte_size,
                manual_alignment,
                max_field_alignment,
            ),

            Union {
                fields: Some(ref fields),
                is_packed,
                ..
            } => {
                let name = self
                    .type_converter
                    .borrow()
                    .resolve_decl_name(decl_id)
                    .unwrap();

                let mut field_syns = vec![];
                for &x in fields {
                    let field_decl = self.ast_context.index(x);
                    match field_decl.kind {
                        CDeclKind::Field { ref name, typ, .. } => {
                            let name = self
                                .type_converter
                                .borrow_mut()
                                .declare_field_name(decl_id, x, name);
                            let typ = self.convert_type(typ.ctype)?;
                            field_syns.push(mk().pub_().struct_field(name, typ))
                        }
                        _ => {
                            return Err(TranslationError::generic(
                                "Found non-field in record field list",
                            ));
                        }
                    }
                }

                let mut repr = vec!["C"];
                if is_packed {
                    repr.push("packed");
                }

                Ok(if field_syns.is_empty() {
                    // Empty unions are a GNU extension, but Rust doesn't allow empty unions.
                    ConvertedDecl::Item(
                        mk().span(span)
                            .pub_()
                            .call_attr("derive", vec!["Copy", "Clone"])
                            .call_attr("repr", repr)
                            .struct_item(name, vec![], false),
                    )
                } else {
                    ConvertedDecl::Item(
                        mk().span(span)
                            .pub_()
                            .call_attr("derive", vec!["Copy", "Clone"])
                            .call_attr("repr", repr)
                            .union_item(name, field_syns),
                    )
                })
            }

            Field { .. } => Err(TranslationError::generic(
                "Field declarations should be handled inside structs/unions",
            )),

            Enum {
                integral_type: Some(integral_type),
                ..
            } => {
                let enum_name = &self
                    .type_converter
                    .borrow()
                    .resolve_decl_name(decl_id)
                    .expect("Enums should already be renamed");
                let ty = self.convert_type(integral_type.ctype)?;
                Ok(ConvertedDecl::Item(
                    mk().span(span).pub_().type_item(enum_name, ty),
                ))
            }

            EnumConstant { value, .. } => {
                let name = self
                    .renamer
                    .borrow_mut()
                    .get(&decl_id)
                    .expect("Enum constant not named");
                let enum_id = self.ast_context.parents[&decl_id];
                let enum_name = self
                    .type_converter
                    .borrow()
                    .resolve_decl_name(enum_id)
                    .expect("Enums should already be renamed");
                self.add_import(enum_id, &enum_name);

                let ty = mk().path_ty(vec![enum_name]);
                let val = match value {
                    ConstIntExpr::I(value) => signed_int_expr(value),
                    ConstIntExpr::U(value) => mk().lit_expr(mk().int_unsuffixed_lit(value as u128)),
                };

                Ok(ConvertedDecl::Item(
                    mk().span(span).pub_().const_item(name, ty, val),
                ))
            }

            // We can allow non top level function declarations (i.e. extern
            // declarations) without any problem. Clang doesn't support nested
            // functions, so we will never see nested function definitions.
            Function {
                is_global,
                is_inline,
                is_extern,
                typ,
                ref name,
                ref parameters,
                body,
                ref attrs,
                ..
            } => {
                let new_name = &self
                    .renamer
                    .borrow()
                    .get(&decl_id)
                    .expect("Functions should already be renamed");

                if self.import_simd_function(new_name)? {
                    return Ok(ConvertedDecl::NoItem);
                }

                let (ret, is_variadic): (Option<CQualTypeId>, bool) =
                    match self.ast_context.resolve_type(typ).kind {
                        CTypeKind::Function(ret, _, is_var, is_noreturn, _) => {
                            (if is_noreturn { None } else { Some(ret) }, is_var)
                        }
                        ref k => {
                            return Err(format_err!(
                                "Type of function {:?} was not a function type, got {:?}",
                                decl_id,
                                k
                            )
                            .into());
                        }
                    };

                let mut args: Vec<(CDeclId, String, CQualTypeId)> = vec![];
                for param_id in parameters {
                    if let CDeclKind::Variable { ref ident, typ, .. } =
                        self.ast_context.index(*param_id).kind
                    {
                        args.push((*param_id, ident.clone(), typ))
                    } else {
                        return Err(TranslationError::generic(
                            "Parameter is not variable declaration",
                        ));
                    }
                }

                let is_main = self.ast_context.c_main == Some(decl_id);

                let converted_function = self.convert_function(
                    ctx,
                    span,
                    is_global,
                    is_inline,
                    is_main,
                    is_variadic,
                    is_extern,
                    new_name,
                    name,
                    &args,
                    ret,
                    body,
                    attrs,
                );

                converted_function.or_else(|e| match self.tcfg.replace_unsupported_decls {
                    ReplaceMode::Extern if body.is_none() => self.convert_function(
                        ctx,
                        span,
                        is_global,
                        false,
                        is_main,
                        is_variadic,
                        is_extern,
                        new_name,
                        name,
                        &args,
                        ret,
                        None,
                        attrs,
                    ),
                    _ => Err(e),
                })
            }

            Typedef { ref typ, .. } => {
                let new_name = &self
                    .type_converter
                    .borrow()
                    .resolve_decl_name(decl_id)
                    .unwrap();

                if self.import_simd_typedef(new_name)? {
                    return Ok(ConvertedDecl::NoItem);
                }

                // We can't typedef to std::ffi::VaList, since the typedef won't
                // have explicit lifetime params which VaList
                // requires. Temporarily disable translation of valist to Rust
                // native VaList.
                let translate_valist = mem::replace(
                    &mut self.type_converter.borrow_mut().translate_valist,
                    false,
                );
                let ty = self.convert_type(typ.ctype)?;
                self.type_converter.borrow_mut().translate_valist = translate_valist;

                Ok(ConvertedDecl::Item(
                    mk().span(span).pub_().type_item(new_name, ty),
                ))
            }

            // Externally-visible variable without initializer (definition elsewhere)
            Variable {
                is_externally_visible: true,
                has_static_duration,
                has_thread_duration,
                is_defn: false,
                ref ident,
                initializer,
                typ,
                ref attrs,
                ..
            } => {
                assert!(
                    has_static_duration || has_thread_duration,
                    "An extern variable must be static or thread-local"
                );
                assert!(
                    initializer.is_none(),
                    "An extern variable that isn't a definition can't have an initializer"
                );

                if has_thread_duration {
                    self.use_feature("thread_local");
                }

                let new_name = self
                    .renamer
                    .borrow()
                    .get(&decl_id)
                    .expect("Variables should already be renamed");
                let ConvertedVariable { ty, mutbl, init: _ } =
                    self.convert_variable(ctx.static_(), None, typ)?;
                let mut extern_item = mk_linkage(true, &new_name, ident)
                    .span(span)
                    .set_mutbl(mutbl);

                // When putting extern statics into submodules, they need to be public to be accessible
                if self.tcfg.reorganize_definitions {
                    extern_item = extern_item.pub_();
                };

                if has_thread_duration {
                    extern_item = extern_item.single_attr("thread_local");
                }

                for attr in attrs {
                    extern_item = match attr {
                        c_ast::Attribute::Alias(aliasee) => {
                            extern_item.str_attr("link_name", aliasee)
                        }
                        _ => continue,
                    };
                }

                Ok(ConvertedDecl::ForeignItem(
                    extern_item.static_foreign_item(&new_name, ty),
                ))
            }

            // Static-storage or thread-local variable with initializer (definition here)
            Variable {
                has_static_duration,
                has_thread_duration,
                is_externally_visible,
                ref ident,
                initializer,
                typ,
                ref attrs,
                ..
            } if has_static_duration || has_thread_duration => {
                if has_thread_duration {
                    self.use_feature("thread_local");
                }

                let new_name = &self
                    .renamer
                    .borrow()
                    .get(&decl_id)
                    .expect("Variables should already be renamed");

                // Collect problematic static initializers and offload them to sections for the linker
                // to initialize for us
                let (ty, init) = if self.static_initializer_is_uncompilable(initializer, typ) {
                    // Note: We don't pass has_static_duration through here. Extracted initializers
                    // are run outside of the static initializer.
                    let ConvertedVariable { ty, mutbl: _, init } =
                        self.convert_variable(ctx.not_static(), initializer, typ)?;

                    let mut init = init?.to_expr();

                    let comment = String::from("// Initialized in run_static_initializers");
                    let comment_pos = if span.is_dummy() {
                        None
                    } else {
                        Some(span.lo())
                    };
                    span = self
                        .comment_store
                        .borrow_mut()
                        .extend_existing_comments(
                            &[comment],
                            comment_pos,
                            //CommentStyle::Isolated,
                        )
                        .map(pos_to_span)
                        .unwrap_or(span);

                    self.add_static_initializer_to_section(new_name, typ, &mut init)?;

                    (ty, init)
                } else {
                    let ConvertedVariable { ty, mutbl: _, init } =
                        self.convert_variable(ctx.static_(), initializer, typ)?;
                    let mut init = init?;
                    // TODO: Replace this by relying entirely on
                    // WithStmts.is_unsafe() of the translated variable
                    if self.static_initializer_is_unsafe(initializer, typ) {
                        init.set_unsafe()
                    }
                    let init = init.to_unsafe_pure_expr().ok_or_else(|| {
                        format_err!("Expected no side-effects in static initializer")
                    })?;

                    (ty, init)
                };

                let static_def = if is_externally_visible {
                    mk_linkage(false, new_name, ident).pub_().extern_("C")
                } else if self.cur_file.get().is_some() {
                    mk().pub_()
                } else {
                    mk()
                };

                // Force mutability due to the potential for raw pointers occurring in the type
                // and because we may be assigning to these variables in the external initializer
                let mut static_def = static_def.span(span).mutbl();
                if has_thread_duration {
                    static_def = static_def.single_attr("thread_local");
                }

                // Add static attributes
                for attr in attrs {
                    static_def = match attr {
                        c_ast::Attribute::Used => static_def.single_attr("used"),
                        c_ast::Attribute::Section(name) => {
                            static_def.str_attr("link_section", name)
                        }
                        _ => continue,
                    }
                }

                Ok(ConvertedDecl::Item(
                    static_def.static_item(new_name, ty, init),
                ))
            }

            Variable { .. } => Err(TranslationError::generic(
                "This should be handled in 'convert_decl_stmt'",
            )),

            MacroObject { .. } => {
                let name = self
                    .renamer
                    .borrow_mut()
                    .get(&decl_id)
                    .expect("Macro object not named");

                trace!(
                    "Expanding macro {:?}: {:?}",
                    decl_id,
                    self.ast_context[decl_id]
                );

                let maybe_replacement = self.recreate_const_macro_from_expansions(
                    ctx.set_const(true).set_expanding_macro(decl_id),
                    &self.ast_context.macro_expansions[&decl_id],
                );

                match maybe_replacement {
                    Ok((replacement, ty)) => {
                        trace!("  to {:?}", replacement);

                        let expansion = MacroExpansion { ty };
                        self.macro_expansions
                            .borrow_mut()
                            .insert(decl_id, Some(expansion));
                        let ty = self.convert_type(ty)?;

                        Ok(ConvertedDecl::Item(mk().span(span).pub_().const_item(
                            name,
                            ty,
                            replacement,
                        )))
                    }
                    Err(e) => {
                        self.macro_expansions.borrow_mut().insert(decl_id, None);
                        info!("Could not expand macro {}: {}", name, e);
                        Ok(ConvertedDecl::NoItem)
                    }
                }
            }

            // We aren't doing anything with the definitions of function-like
            // macros yet.
            MacroFunction { .. } => Ok(ConvertedDecl::NoItem),

            // Do not translate non-canonical decls. They will be translated at
            // their canonical declaration.
            NonCanonicalDecl { .. } => Ok(ConvertedDecl::NoItem),

            StaticAssert { .. } => {
                warn!("ignoring static assert during translation");
                Ok(ConvertedDecl::NoItem)
            }
        }
    }

    /// Determine if we're able to convert this const macro expansion.
    fn can_convert_const_macro_expansion(&self, expr_id: CExprId) -> TranslationResult<()> {
        match self.tcfg.translate_const_macros {
            TranslateMacros::None => Err(format_err!("translate_const_macros is None"))?,
            TranslateMacros::Conservative => {
                // TODO We still allow `CExprKind::ExplicitCast`s
                // even though they're broken (see #853).

                // This is a top-down, pessimistic/conservative analysis.
                // This is somewhat duplicative of `fn convert_expr` simply checking
                // `ExprContext::is_const` and returning errors where the expr is not `const`,
                // which is an non-conservative analysis scattered across all of the `fn convert_*`s.
                // That's what's done for `TranslateMacros::Experimental`,
                // as opposed to the conservative analysis done here for `TranslateMacros::Conservative`.
                // When the conservative analysis is incomplete,
                // it won't translate the macro, but the result will compile.
                // But when the non-conservative analysis is incomplete,
                // the resulting code may not transpile,
                // which is why the conservative analysis is used for `TranslateMacros::Conservative`.
                if !self.ast_context.is_const_expr(expr_id) {
                    Err(format_err!("non-const expr {expr_id:?}"))?;
                }
                Ok(())
            }
            TranslateMacros::Experimental => Ok(()),
        }
    }

    /// Given all of the expansions of a const macro,
    /// try to recreate a Rust `const` translation
    /// that is equivalent to every expansion.
    ///
    /// This may fail, in which case we simply don't emit a `const`
    /// and leave all of the expansions as fully inlined
    /// instead of referencing this `const`.
    ///
    /// For example, if the types of the macro expansion have no common type,
    /// which is required for a Rust `const` but not a C const macro,
    /// this can fail.  Or there could just be a feature we don't yet support.
    fn recreate_const_macro_from_expansions(
        &self,
        ctx: ExprContext,
        expansions: &[CExprId],
    ) -> TranslationResult<(Box<Expr>, CTypeId)> {
        let (val, ty) = expansions
            .iter()
            .try_fold::<Option<(WithStmts<Box<Expr>>, CTypeId)>, _, _>(None, |canonical, &id| {
                self.can_convert_const_macro_expansion(id)?;

                let ty = self.ast_context[id]
                    .kind
                    .get_type()
                    .ok_or_else(|| format_err!("Invalid expression type"))?;
                let expr = self.convert_expr(ctx, id, None)?;

                // Join ty and cur_ty to the smaller of the two types. If the
                // types are not cast-compatible, abort the fold.
                let ty_kind = self.ast_context.resolve_type(ty).kind.clone();
                if let Some((canon_val, canon_ty)) = canonical {
                    let canon_ty_kind = self.ast_context.resolve_type(canon_ty).kind.clone();
                    if let Some(smaller_ty) =
                        CTypeKind::smaller_compatible_type(canon_ty_kind.clone(), ty_kind)
                    {
                        if smaller_ty == canon_ty_kind {
                            Ok(Some((canon_val, canon_ty)))
                        } else {
                            Ok(Some((expr, ty)))
                        }
                    } else {
                        Err(format_err!("Not all macro expansions are compatible types"))
                    }
                } else {
                    Ok(Some((expr, ty)))
                }
            })?
            .ok_or_else(|| format_err!("Could not find a valid type for macro"))?;

        val.to_unsafe_pure_expr()
            .map(|val| (val, ty))
            .ok_or_else(|| TranslationError::generic("Macro expansion is not a pure expression"))

        // TODO: Validate that all replacements are equivalent and pick the most
        // common type to minimize casts.
    }

    fn convert_function(
        &self,
        ctx: ExprContext,
        span: Span,
        is_global: bool,
        is_inline: bool,
        is_main: bool,
        is_variadic: bool,
        is_extern: bool,
        new_name: &str,
        name: &str,
        arguments: &[(CDeclId, String, CQualTypeId)],
        return_type: Option<CQualTypeId>,
        body: Option<CStmtId>,
        attrs: &IndexSet<c_ast::Attribute>,
    ) -> TranslationResult<ConvertedDecl> {
        self.function_context.borrow_mut().enter_new(name);

        self.with_scope(|| {
            let mut args: Vec<FnArg> = vec![];

            // handle regular (non-variadic) arguments
            for &(decl_id, ref var, typ) in arguments {
                let ConvertedFunctionParam { ty, mutbl } = self.convert_function_param(ctx, typ)?;

                let pat = if var.is_empty() {
                    mk().wild_pat()
                } else {
                    // extern function declarations don't support/require mut patterns
                    let mutbl = if body.is_none() {
                        Mutability::Immutable
                    } else {
                        mutbl
                    };

                    let new_var = self
                        .renamer
                        .borrow_mut()
                        .insert(decl_id, var.as_str())
                        .unwrap_or_else(|| {
                            panic!(
                                "Failed to insert argument '{}' while converting '{}'",
                                var, name
                            )
                        });

                    mk().set_mutbl(mutbl).ident_pat(new_var)
                };

                args.push(mk().arg(ty, pat))
            }

            let variadic = if is_variadic {
                // function definitions
                let mut builder = mk();
                let arg_va_list_name = if let Some(body_id) = body {
                    // FIXME: detect mutability requirements.
                    builder = builder.set_mutbl(Mutability::Mutable);
                    Some(self.register_va_decls(body_id))
                } else {
                    None
                };

                Some(builder.variadic_arg(arg_va_list_name))
            } else {
                None
            };

            // handle return type
            let ret = match return_type {
                Some(return_type) => self.convert_type(return_type.ctype)?,
                None => mk().never_ty(),
            };
            let is_void_ret = return_type
                .map(|qty| self.ast_context[qty.ctype].kind == CTypeKind::Void)
                .unwrap_or(false);

            // If a return type is void, we should instead omit the unit type return,
            // -> (), to be more idiomatic
            let ret = if is_void_ret {
                ReturnType::Default
            } else {
                ReturnType::Type(Default::default(), ret)
            };

            let decl = mk().fn_decl(new_name, args, variadic, ret);

            if let Some(body) = body {
                // Translating an actual function

                let ret = match return_type {
                    Some(return_type) => {
                        let ret_type_id: CTypeId =
                            self.ast_context.resolve_type_id(return_type.ctype);
                        if let CTypeKind::Void = self.ast_context.index(ret_type_id).kind {
                            cfg::ImplicitReturnType::Void
                        } else if is_main {
                            cfg::ImplicitReturnType::Main
                        } else {
                            cfg::ImplicitReturnType::NoImplicitReturnType
                        }
                    }
                    _ => cfg::ImplicitReturnType::Void,
                };

                let mut body_stmts = vec![];
                for &(_, _, typ) in arguments {
                    body_stmts.append(&mut self.compute_variable_array_sizes(ctx, typ.ctype)?);
                }

                let body_ids = match self.ast_context.index(body).kind {
                    CStmtKind::Compound(ref stmts) => stmts,
                    _ => panic!("function body expects to be a compound statement"),
                };
                let mut converted_body =
                    self.convert_function_body(ctx, name, body_ids, return_type, ret)?;

                // If `alloca` was used in the function body, include a variable to hold the
                // allocations.
                if let Some(alloca_allocations_name) = self
                    .function_context
                    .borrow_mut()
                    .alloca_allocations_name
                    .take()
                {
                    // let mut alloca_allocations: Vec<Vec<u8>> = Vec::new();
                    let inner_vec = mk().path_ty(vec![mk().path_segment_with_args(
                        "Vec",
                        mk().angle_bracketed_args(vec![mk().ident_ty("u8")]),
                    )]);
                    let outer_vec = mk().path_ty(vec![mk().path_segment_with_args(
                        "Vec",
                        mk().angle_bracketed_args(vec![inner_vec]),
                    )]);
                    let alloca_allocations_stmt = mk().local_stmt(Box::new(mk().local(
                        mk().mutbl().ident_pat(alloca_allocations_name),
                        Some(outer_vec),
                        Some(mk().call_expr(mk().path_expr(vec!["Vec", "new"]), vec![])),
                    )));

                    body_stmts.push(alloca_allocations_stmt);
                }

                body_stmts.append(&mut converted_body);
                let mut block = stmts_block(body_stmts);
                if let Some(span) = self.get_span(SomeId::Stmt(body)) {
                    block.set_span(span);
                }

                // c99 extern inline functions should be pub, but not gnu_inline attributed
                // extern inlines, which become subject to their gnu89 visibility (private)
                let is_extern_inline =
                    is_inline && is_extern && !attrs.contains(&c_ast::Attribute::GnuInline);

                // Only add linkage attributes if the function is `extern`
                let mut mk_ = if is_main {
                    // Cross-check this function as if it was called `main`
                    // FIXME: pass in a vector of NestedMetaItem elements,
                    // but strings have to do for now
                    self.mk_cross_check(mk(), vec!["entry(djb2=\"main\")", "exit(djb2=\"main\")"])
                } else if (is_global && !is_inline) || is_extern_inline {
                    mk_linkage(false, new_name, name).extern_("C").pub_()
                } else if self.cur_file.get().is_some() {
                    mk().extern_("C").pub_()
                } else {
                    mk().extern_("C")
                };

                for attr in attrs {
                    mk_ = match attr {
                        c_ast::Attribute::AlwaysInline => mk_.call_attr("inline", vec!["always"]),
                        c_ast::Attribute::Cold => mk_.single_attr("cold"),
                        c_ast::Attribute::NoInline => mk_.call_attr("inline", vec!["never"]),
                        _ => continue,
                    };
                }

                // If this function is just a regular inline
                if is_inline && !attrs.contains(&c_ast::Attribute::AlwaysInline) {
                    mk_ = mk_.single_attr("inline");

                    // * In C99, a function defined inline will never, and a function defined extern
                    //   inline will always, emit an externally visible function.
                    // * If a non-static function is declared inline, then it must be defined in the
                    //   same translation unit. The inline definition that does not use extern is
                    //   not externally visible and does not prevent other translation units from
                    //   defining the same function. This makes the inline keyword an alternative to
                    //   static for defining functions inside header files, which may be included in
                    //   multiple translation units of the same program.
                    // * always_inline implies inline -
                    //   https://gcc.gnu.org/ml/gcc-help/2007-01/msg00051.html
                    //   even if the `inline` keyword isn't present
                    // * gnu_inline instead applies gnu89 rules. extern inline will not emit an
                    //   externally visible function.
                    if is_global && is_extern && !attrs.contains(&c_ast::Attribute::GnuInline) {
                        self.use_feature("linkage");
                        // ensures that public inlined rust function can be used in other modules
                        mk_ = mk_.str_attr("linkage", "external");
                    }
                    // NOTE: it does not seem necessary to have an else branch here that
                    // specifies internal linkage in all other cases due to name mangling by rustc.
                }

                Ok(ConvertedDecl::Item(
                    mk_.span(span).unsafe_().fn_item(decl, block),
                ))
            } else {
                // Translating an extern function declaration
                let mut mk_ = mk_linkage(true, new_name, name).span(span);

                // When putting extern fns into submodules, they need to be public to be accessible
                if self.tcfg.reorganize_definitions {
                    mk_ = mk_.pub_();
                };

                for attr in attrs {
                    mk_ = match attr {
                        c_ast::Attribute::Alias(aliasee) => mk_.str_attr("link_name", aliasee),
                        _ => continue,
                    };
                }

                let function_decl = mk_.fn_foreign_item(decl);

                Ok(ConvertedDecl::ForeignItem(function_decl))
            }
        })
    }

    pub fn convert_cfg(
        &self,
        name: &str,
        graph: cfg::Cfg<cfg::Label, cfg::StmtOrDecl>,
        store: cfg::DeclStmtStore,
        live_in: IndexSet<CDeclId>,
        cut_out_trailing_ret: bool,
    ) -> TranslationResult<Vec<Stmt>> {
        if self.tcfg.dump_function_cfgs {
            graph
                .dump_dot_graph(
                    &self.ast_context,
                    &store,
                    self.tcfg.dump_cfg_liveness,
                    self.tcfg.use_c_loop_info,
                    format!("{}_{}.dot", "cfg", name),
                )
                .expect("Failed to write CFG .dot file");
        }
        if self.tcfg.json_function_cfgs {
            graph
                .dump_json_graph(&store, format!("{}_{}.json", "cfg", name))
                .expect("Failed to write CFG .json file");
        }

        let (lifted_stmts, relooped) = cfg::relooper::reloop(
            graph,
            store,
            self.tcfg.simplify_structures,
            self.tcfg.use_c_loop_info,
            self.tcfg.use_c_multiple_info,
            live_in,
        );

        if self.tcfg.dump_structures {
            eprintln!("Relooped structures:");
            for s in &relooped {
                eprintln!("  {:#?}", s);
            }
        }

        let current_block_ident = self.renamer.borrow_mut().pick_name("current_block");
        let current_block = mk().ident_expr(&current_block_ident);
        let mut stmts: Vec<Stmt> = lifted_stmts;
        if cfg::structures::has_multiple(&relooped) {
            if self.tcfg.fail_on_multiple {
                panic!("Uses of `current_block' are illegal with `--fail-on-multiple'.");
            }

            let current_block_ty = if self.tcfg.debug_relooper_labels {
                mk().ref_lt_ty("static", mk().path_ty(vec!["str"]))
            } else {
                mk().path_ty(vec!["u64"])
            };

            let local = mk().local(
                mk().mutbl().ident_pat(current_block_ident),
                Some(current_block_ty),
                None,
            );
            stmts.push(mk().local_stmt(Box::new(local)))
        }

        stmts.extend(cfg::structures::structured_cfg(
            &relooped,
            &mut self.comment_store.borrow_mut(),
            current_block,
            self.tcfg.debug_relooper_labels,
            cut_out_trailing_ret,
        )?);
        Ok(stmts)
    }

    fn convert_function_body(
        &self,
        ctx: ExprContext,
        name: &str,
        body_ids: &[CStmtId],
        ret_ty: Option<CQualTypeId>,
        ret: cfg::ImplicitReturnType,
    ) -> TranslationResult<Vec<Stmt>> {
        // Function body scope
        self.with_scope(|| {
            let (graph, store) = cfg::Cfg::from_stmts(self, ctx, body_ids, ret, ret_ty)?;
            self.convert_cfg(name, graph, store, IndexSet::new(), true)
        })
    }

    /// Convert a C expression to a rust boolean expression
    pub fn convert_condition(
        &self,
        ctx: ExprContext,
        target: bool,
        cond_id: CExprId,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        let ty_id = self.ast_context[cond_id]
            .kind
            .get_type()
            .ok_or_else(|| format_err!("bad condition type"))?;

        let null_pointer_case =
            |negated: bool, ptr: CExprId| -> TranslationResult<WithStmts<Box<Expr>>> {
                let val = self.convert_expr(ctx.used().decay_ref(), ptr, None)?;
                let ptr_type = self.ast_context[ptr]
                    .kind
                    .get_type()
                    .ok_or_else(|| format_err!("bad pointer type for condition"))?;
                val.and_then(|e| {
                    Ok(WithStmts::new_val(
                        if self.ast_context.is_function_pointer(ptr_type) {
                            if negated {
                                mk().method_call_expr(e, "is_some", vec![])
                            } else {
                                mk().method_call_expr(e, "is_none", vec![])
                            }
                        } else {
                            // TODO: `pointer::is_null` becomes stably const in Rust 1.84.
                            if ctx.is_const {
                                return Err(format_translation_err!(
                                    None,
                                    "cannot check nullity of pointer in `const` context",
                                ));
                            }
                            let is_null = mk().method_call_expr(e, "is_null", vec![]);
                            if negated {
                                mk().unary_expr(UnOp::Not(Default::default()), is_null)
                            } else {
                                is_null
                            }
                        },
                    ))
                })
            };

        match self.ast_context[cond_id].kind {
            CExprKind::Binary(_, c_ast::BinOp::EqualEqual, null_expr, ptr, _, _)
                if self.ast_context.is_null_expr(null_expr) =>
            {
                null_pointer_case(!target, ptr)
            }

            CExprKind::Binary(_, c_ast::BinOp::EqualEqual, ptr, null_expr, _, _)
                if self.ast_context.is_null_expr(null_expr) =>
            {
                null_pointer_case(!target, ptr)
            }

            CExprKind::Binary(_, c_ast::BinOp::NotEqual, null_expr, ptr, _, _)
                if self.ast_context.is_null_expr(null_expr) =>
            {
                null_pointer_case(target, ptr)
            }

            CExprKind::Binary(_, c_ast::BinOp::NotEqual, ptr, null_expr, _, _)
                if self.ast_context.is_null_expr(null_expr) =>
            {
                null_pointer_case(target, ptr)
            }

            CExprKind::Unary(_, c_ast::UnOp::Not, subexpr_id, _) => {
                self.convert_condition(ctx, !target, subexpr_id)
            }

            _ => {
                // DecayRef could (and probably should) be Default instead of Yes here; however, as noted
                // in https://github.com/rust-lang/rust/issues/53772, you cant compare a reference (lhs) to
                // a ptr (rhs) (even though the reverse works!). We could also be smarter here and just
                // specify Yes for that particular case, given enough analysis.
                let val = self.convert_expr(ctx.used().decay_ref(), cond_id, None)?;
                val.result_map(|e| self.match_bool(ctx, target, ty_id, e))
            }
        }
    }

    /// Search for references to the given declaration in a value position
    /// inside the given expression. Uses of the declaration inside typeof
    /// operations are ignored because our translation will ignore them
    /// and use the computed types instead.
    fn has_decl_reference(&self, decl_id: CDeclId, expr_id: CExprId) -> bool {
        let mut iter = DFExpr::new(&self.ast_context, expr_id.into());
        while let Some(x) = iter.next() {
            match x {
                SomeId::Expr(e) => match self.ast_context[e].kind {
                    CExprKind::DeclRef(_, d, _) if d == decl_id => return true,
                    CExprKind::UnaryType(_, _, Some(_), _) => iter.prune(1),
                    _ => {}
                },
                SomeId::Type(t) => {
                    if let CTypeKind::TypeOfExpr(_) = self.ast_context[t].kind {
                        iter.prune(1);
                    }
                }
                _ => {}
            }
        }
        false
    }

    pub fn convert_decl_stmt_info(
        &self,
        ctx: ExprContext,
        decl_id: CDeclId,
    ) -> TranslationResult<cfg::DeclStmtInfo> {
        if let CDeclKind::Variable {
            ref ident,
            has_static_duration: true,
            is_externally_visible: false,
            is_defn: true,
            initializer,
            typ,
            ..
        } = self.ast_context.index(decl_id).kind
        {
            if self.static_initializer_is_uncompilable(initializer, typ) {
                let ident2 = self
                    .renamer
                    .borrow_mut()
                    .insert_root(decl_id, ident)
                    .ok_or_else(|| {
                        TranslationError::generic(
                            "Unable to rename function scoped static initializer",
                        )
                    })?;
                let ConvertedVariable { ty, mutbl: _, init } =
                    self.convert_variable(ctx.static_(), initializer, typ)?;
                let default_init = self.implicit_default_expr(typ.ctype, true)?.to_expr();
                let comment = String::from("// Initialized in run_static_initializers");
                let span = self
                    .comment_store
                    .borrow_mut()
                    .add_comments(&[comment])
                    .map(pos_to_span)
                    .unwrap_or_else(Span::call_site);
                let static_item = mk()
                    .span(span)
                    .mutbl()
                    .static_item(&ident2, ty, default_init);
                let mut init = init?;
                init.set_unsafe();
                let mut init = init.to_expr();

                self.add_static_initializer_to_section(&ident2, typ, &mut init)?;
                self.items.borrow_mut()[&self.main_file].add_item(static_item);

                return Ok(cfg::DeclStmtInfo::empty());
            }
        };

        match self.ast_context.index(decl_id).kind {
            CDeclKind::Variable {
                has_static_duration: false,
                has_thread_duration: false,
                is_externally_visible: false,
                is_defn,
                ref ident,
                initializer,
                typ,
                ..
            } => {
                assert!(
                    is_defn,
                    "Only local variable definitions should be extracted"
                );

                let rust_name = self
                    .renamer
                    .borrow_mut()
                    .insert(decl_id, ident)
                    .unwrap_or_else(|| panic!("Failed to insert variable '{}'", ident));

                if self.ast_context.is_va_list(typ.ctype) {
                    // translate `va_list` variables to `VaListImpl`s and omit the initializer.
                    let pat_mut = mk().mutbl().ident_pat(rust_name);
                    let ty = mk().abs_path_ty(vec!["core", "ffi", "VaListImpl"]);
                    let local_mut = mk().local(pat_mut, Some(ty), None);

                    return Ok(cfg::DeclStmtInfo::new(
                        vec![],                                     // decl
                        vec![],                                     // assign
                        vec![mk().local_stmt(Box::new(local_mut))], // decl_and_assign
                    ));
                }

                let has_self_reference = if let Some(expr_id) = initializer {
                    self.has_decl_reference(decl_id, expr_id)
                } else {
                    false
                };

                let mut stmts = self.compute_variable_array_sizes(ctx, typ.ctype)?;

                let ConvertedVariable { ty, mutbl, init } =
                    self.convert_variable(ctx, initializer, typ)?;
                let mut init = init?;

                stmts.append(init.stmts_mut());
                // A `const` context is not "already unsafe" the way code within a `fn` is
                // (since we translate all `fn`s as `unsafe`). Therefore, in `const` contexts,
                // expose any underlying unsafety in the initializer with an `unsafe` block.
                let init = if ctx.is_const {
                    init.to_unsafe_pure_expr()
                        .expect("init should not have any statements")
                } else {
                    init.into_value()
                };

                let zeroed = self.implicit_default_expr(typ.ctype, false)?;
                let zeroed = if ctx.is_const {
                    zeroed.to_unsafe_pure_expr()
                } else {
                    zeroed.to_pure_expr()
                }
                .expect("Expected decl initializer to not have any statements");
                let pat_mut = mk().mutbl().ident_pat(rust_name.clone());
                let local_mut = mk().local(pat_mut, Some(ty.clone()), Some(zeroed));
                if has_self_reference {
                    let assign = mk().assign_expr(mk().ident_expr(rust_name), init);

                    let mut assign_stmts = stmts.clone();
                    assign_stmts.push(mk().semi_stmt(assign.clone()));

                    let mut decl_and_assign = vec![mk().local_stmt(Box::new(local_mut.clone()))];
                    decl_and_assign.append(&mut stmts);
                    decl_and_assign.push(mk().expr_stmt(assign));

                    Ok(cfg::DeclStmtInfo::new(
                        vec![mk().local_stmt(Box::new(local_mut))],
                        assign_stmts,
                        decl_and_assign,
                    ))
                } else {
                    let pat = mk().set_mutbl(mutbl).ident_pat(rust_name.clone());

                    let type_annotation = if self.tcfg.reduce_type_annotations
                        && !self.should_assign_type_annotation(typ.ctype, initializer)
                    {
                        None
                    } else {
                        Some(ty)
                    };

                    let local = mk().local(pat, type_annotation, Some(init.clone()));
                    let assign = mk().assign_expr(mk().ident_expr(rust_name), init);

                    let mut assign_stmts = stmts.clone();
                    assign_stmts.push(mk().semi_stmt(assign));

                    let mut decl_and_assign = stmts;
                    decl_and_assign.push(mk().local_stmt(Box::new(local)));

                    Ok(cfg::DeclStmtInfo::new(
                        vec![mk().local_stmt(Box::new(local_mut))],
                        assign_stmts,
                        decl_and_assign,
                    ))
                }
            }

            ref decl => {
                let inserted = if let Some(ident) = decl.get_name() {
                    self.renamer.borrow_mut().insert(decl_id, ident).is_some()
                } else {
                    false
                };

                // TODO: We need this because we can have multiple 'extern' decls of the same variable.
                //       When we do, we must make sure to insert into the renamer the first time, and
                //       then skip subsequent times.
                use CDeclKind::*;
                let skip = match decl {
                    Variable { .. } => !inserted,
                    Struct { .. } => true,
                    Union { .. } => true,
                    Enum { .. } => true,
                    Typedef { .. } => true,
                    _ => false,
                };

                if skip {
                    Ok(cfg::DeclStmtInfo::new(vec![], vec![], vec![]))
                } else {
                    use ConvertedDecl::*;
                    let items = match self.convert_decl(ctx, decl_id)? {
                        Item(item) => vec![item],
                        ForeignItem(item) => {
                            vec![mk().extern_("C").foreign_items(vec![*item])]
                        }
                        Items(items) => items,
                        NoItem => return Ok(cfg::DeclStmtInfo::empty()),
                    };

                    let item_stmt = |item| mk().item_stmt(item);
                    Ok(cfg::DeclStmtInfo::new(
                        items.iter().cloned().map(item_stmt).collect(),
                        vec![],
                        items.into_iter().map(item_stmt).collect(),
                    ))
                }
            }
        }
    }

    fn should_assign_type_annotation(
        &self,
        ctypeid: CTypeId,
        initializer: Option<CExprId>,
    ) -> bool {
        let initializer_kind = initializer.map(|expr_id| &self.ast_context[expr_id].kind);

        // If the RHS is a func call, we should be able to skip type annotation
        // because we get a type from the function return type
        if let Some(CExprKind::Call(_, _, _)) = initializer_kind {
            return false;
        }

        use CTypeKind::*;
        match self.ast_context.resolve_type(ctypeid).kind {
            Pointer(CQualTypeId { ctype, .. }) => {
                match self.ast_context.resolve_type(ctype).kind {
                    Function(..) => {
                        // Fn pointers need to be type annotated if null
                        if initializer.is_none() {
                            return true;
                        }

                        // None assignments don't provide enough type information unless there are follow-up assignments
                        if let Some(CExprKind::ImplicitCast(_, _, CastKind::NullToPointer, _, _)) =
                            initializer_kind
                        {
                            return true;
                        }

                        // We could set this to false and skip non null fn ptr annotations. This will work
                        // 99% of the time, however there is a strange case where fn ptr comparisons
                        // complain PartialEq is not implemented for the type inferred function type,
                        // but the identical type that is explicitly defined doesn't seem to have that issue
                        // Probably a rustc bug. See https://github.com/rust-lang/rust/issues/53861
                        true
                    }
                    _ => {
                        // Non function null ptrs provide enough information to skip
                        // type annotations; ie `= ::core::ptr::null::<MyStruct>();`
                        if initializer.is_none() {
                            return false;
                        }

                        if let Some(CExprKind::ImplicitCast(_, _, cast_kind, _, _)) =
                            initializer_kind
                        {
                            match cast_kind {
                                CastKind::NullToPointer => return false,
                                CastKind::ConstCast => return true,
                                _ => {}
                            };
                        }

                        // ref decayed ptrs generally need a type annotation
                        if let Some(CExprKind::Unary(_, c_ast::UnOp::AddressOf, _, _)) =
                            initializer_kind
                        {
                            return true;
                        }

                        false
                    }
                }
            }
            // For some reason we don't seem to apply type suffixes when 0-initializing
            // so type annotation is need for 0-init ints and floats at the moment, but
            // they could be simplified in favor of type suffixes
            Bool | Char | SChar | Short | Int | Long | LongLong | UChar | UShort | UInt | ULong
            | ULongLong | LongDouble | Int128 | UInt128 => initializer.is_none(),
            Float | Double => initializer.is_none(),
            Struct(_) | Union(_) | Enum(_) => false,
            Function(..) => unreachable!("Can't have a function directly as a type"),
            Typedef(_) => unreachable!("Typedef should be expanded though resolve_type"),
            _ => true,
        }
    }

    fn convert_variable(
        &self,
        ctx: ExprContext,
        initializer: Option<CExprId>,
        typ: CQualTypeId,
    ) -> TranslationResult<ConvertedVariable> {
        let init = match initializer {
            Some(x) => self.convert_expr(ctx.used(), x, Some(typ)),
            None => self.implicit_default_expr(typ.ctype, ctx.is_static),
        };

        // Variable declarations for variable-length arrays use the type of a pointer to the
        // underlying array element
        let ty = if let CTypeKind::VariableArray(mut elt, _) =
            self.ast_context.resolve_type(typ.ctype).kind
        {
            elt = self.variable_array_base_type(elt);
            let ty = self.convert_type(elt)?;
            mk().path_ty(vec![
                mk().path_segment_with_args("Vec", mk().angle_bracketed_args(vec![ty]))
            ])
        } else {
            self.convert_type(typ.ctype)?
        };

        let mutbl = if typ.qualifiers.is_const {
            Mutability::Immutable
        } else {
            Mutability::Mutable
        };

        Ok(ConvertedVariable { ty, mutbl, init })
    }

    fn convert_function_param(
        &self,
        ctx: ExprContext,
        typ: CQualTypeId,
    ) -> TranslationResult<ConvertedFunctionParam> {
        if self.ast_context.is_va_list(typ.ctype) {
            let mutbl = if typ.qualifiers.is_const {
                Mutability::Immutable
            } else {
                Mutability::Mutable
            };
            let ty = mk().abs_path_ty(vec!["core", "ffi", "VaList"]);
            return Ok(ConvertedFunctionParam { mutbl, ty });
        }

        self.convert_variable(ctx, None, typ)
            .map(|ConvertedVariable { ty, mutbl, .. }| ConvertedFunctionParam { ty, mutbl })
    }

    fn convert_type(&self, type_id: CTypeId) -> TranslationResult<Box<Type>> {
        self.import_type(type_id);

        self.type_converter
            .borrow_mut()
            .convert(&self.ast_context, type_id)
    }

    fn addr_lhs(
        &self,
        lhs: Box<Expr>,
        lhs_type: CQualTypeId,
        write: bool,
    ) -> TranslationResult<Box<Expr>> {
        let mutbl = if write {
            Mutability::Mutable
        } else {
            Mutability::Immutable
        };
        let addr_lhs = match *lhs {
            Expr::Unary(ExprUnary {
                op: UnOp::Deref(_),
                expr: e,
                ..
            }) => {
                if write == lhs_type.qualifiers.is_const {
                    let lhs_type = self.convert_type(lhs_type.ctype)?;
                    let ty = mk().set_mutbl(mutbl).ptr_ty(lhs_type);

                    mk().cast_expr(e, ty)
                } else {
                    e
                }
            }
            _ => {
                let addr_lhs = mk().set_mutbl(mutbl).borrow_expr(lhs);

                let lhs_type = self.convert_type(lhs_type.ctype)?;
                let ty = mk().set_mutbl(mutbl).ptr_ty(lhs_type);

                mk().cast_expr(addr_lhs, ty)
            }
        };
        Ok(addr_lhs)
    }

    /// Write to a `lhs` that is volatile
    pub fn volatile_write(
        &self,
        lhs: Box<Expr>,
        lhs_type: CQualTypeId,
        rhs: Box<Expr>,
    ) -> TranslationResult<Box<Expr>> {
        let addr_lhs = self.addr_lhs(lhs, lhs_type, true)?;

        Ok(mk().call_expr(
            mk().abs_path_expr(vec!["core", "ptr", "write_volatile"]),
            vec![addr_lhs, rhs],
        ))
    }

    /// Read from a `lhs` that is volatile
    pub fn volatile_read(
        &self,
        lhs: Box<Expr>,
        lhs_type: CQualTypeId,
    ) -> TranslationResult<Box<Expr>> {
        let addr_lhs = self.addr_lhs(lhs, lhs_type, false)?;

        // We explicitly annotate the type of pointer we're reading from
        // in order to avoid omitted bit-casts to const from causing the
        // wrong type to be inferred via the result of the pointer.
        let mut path_parts: Vec<PathSegment> = vec![];
        for elt in ["core", "ptr"] {
            path_parts.push(mk().path_segment(elt))
        }
        let elt_ty = self.convert_type(lhs_type.ctype)?;
        let ty_params = mk().angle_bracketed_args(vec![elt_ty]);
        let elt = mk().path_segment_with_args("read_volatile", ty_params);
        path_parts.push(elt);

        let read_volatile_expr = mk().abs_path_expr(path_parts);
        Ok(mk().call_expr(read_volatile_expr, vec![addr_lhs]))
    }

    // Compute the offset multiplier for variable length array indexing
    // Rust type: usize
    pub fn compute_size_of_expr(&self, type_id: CTypeId) -> Option<Box<Expr>> {
        match self.ast_context.resolve_type(type_id).kind {
            CTypeKind::VariableArray(elts, Some(counts)) => {
                let opt_esize = self.compute_size_of_expr(elts);
                let csize_name = self
                    .renamer
                    .borrow()
                    .get(&CDeclId(counts.0))
                    .expect("Failed to lookup VLA expression");
                let csize = mk().path_expr(vec![csize_name]);

                let val = match opt_esize {
                    None => csize,
                    Some(esize) => mk().binary_expr(BinOp::Mul(Default::default()), csize, esize),
                };
                Some(val)
            }
            _ => None,
        }
    }

    /// Variable element arrays are represented by a flat array of non-variable-length array
    /// elements. This function traverses potentially multiple levels of variable-length array
    /// to find the underlying element type.
    fn variable_array_base_type(&self, mut elt: CTypeId) -> CTypeId {
        while let CTypeKind::VariableArray(elt_, _) = self.ast_context.resolve_type(elt).kind {
            elt = elt_;
        }
        elt
    }

    /// This generates variables that store the computed sizes of the variable-length arrays in
    /// the given type.
    pub fn compute_variable_array_sizes(
        &self,
        ctx: ExprContext,
        mut type_id: CTypeId,
    ) -> TranslationResult<Vec<Stmt>> {
        let mut stmts = vec![];

        loop {
            match self.ast_context.resolve_type(type_id).kind {
                CTypeKind::Pointer(elt) => type_id = elt.ctype,
                CTypeKind::ConstantArray(elt, _) => type_id = elt,
                CTypeKind::VariableArray(elt, Some(expr_id)) => {
                    type_id = elt;

                    // Convert this expression
                    let expr = self
                        .convert_expr(ctx.used(), expr_id, None)?
                        .and_then(|expr| {
                            let name = self
                                .renamer
                                .borrow_mut()
                                .insert(CDeclId(expr_id.0), "vla")
                                .unwrap(); // try using declref name?
                                           // TODO: store the name corresponding to expr_id

                            let local = mk().local(
                                mk().ident_pat(name),
                                None,
                                Some(mk().cast_expr(expr, mk().path_ty(vec!["usize"]))),
                            );

                            let res: TranslationResult<WithStmts<()>> =
                                Ok(WithStmts::new(vec![mk().local_stmt(Box::new(local))], ()));
                            res
                        })?;

                    stmts.extend(expr.into_stmts());
                }
                _ => break,
            }
        }

        Ok(stmts)
    }

    // Compute the size of a type
    // Rust type: usize
    pub fn compute_size_of_type(
        &self,
        ctx: ExprContext,
        type_id: CTypeId,
        override_ty: Option<CQualTypeId>,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        if let CTypeKind::VariableArray(elts, len) = self.ast_context.resolve_type(type_id).kind {
            let len = len.expect("Sizeof a VLA type with count expression omitted");

            let elts = self.compute_size_of_type(ctx, elts, override_ty)?;
            return elts.and_then(|lhs| {
                let len = self.convert_expr(ctx.used().not_static(), len, override_ty)?;
                Ok(len.map(|len| {
                    let rhs = cast_int(len, "usize", true);
                    mk().binary_expr(BinOp::Mul(Default::default()), lhs, rhs)
                }))
            });
        }
        let ty = self.convert_type(type_id)?;
        let mut result = self.mk_size_of_ty_expr(ty);
        // cast to expected ty if one is known
        if let Some(expected_ty) = override_ty {
            trace!(
                "Converting result of sizeof to {:?}",
                self.ast_context.resolve_type(expected_ty.ctype)
            );
            let result_ty = self.convert_type(expected_ty.ctype)?;
            result = result.map(|x| x.map(|x| mk().cast_expr(x, result_ty)));
        }
        result
    }

    fn mk_size_of_ty_expr(&self, ty: Box<Type>) -> TranslationResult<WithStmts<Box<Expr>>> {
        let name = "size_of";
        let params = mk().angle_bracketed_args(vec![ty]);
        let path = vec![
            mk().path_segment("core"),
            mk().path_segment("mem"),
            mk().path_segment_with_args(name, params),
        ];
        let call = mk().call_expr(mk().abs_path_expr(path), vec![]);

        Ok(WithStmts::new_val(call))
    }

    pub fn compute_align_of_type(
        &self,
        mut type_id: CTypeId,
        preferred: bool,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        type_id = self.variable_array_base_type(type_id);

        let ty = self.convert_type(type_id)?;
        let tys = vec![ty];
        let mut path = vec![mk().path_segment("core")];
        if preferred {
            self.use_feature("core_intrinsics");
            path.push(mk().path_segment("intrinsics"));
            path.push(mk().path_segment_with_args("pref_align_of", mk().angle_bracketed_args(tys)));
        } else {
            path.push(mk().path_segment("mem"));
            path.push(mk().path_segment_with_args("align_of", mk().angle_bracketed_args(tys)));
        }
        let call = mk().call_expr(mk().abs_path_expr(path), vec![]);
        Ok(WithStmts::new_val(call))
    }

    /// Convert multiple expressions (while collecting a context of statements) given either all or
    /// none of their expected types
    #[allow(clippy::vec_box/*, reason = "not worth a substantial refactor"*/)]
    fn convert_exprs(
        &self,
        ctx: ExprContext,
        exprs: &[CExprId],
        arg_tys: Option<&[CQualTypeId]>,
    ) -> TranslationResult<WithStmts<Vec<Box<Expr>>>> {
        assert!(arg_tys.map(|tys| tys.len() == exprs.len()).unwrap_or(true));
        exprs
            .iter()
            .enumerate()
            .map(|(n, arg)| self.convert_expr(ctx, *arg, arg_tys.map(|tys| tys[n])))
            .collect()
    }

    /// Variant of `convert_exprs` for the arguments of a function call.
    /// Accounts for differences in translation for arguments, and for varargs where only a prefix
    /// of the expression types are known.
    #[allow(clippy::vec_box/*, reason = "not worth a substantial refactor"*/)]
    fn convert_call_args(
        &self,
        ctx: ExprContext,
        exprs: &[CExprId],
        arg_tys: Option<&[CQualTypeId]>,
        is_variadic: bool,
    ) -> TranslationResult<WithStmts<Vec<Box<Expr>>>> {
        let arg_tys = if let Some(arg_tys) = arg_tys {
            if !is_variadic {
                assert!(arg_tys.len() == exprs.len());
            }

            arg_tys
        } else {
            &[]
        };

        exprs
            .iter()
            .enumerate()
            .map(|(n, arg)| self.convert_call_arg(ctx, *arg, arg_tys.get(n).copied()))
            .collect()
    }

    /// Translate a C expression into a Rust one, possibly collecting side-effecting statements
    /// to run before the expression.
    ///
    /// `ctx.is_used()` informs us how the C expression we are translating is used in the C
    /// program.
    ///
    /// In the case that `ctx.is_unused()`, all side-effecting components will be in the
    /// `stmts` field of the output and it is expected that the `val` field of the output will be
    /// ignored.
    ///
    /// `override_ty` is the type expected by the surrounding expression context.
    /// This can be different from the type of the AST node itself
    /// and in many cases should override it.
    pub fn convert_expr(
        &self,
        mut ctx: ExprContext,
        expr_id: CExprId,
        override_ty: Option<CQualTypeId>,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        let Located {
            loc: src_loc,
            kind: expr_kind,
        } = &self.ast_context[expr_id];

        trace!(
            "Converting expr {:?}: {:?}",
            expr_id,
            self.ast_context[expr_id]
        );

        if let Some(converted) = self.convert_const_macro_expansion(ctx, expr_id, override_ty)? {
            return Ok(converted);
        }

        {
            let text = self.ast_context.macro_expansion_text.get(&expr_id);
            if let Some(converted) =
                text.and_then(|text| self.convert_fn_macro_invocation(ctx, text))
            {
                return Ok(converted);
            }
        }

        use CExprKind::*;
        match *expr_kind {
            DesignatedInitExpr(..) => {
                Err(TranslationError::generic("Unexpected designated init expr"))
            }
            BadExpr => Err(TranslationError::generic(
                "convert_expr: expression kind not supported",
            )),
            ShuffleVector(_, ref child_expr_ids) => self
                .convert_shuffle_vector(ctx, child_expr_ids)
                .map_err(|e| {
                    TranslationError::new(
                        self.ast_context.display_loc(src_loc),
                        e.context(TranslationErrorKind::OldLLVMSimd),
                    )
                }),
            ConvertVector(..) => Err(TranslationError::generic("convert vector not supported")),

            UnaryType(_ty, kind, opt_expr, arg_ty) => {
                let result = match kind {
                    UnTypeOp::SizeOf => match opt_expr {
                        None => self.compute_size_of_type(ctx, arg_ty.ctype, override_ty)?,
                        Some(_) => {
                            let inner = self.variable_array_base_type(arg_ty.ctype);
                            let inner_size = self.compute_size_of_type(ctx, inner, override_ty)?;

                            if let Some(sz) = self.compute_size_of_expr(arg_ty.ctype) {
                                inner_size.map(|x| {
                                    mk().binary_expr(BinOp::Mul(Default::default()), sz, x)
                                })
                            } else {
                                // Otherwise, use the pointer and make a deref of a pointer offset expression
                                inner_size
                            }
                        }
                    },
                    UnTypeOp::AlignOf => self.compute_align_of_type(arg_ty.ctype, false)?,
                    UnTypeOp::PreferredAlignOf => self.compute_align_of_type(arg_ty.ctype, true)?,
                };

                Ok(result)
            }

            ConstantExpr(ty, child, value) => {
                if let Some(constant) = value {
                    self.convert_constant(constant).map(WithStmts::new_val)
                } else {
                    self.convert_expr(ctx, child, Some(ty))
                }
            }

            DeclRef(qual_ty, decl_id, lrvalue) => {
                let decl = &self
                    .ast_context
                    .get_decl(&decl_id)
                    .ok_or_else(|| format_err!("Missing declref {:?}", decl_id))?
                    .kind;
                if ctx.is_const {
                    // TODO Determining which declarations have been declared within the scope of the const macro expr
                    // vs. which are out-of-scope of the const macro is non-trivial,
                    // so for now, we don't allow const macros referencing any declarations.
                    return Err(format_translation_err!(
                        self.ast_context.display_loc(src_loc),
                        "Cannot yet refer to declarations in a const expr",
                    ));

                    #[allow(unreachable_code)] // TODO temporary (see above).
                    if let CDeclKind::Variable {
                        has_static_duration: true,
                        ..
                    } = decl
                    {
                        return Err(format_translation_err!(
                            self.ast_context.display_loc(src_loc),
                            "Cannot refer to static duration variable in a const expression",
                        ));
                    }
                }

                let varname = decl.get_name().expect("expected variable name").to_owned();
                let rustname = self
                    .renamer
                    .borrow_mut()
                    .get(&decl_id)
                    .ok_or_else(|| format_err!("name not declared: '{}'", varname))?;

                // Import the referenced global decl into our submodule
                if self.tcfg.reorganize_definitions {
                    self.add_import(decl_id, &rustname);
                    // match decl {
                    //     CDeclKind::Variable { is_defn: false, .. } => {}
                    //     _ => self.add_import(decl_id, &rustname),
                    // }
                }

                let mut val = mk().path_expr(vec![rustname]);

                // If the variable is volatile and used as something that isn't an LValue, this
                // constitutes a volatile read.
                if lrvalue.is_rvalue() && qual_ty.qualifiers.is_volatile {
                    val = self.volatile_read(val, qual_ty)?;
                }

                // If the variable is actually an `EnumConstant`, we need to add a cast to the
                // expected integral type. When modifying this, look at `Translation::enum_cast` -
                // this function assumes `DeclRef`'s to `EnumConstants`'s will translate to casts.
                if let &CDeclKind::EnumConstant { .. } = decl {
                    let ty = self.convert_type(qual_ty.ctype)?;
                    val = mk().cast_expr(val, ty);
                }

                // If we are referring to a function and need its address, we
                // need to cast it to fn() to ensure that it has a real address.
                let mut set_unsafe = false;
                if ctx.needs_address() {
                    if let CDeclKind::Function { parameters, .. } = decl {
                        let ty = self.convert_type(qual_ty.ctype)?;
                        let actual_ty = self
                            .type_converter
                            .borrow_mut()
                            .knr_function_type_with_parameters(
                                &self.ast_context,
                                qual_ty.ctype,
                                parameters,
                            )?;
                        if let Some(actual_ty) = actual_ty {
                            if actual_ty != ty {
                                // If we're casting a concrete function to
                                // a K&R function pointer type, use transmute
                                self.import_type(qual_ty.ctype);

                                val = transmute_expr(actual_ty, ty, val);
                                set_unsafe = true;
                            }
                        } else {
                            let decl_kind = &self.ast_context[decl_id].kind;
                            let kind_with_declared_args =
                                self.ast_context.fn_decl_ty_with_declared_args(decl_kind);

                            if let Some(ty) = self
                                .ast_context
                                .type_for_kind(&kind_with_declared_args)
                                .map(CQualTypeId::new)
                            {
                                let ty = self.convert_type(ty.ctype)?;
                                val = mk().cast_expr(val, ty);
                            } else {
                                val = mk().cast_expr(val, ty);
                            }
                        }
                    }
                }

                if let CTypeKind::VariableArray(..) =
                    self.ast_context.resolve_type(qual_ty.ctype).kind
                {
                    val = mk().method_call_expr(val, "as_mut_ptr", vec![]);
                }

                // if the context wants a different type, add a cast
                if let Some(expected_ty) = override_ty {
                    if expected_ty != qual_ty {
                        val = mk().cast_expr(val, self.convert_type(expected_ty.ctype)?);
                    }
                }

                let mut res = WithStmts::new_val(val);
                res.merge_unsafe(set_unsafe);
                Ok(res)
            }

            OffsetOf(ty, ref kind) => match kind {
                OffsetOfKind::Constant(val) => Ok(WithStmts::new_val(self.mk_int_lit(
                    override_ty.unwrap_or(ty),
                    *val,
                    IntBase::Dec,
                )?)),
                OffsetOfKind::Variable(qty, field_id, expr_id) => {
                    self.use_crate(ExternCrate::Memoffset);

                    // Struct Type
                    let decl_id = {
                        let kind = match self.ast_context[qty.ctype].kind {
                            CTypeKind::Elaborated(ty_id) => &self.ast_context[ty_id].kind,
                            ref kind => kind,
                        };

                        kind.as_decl_or_typedef()
                            .expect("Did not find decl_id for offsetof struct")
                    };
                    let name = self.resolve_decl_inner_name(decl_id);
                    let ty_ident = mk().ident(name);

                    // Field name
                    let field_name = self
                        .type_converter
                        .borrow()
                        .resolve_field_name(None, *field_id)
                        .expect("Did not find name for offsetof struct field");
                    let field_ident = mk().ident(field_name);

                    // Index Expr
                    let expr = self
                        .convert_expr(ctx, *expr_id, None)?
                        .to_pure_expr()
                        .ok_or_else(|| {
                            format_err!("Expected Variable offsetof to be a side-effect free")
                        })?;
                    let expr = mk().cast_expr(expr, mk().ident_ty("usize"));
                    use syn::__private::ToTokens;
                    let index_expr = expr.to_token_stream();

                    // offset_of!(Struct, field[expr as usize]) as ty
                    let macro_body = vec![
                        TokenTree::Ident(ty_ident),
                        TokenTree::Punct(Punct::new(',', Alone)),
                        TokenTree::Ident(field_ident),
                        TokenTree::Group(proc_macro2::Group::new(
                            proc_macro2::Delimiter::Bracket,
                            index_expr,
                        )),
                    ];
                    let path = mk().path("offset_of");
                    let mac = mk().mac_expr(mk().mac(
                        path,
                        macro_body,
                        MacroDelimiter::Paren(Default::default()),
                    ));

                    // Cast type
                    let cast_ty = self.convert_type(override_ty.unwrap_or(ty).ctype)?;
                    let cast_expr = mk().cast_expr(mac, cast_ty);

                    Ok(WithStmts::new_val(cast_expr))
                }
            },

            Literal(ty, ref kind) => self.convert_literal(ctx, override_ty.unwrap_or(ty), kind),

            ImplicitCast(ty, expr, kind, opt_field_id, _)
            | ExplicitCast(ty, expr, kind, opt_field_id, _) => {
                let is_explicit = matches!(expr_kind, CExprKind::ExplicitCast(..));
                // A reference must be decayed if a bitcast is required. Const casts in
                // LLVM 8 are now NoOp casts, so we need to include it as well.
                match kind {
                    CastKind::BitCast | CastKind::PointerToIntegral | CastKind::NoOp => {
                        ctx.decay_ref = DecayRef::Yes
                    }
                    CastKind::ArrayToPointerDecay
                    | CastKind::FunctionToPointerDecay
                    | CastKind::BuiltinFnToFnPtr => {
                        ctx.needs_address = true;
                    }
                    _ => {}
                }

                let mut source_ty = self.ast_context[expr]
                    .kind
                    .get_qual_type()
                    .ok_or_else(|| format_err!("bad source type"))?;

                let val = if is_explicit {
                    // If we're casting a function, look for its declared ty to use as a more
                    // precise source type. The AST node's type will not preserve typedef arg types
                    // but the function's declaration will.
                    if let Some(func_decl) = self.ast_context.fn_declref_decl(expr) {
                        let kind_with_declared_args =
                            self.ast_context.fn_decl_ty_with_declared_args(func_decl);
                        let func_ty = self
                            .ast_context
                            .type_for_kind(&kind_with_declared_args)
                            .unwrap_or_else(|| {
                                panic!("no type for kind {kind_with_declared_args:?}")
                            });
                        let func_ptr_ty = self
                            .ast_context
                            .type_for_kind(&CTypeKind::Pointer(CQualTypeId::new(func_ty)))
                            .unwrap_or_else(|| {
                                panic!("no type for kind {kind_with_declared_args:?}")
                            });

                        source_ty = CQualTypeId::new(func_ptr_ty);
                    }

                    let stmts = self.compute_variable_array_sizes(ctx, ty.ctype)?;
                    let mut val = self.convert_expr(ctx, expr, None)?;
                    val.prepend_stmts(stmts);
                    val
                } else {
                    // In general, if we are casting the result of an expression, then the inner
                    // expression should be translated to whatever type it normally would.
                    // But for literals, if we don't absolutely have to cast, we would rather the
                    // literal is translated according to the type we're expecting, and then we can
                    // skip the cast entirely.
                    if let (Some(ty), CExprKind::Literal(_ty, lit)) =
                        (override_ty, &self.ast_context[expr].kind)
                    {
                        if self.literal_matches_ty(lit, ty) {
                            return self.convert_expr(ctx, expr, override_ty);
                        }
                    }
                    // LValueToRValue casts don't actually change the type, so it still makes sense
                    // to translate their inner expression with the expected type from outside the
                    // cast.
                    if kind == CastKind::LValueToRValue
                        && Some(source_ty.ctype) != override_ty.map(|x| x.ctype)
                    {
                        self.convert_expr(ctx, expr, override_ty)?
                    } else {
                        self.convert_expr(ctx, expr, None)?
                    }
                };
                // Shuffle Vector "function" builtins will add a cast to the output of the
                // builtin call which is unnecessary for translation purposes
                if self.casting_simd_builtin_call(expr, is_explicit, kind) {
                    return Ok(val);
                }

                let target_ty = override_ty.unwrap_or(ty);

                self.convert_cast(
                    ctx,
                    source_ty,
                    target_ty,
                    val,
                    Some(expr),
                    Some(kind),
                    opt_field_id,
                )
            }

            Unary(type_id, op, arg, lrvalue) => {
                self.convert_unary_operator(ctx, op, override_ty.unwrap_or(type_id), arg, lrvalue)
            }

            Conditional(ty, cond, lhs, rhs) => {
                if ctx.is_const {
                    return Err(format_translation_err!(
                        self.ast_context.display_loc(src_loc),
                        "Constants cannot contain ternary expressions in Rust",
                    ));
                }
                let cond = self.convert_condition(ctx, true, cond)?;

                let lhs = self.convert_expr(ctx, lhs, Some(override_ty.unwrap_or(ty)))?;
                let rhs = self.convert_expr(ctx, rhs, Some(override_ty.unwrap_or(ty)))?;

                if ctx.is_unused() {
                    let is_unsafe = lhs.is_unsafe() || rhs.is_unsafe();
                    let then = mk().block(lhs.into_stmts());
                    let else_ = mk().block_expr(mk().block(rhs.into_stmts()));

                    let mut res = cond.and_then(|c| -> TranslationResult<_> {
                        Ok(WithStmts::new(
                            vec![mk().semi_stmt(mk().ifte_expr(c, then, Some(else_)))],
                            self.panic_or_err("Conditional expression is not supposed to be used"),
                        ))
                    })?;
                    res.merge_unsafe(is_unsafe);
                    Ok(res)
                } else {
                    let then = lhs.to_block();
                    let else_ = rhs.to_expr();

                    Ok(cond.map(|c| {
                        let ifte_expr = mk().ifte_expr(c, then, Some(else_));

                        if ctx.ternary_needs_parens {
                            mk().paren_expr(ifte_expr)
                        } else {
                            ifte_expr
                        }
                    }))
                }
            }

            BinaryConditional(ty, lhs, rhs) => {
                if ctx.is_unused() {
                    let mut lhs = self.convert_condition(ctx, false, lhs)?;
                    let rhs = self.convert_expr(ctx, rhs, None)?;
                    lhs.merge_unsafe(rhs.is_unsafe());

                    lhs.and_then(|val| {
                        Ok(WithStmts::new(
                            vec![mk().semi_stmt(mk().ifte_expr(
                                val,
                                mk().block(rhs.into_stmts()),
                                None,
                            ))],
                            self.panic_or_err(
                                "Binary conditional expression is not supposed to be used",
                            ),
                        ))
                    })
                } else {
                    self.name_reference_write_read(ctx, lhs)?.result_map(
                        |NamedReference {
                             rvalue: lhs_val, ..
                         }| {
                            let cond = self.match_bool(ctx, true, ty.ctype, lhs_val.clone())?;
                            let ite = mk().ifte_expr(
                                cond,
                                mk().block(vec![mk().expr_stmt(lhs_val)]),
                                Some(self.convert_expr(ctx, rhs, None)?.to_expr()),
                            );
                            Ok(ite)
                        },
                    )
                }
            }

            Binary(type_id, op, lhs, rhs, opt_lhs_type_id, opt_res_type_id) => self
                .convert_binary_expr(
                    ctx,
                    override_ty.unwrap_or(type_id),
                    op,
                    lhs,
                    rhs,
                    opt_lhs_type_id,
                    opt_res_type_id,
                )
                .map_err(|e| e.add_loc(self.ast_context.display_loc(src_loc))),

            ArraySubscript(_, lhs, rhs, _) => self
                .convert_array_subscript(ctx, lhs, rhs, override_ty, true)
                .map_err(|e| e.add_loc(self.ast_context.display_loc(src_loc))),

            Call(call_expr_ty, func, ref args) => {
                let fn_ty =
                    self.ast_context
                        .get_pointee_qual_type(
                            self.ast_context[func].kind.get_type().ok_or_else(|| {
                                format_err!("Invalid callee expression {:?}", func)
                            })?,
                        )
                        .map(|ty| &self.ast_context.resolve_type(ty.ctype).kind);
                let is_variadic = match fn_ty {
                    Some(CTypeKind::Function(_, _, is_variadic, _, _)) => *is_variadic,
                    _ => false,
                };

                let mut arg_tys = if let Some(CDeclKind::Function { parameters, .. }) =
                    self.ast_context.fn_declref_decl(func)
                {
                    self.ast_context.tys_of_params(parameters)
                } else {
                    None
                };

                let func = match self.ast_context[func].kind {
                    // Direct function call
                    CExprKind::ImplicitCast(_, fexp, CastKind::FunctionToPointerDecay, _, _)
                    // Only a direct function call with pointer decay if the
                    // callee is a declref
                    if matches!(self.ast_context[fexp].kind, CExprKind::DeclRef(..)) =>
                        {
                            self.convert_expr(ctx.used(), fexp, None)?
                        }

                    // Builtin function call
                    CExprKind::ImplicitCast(_, fexp, CastKind::BuiltinFnToFnPtr, _, _) => {
                        return self.convert_builtin(ctx, fexp, args);
                    }

                    // Function pointer call
                    _ => {
                        let mut callee = self.convert_expr(ctx.used(), func, None)?;
                        let make_fn_ty = |ret_ty: Box<Type>| {
                            let ret_ty = match *ret_ty {
                                Type::Tuple(TypeTuple { elems: ref v, .. }) if v.is_empty() => ReturnType::Default,
                                _ => ReturnType::Type(Default::default(), ret_ty),
                            };
                            let bare_ty = (
                                vec![mk().bare_arg(mk().infer_ty(), None::<Box<Ident>>); args.len()],
                                None::<BareVariadic>,
                                ret_ty
                            );
                            mk().barefn_ty(bare_ty)
                        };
                        match fn_ty {
                            Some(CTypeKind::Function(ret_ty, _, _, _, false)) => {
                                // K&R function pointer without arguments
                                let ret_ty = self.convert_type(ret_ty.ctype)?;
                                let target_ty = make_fn_ty(ret_ty);
                                callee.set_unsafe();
                                callee.map(|fn_ptr| {
                                    let fn_ptr = unwrap_function_pointer(fn_ptr);
                                    transmute_expr(mk().infer_ty(), target_ty, fn_ptr)
                                })
                            }
                            None => {
                                // We have to infer the return type from our expression type
                                let ret_ty = self.convert_type(call_expr_ty.ctype)?;
                                let target_ty = make_fn_ty(ret_ty);
                                callee.set_unsafe();
                                callee.map(|fn_ptr| {
                                    transmute_expr(mk().infer_ty(), target_ty, fn_ptr)
                                })
                            }
                            Some(CTypeKind::Function(_, ty_arg_tys, ..)) => {
                                arg_tys = Some(ty_arg_tys.clone());
                                // Normal function pointer
                                callee.map(unwrap_function_pointer)
                            }
                            Some(_) => panic!("function pointer did not point to CTYpeKind::Function: {fn_ty:?}"),
                        }
                    }
                };

                let call = func.and_then(|func| {
                    // We want to decay refs only when function is variadic
                    ctx.decay_ref = DecayRef::from(is_variadic);

                    let args =
                        self.convert_call_args(ctx.used(), args, arg_tys.as_deref(), is_variadic)?;

                    let mut call_expr = args.map(|args| mk().call_expr(func, args));
                    if let Some(expected_ty) = override_ty {
                        if call_expr_ty != expected_ty {
                            let ret_ty = self.convert_type(expected_ty.ctype)?;
                            call_expr = call_expr.map(|call| mk().cast_expr(call, ret_ty));
                        }
                    }

                    let res: TranslationResult<_> = Ok(call_expr);
                    res
                })?;

                self.convert_side_effects_expr(
                    ctx,
                    call,
                    "Function call expression is not supposed to be used",
                )
            }

            Member(qual_ty, expr, decl, kind, _) => {
                if ctx.is_unused() {
                    self.convert_expr(ctx, expr, None)
                } else {
                    let mut val = match kind {
                        MemberKind::Dot => self.convert_expr(ctx, expr, None)?,
                        MemberKind::Arrow => {
                            if let CExprKind::Unary(_, c_ast::UnOp::AddressOf, subexpr_id, _) =
                                self.ast_context[expr].kind
                            {
                                // Special-case the `(&x)->field` pattern
                                // Convert it directly into `x.field`
                                self.convert_expr(ctx, subexpr_id, None)?
                            } else {
                                let val = self.convert_expr(ctx, expr, None)?;
                                val.map(|v| mk().unary_expr(UnOp::Deref(Default::default()), v))
                            }
                        }
                    };

                    let record_id = self.ast_context.parents[&decl];
                    if self.ast_context.has_inner_struct_decl(record_id) {
                        // The structure is split into an outer and an inner,
                        // so we need to go through the outer structure to the inner one
                        val = val.map(|v| mk().anon_field_expr(v, 0));
                    };

                    let field_name = self
                        .type_converter
                        .borrow()
                        .resolve_field_name(None, decl)
                        .unwrap();
                    let is_bitfield = match &self.ast_context[decl].kind {
                        CDeclKind::Field { bitfield_width, .. } => bitfield_width.is_some(),
                        _ => unreachable!("Found a member which is not a field"),
                    };
                    if is_bitfield {
                        // Convert a bitfield member one of four ways:
                        // A) bf.a()
                        // B) (*bf).a()
                        // C) bf
                        // D) (*bf)
                        //
                        // The first two are when we know this bitfield member is going to be read
                        // from (default), possibly requiring a dereference first. The latter two
                        // are generated when we are expecting to require a write, which will need
                        // to make a method call with some input which we do not yet have access
                        // to and will have to be handled elsewhere, IE `bf.set_a(1)`
                        if !ctx.is_bitfield_write {
                            // Cases A and B above
                            val = val.map(|v| mk().method_call_expr(v, field_name, vec![]));
                        }
                    } else {
                        val = val.map(|v| mk().field_expr(v, field_name));
                    };

                    // if the context wants a different type, add a cast
                    if let Some(expected_ty) = override_ty {
                        if expected_ty != qual_ty {
                            let ty = self.convert_type(expected_ty.ctype)?;
                            val = val.map(|v| mk().cast_expr(v, ty));
                        }
                    }

                    Ok(val)
                }
            }

            Paren(_, val) => self.convert_expr(ctx, val, override_ty),

            CompoundLiteral(qty, val) => {
                let val = self.convert_expr(ctx, val, override_ty)?;

                if !ctx.needs_address() || ctx.is_static || ctx.is_const {
                    // Statics and consts have their intermediates' lifetimes extended.
                    return Ok(val);
                }

                // C compound literals are lvalues, but equivalent Rust expressions generally are not.
                // So if an address is needed, store it in an intermediate variable first.
                let fresh_name = self.renamer.borrow_mut().fresh();
                let fresh_ty = self.convert_type(override_ty.unwrap_or(qty).ctype)?;

                val.and_then(|val| {
                    let fresh_stmt = {
                        let mutbl = if qty.qualifiers.is_const {
                            Mutability::Immutable
                        } else {
                            Mutability::Mutable
                        };

                        let local = mk().local(
                            mk().set_mutbl(mutbl).ident_pat(&fresh_name),
                            Some(fresh_ty),
                            Some(val),
                        );
                        mk().local_stmt(Box::new(local))
                    };

                    Ok(WithStmts::new(
                        vec![fresh_stmt],
                        mk().ident_expr(fresh_name),
                    ))
                })
            }

            InitList(ty, ref ids, opt_union_field_id, _) => {
                self.convert_init_list(ctx, ty, ids, opt_union_field_id)
            }

            ImplicitValueInit(ty) => self.implicit_default_expr(ty.ctype, ctx.is_static),

            Predefined(_, val_id) => self.convert_expr(ctx, val_id, override_ty),

            Statements(_, compound_stmt_id) => {
                self.convert_statement_expression(ctx, compound_stmt_id)
            }

            VAArg(ty, val_id) => self.convert_vaarg(ctx, ty, val_id),

            Choose(_, _cond, lhs, rhs, is_cond_true) => {
                let chosen_expr = if is_cond_true {
                    self.convert_expr(ctx, lhs, override_ty)?
                } else {
                    self.convert_expr(ctx, rhs, override_ty)?
                };

                // TODO: Support compile-time choice between lhs and rhs based on cond.

                // From Clang Expr.h
                // ChooseExpr - GNU builtin-in function __builtin_choose_expr.
                // This AST node is similar to the conditional operator (?:) in C, with
                // the following exceptions:
                // - the test expression must be a integer constant expression.
                // - the expression returned acts like the chosen subexpression in every
                //   visible way: the type is the same as that of the chosen subexpression,
                //   and all predicates (whether it's an l-value, whether it's an integer
                //   constant expression, etc.) return the same result as for the chosen
                //   sub-expression.

                Ok(chosen_expr)
            }

            Atomic {
                ref name,
                ptr,
                order,
                val1,
                order_fail,
                val2,
                weak,
                ..
            } => self.convert_atomic(ctx, name, ptr, order, val1, order_fail, val2, weak),
        }
    }

    pub fn convert_constant(&self, constant: ConstIntExpr) -> TranslationResult<Box<Expr>> {
        let expr = match constant {
            ConstIntExpr::U(n) => mk().lit_expr(mk().int_unsuffixed_lit(n as u128)),

            ConstIntExpr::I(n) if n >= 0 => mk().lit_expr(mk().int_unsuffixed_lit(n as u128)),

            ConstIntExpr::I(n) => mk().unary_expr(
                UnOp::Neg(Default::default()),
                mk().lit_expr(mk().int_unsuffixed_lit(n.unsigned_abs() as u128)),
            ),
        };
        Ok(expr)
    }

    /// Wrapper around `convert_expr` for the arguments of a function call.
    pub fn convert_call_arg(
        &self,
        ctx: ExprContext,
        expr_id: CExprId,
        override_ty: Option<CQualTypeId>,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        let mut val;

        if (self.ast_context.index(expr_id).kind.get_qual_type())
            .map_or(false, |qtype| self.ast_context.is_va_list(qtype.ctype))
        {
            // No `override_ty` to avoid unwanted casting.
            val = self.convert_expr(ctx, expr_id, None)?;
            val = val.map(|val| mk().method_call_expr(val, "as_va_list", Vec::new()));
        } else {
            val = self.convert_expr(ctx, expr_id, override_ty)?;
        }

        Ok(val)
    }

    /// Convert the expansion of a const-like macro.
    ///
    /// See [`TranspilerConfig::translate_const_macros`].
    ///
    /// [`TranspilerConfig::translate_const_macros`]: crate::TranspilerConfig::translate_const_macros
    fn convert_const_macro_expansion(
        &self,
        ctx: ExprContext,
        expr_id: CExprId,
        override_ty: Option<CQualTypeId>,
    ) -> TranslationResult<Option<WithStmts<Box<Expr>>>> {
        let macros = match self.ast_context.macro_invocations.get(&expr_id) {
            Some(macros) => macros.as_slice(),
            None => return Ok(None),
        };

        // Find the first macro after the macro we're currently expanding, if any.
        let first_macro = macros
            .splitn(2, |macro_id| ctx.expanding_macro(macro_id))
            .last()
            .unwrap()
            .first();
        let macro_id = match first_macro {
            Some(macro_id) => macro_id,
            None => return Ok(None),
        };

        trace!("  found macro expansion: {macro_id:?}");
        // Ensure that we've converted this macro and that it has a valid definition.
        let expansion = self.macro_expansions.borrow().get(macro_id).cloned();
        let macro_ty = match expansion {
            // Expansion exists.
            Some(Some(expansion)) => expansion.ty,

            // Expansion wasn't possible.
            Some(None) => return Ok(None),

            // We haven't tried to expand it yet.
            None => {
                self.convert_decl(ctx, *macro_id)?;
                if let Some(Some(expansion)) = self.macro_expansions.borrow().get(macro_id) {
                    expansion.ty
                } else {
                    return Ok(None);
                }
            }
        };
        let rust_name = self
            .renamer
            .borrow_mut()
            .get(macro_id)
            .ok_or_else(|| format_err!("Macro name not declared"))?;

        self.add_import(*macro_id, &rust_name);

        let val = WithStmts::new_val(mk().path_expr(vec![rust_name]));

        let expr_kind = &self.ast_context[expr_id].kind;
        // TODO We'd like to get rid of this cast eventually (see #1321).
        // Currently, const macros do not get the correct `override_ty` themselves,
        // so they aren't declared with the correct portable type,
        // but its uses are expecting the correct portable type,
        // so we need to cast it to the `override_ty` here.
        let expr_ty = override_ty.or_else(|| expr_kind.get_qual_type());
        if let Some(expr_ty) = expr_ty {
            self.convert_cast(
                ctx,
                CQualTypeId::new(macro_ty),
                expr_ty,
                val,
                None,
                None,
                None,
            )
            .map(Some)
        } else {
            Ok(Some(val))
        }

        // TODO: May need to handle volatile reads here.
        // See `DeclRef` below.
    }

    /// Convert the expansion of a function-like macro.
    ///
    /// See [`TranspilerConfig::translate_fn_macros`].
    ///
    /// [`TranspilerConfig::translate_fn_macros`]: crate::TranspilerConfig::translate_fn_macros
    fn convert_fn_macro_invocation(
        &self,
        _ctx: ExprContext,
        text: &str,
    ) -> Option<WithStmts<Box<Expr>>> {
        match self.tcfg.translate_fn_macros {
            TranslateMacros::None => return None,
            TranslateMacros::Conservative => return None, // Nothing is supported for `Conservative` yet.
            TranslateMacros::Experimental => {}
        }

        let mut split = text.splitn(2, '(');
        let ident = split.next()?.trim();
        let args = split.next()?.trim_end_matches(')');

        let ts: TokenStream = syn::parse_str(args).ok()?;
        Some(WithStmts::new_val(mk().mac_expr(mk().mac(
            mk().path(ident),
            ts,
            MacroDelimiter::Paren(Default::default()),
        ))))
    }

    /// If `ctx` is unused, convert `expr` to a semi statement, otherwise return
    /// `expr`.
    fn convert_side_effects_expr(
        &self,
        ctx: ExprContext,
        expr: WithStmts<Box<Expr>>,
        panic_msg: &str,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        if ctx.is_unused() {
            // Recall that if `used` is false, the `stmts` field of the output must contain
            // all side-effects (and a function call can always have side-effects)
            expr.and_then(|expr| {
                Ok(WithStmts::new(
                    vec![mk().semi_stmt(expr)],
                    self.panic_or_err(panic_msg),
                ))
            })
        } else {
            Ok(expr)
        }
    }

    fn convert_statement_expression(
        &self,
        ctx: ExprContext,
        compound_stmt_id: CStmtId,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        fn as_semi_break_stmt(stmt: &Stmt, lbl: &cfg::Label) -> Option<Option<Box<Expr>>> {
            if let Stmt::Expr(
                Expr::Break(ExprBreak {
                    label: Some(blbl),
                    expr: ret_val,
                    ..
                }),
                Some(_),
            ) = stmt
            {
                if blbl.ident == mk().label(lbl.pretty_print()).name.ident {
                    return Some(ret_val.clone());
                }
            }
            None
        }

        match self.ast_context[compound_stmt_id].kind {
            CStmtKind::Compound(ref substmt_ids) if !substmt_ids.is_empty() => {
                let n = substmt_ids.len();
                let result_id = substmt_ids[n - 1];

                let name = format!("<stmt-expr_{:?}>", compound_stmt_id);
                let lbl_ident = self.renamer.borrow_mut().pick_name("c2rust_label");
                let lbl = cfg::Label::FromC(compound_stmt_id, Some(Rc::from(lbl_ident)));

                let mut stmts = match self.ast_context[result_id].kind {
                    CStmtKind::Expr(expr_id) => {
                        let ret = cfg::ImplicitReturnType::StmtExpr(ctx, expr_id, lbl.clone());
                        self.convert_function_body(ctx, &name, &substmt_ids[0..(n - 1)], None, ret)?
                    }

                    _ => self.convert_function_body(
                        ctx,
                        &name,
                        substmt_ids,
                        None,
                        cfg::ImplicitReturnType::Void,
                    )?,
                };

                if let Some(stmt) = stmts.pop() {
                    match as_semi_break_stmt(&stmt, &lbl) {
                        Some(val) => {
                            let block = mk().block_expr(match val {
                                Some(val) if ctx.is_used() => WithStmts::new(stmts, val).to_block(),
                                _ => mk().block(stmts),
                            });

                            // enclose block in parentheses to work around
                            // https://github.com/rust-lang/rust/issues/54482
                            let val = mk().paren_expr(block);
                            return self.convert_side_effects_expr(
                                ctx,
                                WithStmts::new_val(val),
                                "Compound statement expression is not supposed to be used",
                            );
                        }
                        _ => {
                            self.use_feature("label_break_value");
                            stmts.push(stmt)
                        }
                    }
                }

                let block_body = mk().block(stmts);
                let val: Box<Expr> = mk().labelled_block_expr(block_body, lbl.pretty_print());
                self.convert_side_effects_expr(
                    ctx,
                    WithStmts::new_val(val),
                    "Compound statement expression is not supposed to be used",
                )
            }
            _ => {
                if ctx.is_unused() {
                    let val =
                        self.panic_or_err("Empty statement expression is not supposed to be used");
                    Ok(WithStmts::new_val(val))
                } else {
                    Err(TranslationError::generic("Bad statement expression"))
                }
            }
        }
    }

    fn convert_cast(
        &self,
        ctx: ExprContext,
        source_cty: CQualTypeId,
        target_cty: CQualTypeId,
        val: WithStmts<Box<Expr>>,
        expr: Option<CExprId>,
        kind: Option<CastKind>,
        opt_field_id: Option<CFieldId>,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        let source_ty_kind = &self.ast_context.resolve_type(source_cty.ctype).kind;
        let target_ty_kind = &self.ast_context.resolve_type(target_cty.ctype).kind;

        if source_ty_kind == target_ty_kind {
            return Ok(val);
        }

        let kind = kind.unwrap_or_else(|| {
            match (source_ty_kind, target_ty_kind) {
                (CTypeKind::VariableArray(..), CTypeKind::Pointer(..))
                | (CTypeKind::ConstantArray(..), CTypeKind::Pointer(..))
                | (CTypeKind::IncompleteArray(..), CTypeKind::Pointer(..)) => {
                    CastKind::ArrayToPointerDecay
                }

                (CTypeKind::Function(..), CTypeKind::Pointer(..)) => {
                    CastKind::FunctionToPointerDecay
                }

                (_, CTypeKind::Pointer(..)) if source_ty_kind.is_integral_type() => {
                    CastKind::IntegralToPointer
                }

                (CTypeKind::Pointer(..), CTypeKind::Bool) => CastKind::PointerToBoolean,

                (CTypeKind::Pointer(..), _) if target_ty_kind.is_integral_type() => {
                    CastKind::PointerToIntegral
                }

                (_, CTypeKind::Bool) if source_ty_kind.is_integral_type() => {
                    CastKind::IntegralToBoolean
                }

                (CTypeKind::Bool, _) if target_ty_kind.is_signed_integral_type() => {
                    CastKind::BooleanToSignedIntegral
                }

                (_, _)
                    if source_ty_kind.is_integral_type() && target_ty_kind.is_integral_type() =>
                {
                    CastKind::IntegralCast
                }

                (_, _)
                    if source_ty_kind.is_integral_type() && target_ty_kind.is_floating_type() =>
                {
                    CastKind::IntegralToFloating
                }

                (_, CTypeKind::Bool) if source_ty_kind.is_floating_type() => {
                    CastKind::FloatingToBoolean
                }

                (_, _)
                    if source_ty_kind.is_floating_type() && target_ty_kind.is_integral_type() =>
                {
                    CastKind::FloatingToIntegral
                }

                (_, _)
                    if source_ty_kind.is_floating_type() && target_ty_kind.is_floating_type() =>
                {
                    CastKind::FloatingCast
                }

                (CTypeKind::Pointer(..), CTypeKind::Pointer(..)) => CastKind::BitCast,

                // Ignoring Complex casts for now
                _ => {
                    warn!(
                        "Unknown CastKind for {:?} to {:?} cast. Defaulting to BitCast",
                        source_ty_kind, target_ty_kind,
                    );

                    CastKind::BitCast
                }
            }
        });

        match kind {
            CastKind::BitCast | CastKind::NoOp => {
                if self.ast_context.is_function_pointer(target_cty.ctype)
                    || self.ast_context.is_function_pointer(source_cty.ctype)
                {
                    let source_ty = self
                        .type_converter
                        .borrow_mut()
                        .convert(&self.ast_context, source_cty.ctype)?;
                    let target_ty = self
                        .type_converter
                        .borrow_mut()
                        .convert(&self.ast_context, target_cty.ctype)?;

                    if source_ty == target_ty {
                        return Ok(val);
                    }

                    self.import_type(source_cty.ctype);
                    self.import_type(target_cty.ctype);

                    val.and_then(|val| {
                        Ok(WithStmts::new_unsafe_val(transmute_expr(
                            source_ty, target_ty, val,
                        )))
                    })
                } else {
                    // Normal case
                    let target_ty = self.convert_type(target_cty.ctype)?;
                    Ok(val.map(|val| mk().cast_expr(val, target_ty)))
                }
            }

            CastKind::IntegralToPointer
                if self.ast_context.is_function_pointer(target_cty.ctype) =>
            {
                let target_ty = self.convert_type(target_cty.ctype)?;
                val.and_then(|x| {
                    self.use_crate(ExternCrate::Libc);
                    let intptr_t = mk().abs_path_ty(vec!["libc", "intptr_t"]);
                    let intptr = mk().cast_expr(x, intptr_t.clone());
                    if ctx.is_const {
                        return Err(format_translation_err!(
                            None,
                            "cannot transmute integers to Option<fn ...> in `const` context",
                        ));
                    }
                    Ok(WithStmts::new_unsafe_val(transmute_expr(
                        intptr_t, target_ty, intptr,
                    )))
                })
            }

            CastKind::IntegralToPointer
            | CastKind::PointerToIntegral
            | CastKind::IntegralCast
            | CastKind::FloatingCast
            | CastKind::FloatingToIntegral
            | CastKind::IntegralToFloating
            | CastKind::BooleanToSignedIntegral => {
                if kind == CastKind::PointerToIntegral && ctx.is_const {
                    return Err(format_translation_err!(
                        None,
                        "cannot observe pointer values in `const` context",
                    ));
                }
                let target_ty = self.convert_type(target_cty.ctype)?;
                let source_ty = self.convert_type(source_cty.ctype)?;

                if let CTypeKind::LongDouble = target_ty_kind {
                    if ctx.is_const {
                        return Err(format_translation_err!(
                                None,
                                "f128 cannot be used in constants because `f128::f128::new` is not `const`",
                            ));
                    }

                    self.use_crate(ExternCrate::F128);

                    let fn_path = mk().abs_path_expr(vec!["f128", "f128", "new"]);
                    Ok(val.map(|val| mk().call_expr(fn_path, vec![val])))
                } else if let CTypeKind::LongDouble = self.ast_context[source_cty.ctype].kind {
                    self.f128_cast_to(val, target_ty_kind)
                } else if let &CTypeKind::Enum(enum_decl_id) = target_ty_kind {
                    // Casts targeting `enum` types...
                    let expr =
                        expr.ok_or_else(|| format_err!("Casts to enums require a C ExprId"))?;
                    Ok(self.enum_cast(
                        target_cty.ctype,
                        enum_decl_id,
                        expr,
                        val,
                        source_ty,
                        target_ty,
                    ))
                } else if target_ty_kind.is_floating_type() && source_ty_kind.is_bool() {
                    val.and_then(|x| {
                        Ok(WithStmts::new_val(mk().cast_expr(
                            mk().cast_expr(x, mk().path_ty(vec!["u8"])),
                            target_ty,
                        )))
                    })
                } else if target_ty_kind.is_pointer() && source_ty_kind.is_bool() {
                    val.and_then(|x| {
                        self.use_crate(ExternCrate::Libc);
                        Ok(WithStmts::new_val(mk().cast_expr(
                            mk().cast_expr(x, mk().abs_path_ty(vec!["libc", "size_t"])),
                            target_ty,
                        )))
                    })
                } else {
                    // Other numeric casts translate to Rust `as` casts,
                    // unless the cast is to a function pointer then use `transmute`.
                    val.and_then(|x| {
                        if self.ast_context.is_function_pointer(source_cty.ctype) {
                            Ok(WithStmts::new_unsafe_val(transmute_expr(
                                source_ty, target_ty, x,
                            )))
                        } else {
                            Ok(WithStmts::new_val(mk().cast_expr(x, target_ty)))
                        }
                    })
                }
            }

            CastKind::LValueToRValue | CastKind::ToVoid | CastKind::ConstCast => Ok(val),

            CastKind::FunctionToPointerDecay | CastKind::BuiltinFnToFnPtr => {
                Ok(val.map(|x| mk().call_expr(mk().ident_expr("Some"), vec![x])))
            }

            CastKind::ArrayToPointerDecay => {
                self.convert_array_to_pointer_decay(ctx, source_cty, target_cty, val, expr)
            }

            CastKind::NullToPointer => {
                assert!(val.stmts().is_empty());
                Ok(WithStmts::new_val(
                    self.null_ptr(target_cty.ctype, ctx.is_static)?,
                ))
            }

            CastKind::ToUnion => {
                let field_id = opt_field_id.expect("Missing field ID in union cast");
                let union_id = self.ast_context.parents[&field_id];

                let union_name = self
                    .type_converter
                    .borrow()
                    .resolve_decl_name(union_id)
                    .expect("required union name");
                let field_name = self
                    .type_converter
                    .borrow()
                    .resolve_field_name(Some(union_id), field_id)
                    .expect("field name required");

                Ok(val.map(|x| {
                    mk().struct_expr(mk().path(vec![union_name]), vec![mk().field(field_name, x)])
                }))
            }

            CastKind::IntegralToBoolean
            | CastKind::FloatingToBoolean
            | CastKind::PointerToBoolean => {
                if let Some(expr) = expr {
                    self.convert_condition(ctx, true, expr)
                } else {
                    val.result_map(|e| self.match_bool(ctx, true, source_cty.ctype, e))
                }
            }

            CastKind::FloatingRealToComplex
            | CastKind::FloatingComplexToIntegralComplex
            | CastKind::FloatingComplexCast
            | CastKind::FloatingComplexToReal
            | CastKind::IntegralComplexToReal
            | CastKind::IntegralRealToComplex
            | CastKind::IntegralComplexCast
            | CastKind::IntegralComplexToFloatingComplex
            | CastKind::IntegralComplexToBoolean => Err(TranslationError::generic(
                "TODO casts with complex numbers not supported",
            )),

            CastKind::VectorSplat => Err(TranslationError::generic(
                "TODO vector splat casts not supported",
            )),

            CastKind::AtomicToNonAtomic | CastKind::NonAtomicToAtomic => Ok(val),
        }
    }

    /// Cast a f128 to some other int or float type
    fn f128_cast_to(
        &self,
        val: WithStmts<Box<Expr>>,
        target_ty_ctype: &CTypeKind,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        self.use_crate(ExternCrate::NumTraits);

        self.with_cur_file_item_store(|item_store| {
            item_store.add_use(true, vec!["num_traits".into()], "ToPrimitive");
        });
        let to_method_name = match target_ty_ctype {
            CTypeKind::Float => "to_f32",
            CTypeKind::Double => "to_f64",
            CTypeKind::Char => "to_i8",
            CTypeKind::UChar => "to_u8",
            CTypeKind::Short => "to_i16",
            CTypeKind::UShort => "to_u16",
            CTypeKind::Int => "to_i32",
            CTypeKind::UInt => "to_u32",
            CTypeKind::Long => "to_i64",
            CTypeKind::ULong => "to_u64",
            CTypeKind::LongLong => "to_i64",
            CTypeKind::ULongLong => "to_u64",
            CTypeKind::Int128 => "to_i128",
            CTypeKind::UInt128 => "to_u128",
            _ => {
                return Err(format_err!(
                    "Tried casting long double to unsupported type: {:?}",
                    target_ty_ctype
                )
                .into());
            }
        };

        Ok(val.map(|val| {
            let to_call = mk().method_call_expr(val, to_method_name, Vec::new());

            mk().method_call_expr(to_call, "unwrap", Vec::new())
        }))
    }

    /// This handles translating casts when the target type in an `enum` type.
    ///
    /// When translating variable references to `EnumConstant`'s, we always insert casts to the
    /// expected type. In C, `EnumConstants` have some integral type, _not_ the enum type. However,
    /// if we then immediately have a cast to convert this variable back into an enum type, we would
    /// like to produce Rust with _no_ casts. This function handles this simplification.
    fn enum_cast(
        &self,
        enum_type: CTypeId,
        enum_decl: CEnumId, // ID of the enum declaration corresponding to the target type
        expr: CExprId,      // ID of initial C argument to cast
        val: WithStmts<Box<Expr>>, // translated Rust argument to cast
        _source_ty: Box<Type>, // source type of cast
        target_ty: Box<Type>, // target type of cast
    ) -> WithStmts<Box<Expr>> {
        // Extract the IDs of the `EnumConstant` decls underlying the enum.
        let variants = match self.ast_context.index(enum_decl).kind {
            CDeclKind::Enum { ref variants, .. } => variants,
            _ => panic!("{:?} does not point to an `enum` declaration", enum_decl),
        };

        match self.ast_context.index(expr).kind {
            // This is the case of finding a variable which is an `EnumConstant` of the same enum
            // we are casting to. Here, we can just remove the extraneous cast instead of generating
            // a new one.
            CExprKind::DeclRef(_, decl_id, _) if variants.contains(&decl_id) => {
                return val.map(|x| match *unparen(&x) {
                    Expr::Cast(ExprCast { ref expr, .. }) => expr.clone(),
                    // If this DeclRef expanded to a const macro, we actually need to insert a cast,
                    // because the translation of a const macro skips implicit casts in its context.
                    Expr::Path(..) => mk().cast_expr(x, target_ty),
                    _ => panic!(
                        "DeclRef {:?} of enum {:?} is not cast: {x:?}",
                        expr, enum_decl
                    ),
                });
            }

            CExprKind::Literal(_, CLiteral::Integer(i, _)) => {
                return val.map(|_| self.enum_for_i64(enum_type, i as i64));
            }

            CExprKind::Unary(_, c_ast::UnOp::Negate, subexpr_id, _) => {
                if let &CExprKind::Literal(_, CLiteral::Integer(i, _)) =
                    &self.ast_context[subexpr_id].kind
                {
                    return val.map(|_| self.enum_for_i64(enum_type, -(i as i64)));
                }
            }

            // In all other cases, a cast to an enum requires a `transmute` - Rust enums cannot be
            // converted into integral types as easily as C ones.
            _ => {}
        }

        val.map(|x| mk().cast_expr(x, target_ty))
    }

    pub fn implicit_default_expr(
        &self,
        ty_id: CTypeId,
        is_static: bool,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        if self.ast_context.is_va_list(ty_id) {
            // generate MaybeUninit::uninit().assume_init()
            let path = vec!["core", "mem", "MaybeUninit", "uninit"];
            let call = mk().call_expr(mk().abs_path_expr(path), vec![]);
            let call = mk().method_call_expr(call, "assume_init", vec![]);
            return Ok(WithStmts::new_val(call));
        }

        let resolved_ty_id = self.ast_context.resolve_type_id(ty_id);
        let resolved_ty = &self.ast_context.index(resolved_ty_id).kind;

        if resolved_ty.is_bool() {
            Ok(WithStmts::new_val(mk().lit_expr(mk().bool_lit(false))))
        } else if resolved_ty.is_integral_type() {
            Ok(WithStmts::new_val(
                mk().lit_expr(mk().int_unsuffixed_lit(0)),
            ))
        } else if resolved_ty.is_floating_type() {
            match self.ast_context[ty_id].kind {
                CTypeKind::LongDouble => {
                    self.use_crate(ExternCrate::F128);
                    Ok(WithStmts::new_val(
                        mk().abs_path_expr(vec!["f128", "f128", "ZERO"]),
                    ))
                }
                _ => Ok(WithStmts::new_val(
                    mk().lit_expr(mk().float_unsuffixed_lit("0.")),
                )),
            }
        } else if let &CTypeKind::Pointer(_) = resolved_ty {
            self.null_ptr(resolved_ty_id, is_static)
                .map(WithStmts::new_val)
        } else if let &CTypeKind::ConstantArray(elt, sz) = resolved_ty {
            let sz = mk().lit_expr(mk().int_unsuffixed_lit(sz as u128));
            Ok(self
                .implicit_default_expr(elt, is_static)?
                .map(|elt| mk().repeat_expr(elt, sz)))
        } else if let &CTypeKind::IncompleteArray(_) = resolved_ty {
            // Incomplete arrays are translated to zero length arrays
            Ok(WithStmts::new_val(mk().array_expr(vec![])))
        } else if let Some(decl_id) = resolved_ty.as_underlying_decl() {
            self.zero_initializer(decl_id, ty_id, is_static)
        } else if let &CTypeKind::VariableArray(elt, _) = resolved_ty {
            // Variable length arrays unnested and implemented as a flat array of the underlying
            // element type.

            // Find base element type of potentially nested arrays
            let inner = self.variable_array_base_type(elt);
            let count = self.compute_size_of_expr(ty_id).unwrap();
            Ok(self
                .implicit_default_expr(inner, is_static)?
                .map(|val| vec_expr(val, count)))
        } else if let &CTypeKind::Vector(CQualTypeId { ctype, .. }, len) = resolved_ty {
            self.implicit_vector_default(ctype, len, is_static)
        } else {
            Err(format_err!("Unsupported default initializer: {:?}", resolved_ty).into())
        }
    }

    /// Produce zero-initializers for structs/unions/enums, looking them up when possible.
    fn zero_initializer(
        &self,
        decl_id: CDeclId,
        type_id: CTypeId,
        is_static: bool,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        self.import_type(type_id);

        let name = self.type_converter.borrow().resolve_decl_name(decl_id);
        let name = name.as_deref().unwrap_or("???");

        // Look up the decl in the cache and return what we find (if we find anything)
        if let Some((init, imports)) = self.zero_inits.borrow().get(&decl_id) {
            self.add_imports(imports);
            log::debug!("looked up imports for {name}: {imports:?}");
            return Ok(init.clone());
        }

        let func_name = &self.function_context.borrow().name;
        let func_name = func_name.as_deref().unwrap_or("<none>");
        log::debug!("deferring imports to save them for {name} in {func_name}");
        self.defer_imports();

        let name_decl_id = match self.ast_context.index(type_id).kind {
            CTypeKind::Typedef(decl_id) => decl_id,
            _ => decl_id,
        };

        // Otherwise, construct the initializer
        let mut init = match self.ast_context.index(decl_id).kind {
            // Zero initialize all of the fields
            CDeclKind::Struct {
                fields: Some(ref fields),
                platform_byte_size,
                ..
            } => self.convert_struct_zero_initializer(
                decl_id,
                name_decl_id,
                fields,
                platform_byte_size,
                is_static,
            )?,

            CDeclKind::Struct { fields: None, .. } => {
                return Err(TranslationError::generic(
                    "Attempted to zero-initialize forward-declared struct",
                ));
            }

            // Zero initialize the first field
            CDeclKind::Union { ref fields, .. } => {
                let name = self
                    .type_converter
                    .borrow()
                    .resolve_decl_name(decl_id)
                    .unwrap();

                let fields = match *fields {
                    Some(ref fields) => fields,
                    None => {
                        return Err(TranslationError::generic(
                            "Attempted to zero-initialize forward-declared struct",
                        ));
                    }
                };

                let &field_id = fields
                    .first()
                    .ok_or_else(|| format_err!("A union should have a field"))?;

                let field = match self.ast_context.index(field_id).kind {
                    CDeclKind::Field { typ, .. } => self
                        .implicit_default_expr(typ.ctype, is_static)?
                        .map(|field_init| {
                            let name = self
                                .type_converter
                                .borrow()
                                .resolve_field_name(Some(decl_id), field_id)
                                .unwrap();

                            mk().field(name, field_init)
                        }),
                    _ => {
                        return Err(TranslationError::generic(
                            "Found non-field in record field list",
                        ));
                    }
                };

                field.map(|field| mk().struct_expr(vec![name], vec![field]))
            }

            // Transmute the number `0` into the enum type
            CDeclKind::Enum { .. } => WithStmts::new_val(self.enum_for_i64(type_id, 0)),

            _ => {
                return Err(TranslationError::generic(
                    "Declaration is not associated with a type",
                ));
            }
        };

        if self.ast_context.has_inner_struct_decl(name_decl_id) {
            // If the structure is split into an outer/inner,
            // wrap the inner initializer using the outer structure
            let outer_name = self
                .type_converter
                .borrow()
                .resolve_decl_name(name_decl_id)
                .unwrap();

            let outer_path = mk().path_expr(vec![outer_name]);
            init = init.map(|i| mk().call_expr(outer_path, vec![i]));
        };

        if init.is_pure() {
            // Insert the initializer into the cache, then return it
            let imports = self.stop_deferring_imports();
            log::debug!("saving imports for {name}: {imports:?}");
            self.zero_inits
                .borrow_mut()
                .insert(decl_id, (init.clone(), imports));
            Ok(init)
        } else {
            Err(TranslationError::generic(
                "Expected no statements in zero initializer",
            ))
        }
    }

    /// Resolve the inner name of a structure declaration
    /// if there is one (if the structure was split),
    /// otherwise just return the normal name
    fn resolve_decl_inner_name(&self, decl_id: CDeclId) -> String {
        if self.ast_context.has_inner_struct_decl(decl_id) {
            self.type_converter
                .borrow_mut()
                .resolve_decl_suffix_name(decl_id, INNER_SUFFIX)
                .to_owned()
        } else {
            self.type_converter
                .borrow()
                .resolve_decl_name(decl_id)
                .unwrap()
        }
    }

    /// Convert a boolean expression to a boolean for use in && or || or if
    fn match_bool(
        &self,
        ctx: ExprContext,
        target: bool,
        ty_id: CTypeId,
        val: Box<Expr>,
    ) -> TranslationResult<Box<Expr>> {
        let ty = &self.ast_context.resolve_type(ty_id).kind;

        Ok(if self.ast_context.is_function_pointer(ty_id) {
            if target {
                mk().method_call_expr(val, "is_some", vec![])
            } else {
                mk().method_call_expr(val, "is_none", vec![])
            }
        } else if ty.is_pointer() {
            // TODO: `pointer::is_null` becomes stably const in Rust 1.84.
            if ctx.is_const {
                return Err(format_translation_err!(
                    None,
                    "cannot check nullity of pointer in `const` context",
                ));
            }
            let mut res = mk().method_call_expr(val, "is_null", vec![]);
            if target {
                res = mk().unary_expr(UnOp::Not(Default::default()), res)
            }
            res
        } else if ty.is_bool() {
            if target {
                val
            } else {
                mk().unary_expr(UnOp::Not(Default::default()), val)
            }
        } else {
            // One simplification we can make at the cost of inspecting `val` more closely: if `val`
            // is already in the form `(x <op> y) as <ty>` where `<op>` is a Rust operator
            // that returns a boolean, we can simple output `x <op> y` or `!(x <op> y)`.
            if let Expr::Cast(ExprCast { expr: ref arg, .. }) = *unparen(&val) {
                if let Expr::Binary(ExprBinary {
                    op:
                        BinOp::Or(_)
                        | BinOp::And(_)
                        | BinOp::Eq(_)
                        | BinOp::Ne(_)
                        | BinOp::Lt(_)
                        | BinOp::Le(_)
                        | BinOp::Gt(_)
                        | BinOp::Ge(_),
                    ..
                }) = *unparen(arg)
                {
                    return Ok(if target {
                        // If target == true, just return the argument
                        Box::new(unparen(arg).clone())
                    } else {
                        // If target == false, return !arg
                        mk().unary_expr(
                            UnOp::Not(Default::default()),
                            Box::new(unparen(arg).clone()),
                        )
                    });
                }
            }

            let val = if ty.is_enum() {
                mk().cast_expr(val, mk().path_ty(vec!["u64"]))
            } else {
                val
            };

            // The backup is to just compare against zero
            let zero = if ty.is_floating_type() {
                mk().lit_expr(mk().float_unsuffixed_lit("0."))
            } else {
                mk().lit_expr(mk().int_unsuffixed_lit(0))
            };

            if target {
                mk().binary_expr(BinOp::Ne(Default::default()), val, zero)
            } else {
                mk().binary_expr(BinOp::Eq(Default::default()), val, zero)
            }
        })
    }

    pub fn with_scope<F, A>(&self, f: F) -> A
    where
        F: FnOnce() -> A,
    {
        self.renamer.borrow_mut().add_scope();
        let result = f();
        self.renamer.borrow_mut().drop_scope();
        result
    }

    /// If we're trying to organize item definitions into submodules, add them to a module
    /// scoped "namespace" if we have a path available, otherwise add it to the global "namespace"
    fn insert_item(&self, mut item: Box<Item>, decl: &CDecl) {
        let decl_file_id = self.ast_context.file_id(decl);

        if self.tcfg.reorganize_definitions {
            self.use_feature("register_tool");
            let attrs = item_attrs(&mut item).expect("no attrs field on unexpected item variant");
            add_src_loc_attr(attrs, &decl.loc.as_ref().map(|x| x.begin()));
            let mut item_stores = self.items.borrow_mut();
            let items = item_stores.entry(decl_file_id.unwrap()).or_default();

            items.add_item(item);
        } else {
            self.items.borrow_mut()[&self.main_file].add_item(item)
        }
    }

    /// If we're trying to organize foreign item definitions into submodules, add them to a module
    /// scoped "namespace" if we have a path available, otherwise add it to the global "namespace"
    fn insert_foreign_item(&self, mut item: ForeignItem, decl: &CDecl) {
        let decl_file_id = self.ast_context.file_id(decl);

        if self.tcfg.reorganize_definitions {
            self.use_feature("register_tool");
            let attrs = foreign_item_attrs(&mut item)
                .expect("no attrs field on unexpected foreign item variant");
            add_src_loc_attr(attrs, &decl.loc.as_ref().map(|x| x.begin()));
            let mut items = self.items.borrow_mut();
            let mod_block_items = items.entry(decl_file_id.unwrap()).or_default();

            mod_block_items.add_foreign_item(item);
        } else {
            self.items.borrow_mut()[&self.main_file].add_foreign_item(item)
        }
    }

    /// Directly add a top-level `use` for the given decl.
    ///
    /// Should not be directly called from any recursive translation steps. Instead,
    /// call `add_import`, which supports deferring imports to allow caching translation
    /// of subexpressions while tracking the requisite imports.
    fn add_use_item(&self, decl_file_id: FileId, decl_id: CDeclId, ident_name: &str) {
        assert!(!self.deferring_imports());

        let decl = &self.ast_context[decl_id];
        let import_file_id = self.ast_context.file_id(decl);

        // If the definition lives in the same header, there is no need to import it
        // in fact, this would be a hard rust error.
        // We should never import into the main module here, as that happens in make_submodule
        if import_file_id == Some(decl_file_id) || decl_file_id == self.main_file {
            return;
        }

        // TODO: get rid of this, not compatible with nested modules
        let mut module_path = vec!["super".into()];

        // If the decl does not live in the main module add the path to the sibling submodule
        if let Some(file_id) = import_file_id {
            if file_id != self.main_file {
                let file_name =
                    clean_path(&self.mod_names, self.ast_context.get_file_path(file_id));

                module_path.push(file_name);
            }
        }

        self.items
            .borrow_mut()
            .entry(decl_file_id)
            .or_default()
            .add_use(false, module_path, ident_name);
    }

    /// Mark an import as required by the translated code.
    /// `decl_id` is the definition to import
    fn add_import(&self, decl_id: CDeclId, ident_name: &str) {
        // If deferring imports, store and return.
        if self.deferring_imports() {
            self.deferred_imports
                .borrow_mut()
                .last_mut()
                .unwrap()
                .insert(Import {
                    decl_id,
                    ident_name: ident_name.into(),
                });
        } else {
            self.add_use_item(self.cur_file(), decl_id, ident_name)
        }
    }

    fn add_imports(&self, imports: &IndexSet<Import>) {
        for Import {
            decl_id,
            ident_name,
        } in imports
        {
            self.add_import(*decl_id, ident_name)
        }
    }

    /// Delay the addition of imports until [`Self::stop_deferring_imports`] is called.
    fn defer_imports(&self) {
        self.deferred_imports.borrow_mut().push(Default::default())
    }

    /// Return whether imports are currently being deferred for later emission.
    fn deferring_imports(&self) -> bool {
        !self.deferred_imports.borrow().is_empty()
    }

    /// Apply and clear the last set of deferred imports. Returns the imports applied.
    /// Must be called to match a previous call to [`Self::defer_imports`]; will panic
    /// otherwise.
    fn stop_deferring_imports(&self) -> IndexSet<Import> {
        let mut deferred = self
            .deferred_imports
            .borrow_mut()
            .pop()
            .expect("`stop_deferring_imports` called without matching call to `defer_imports`");
        for imports in self.deferred_imports.borrow().iter() {
            deferred.extend(imports.clone());
        }
        self.add_imports(&deferred);
        deferred
    }

    fn import_type(&self, ctype: CTypeId) {
        self.add_imports(&self.imports_for_type(ctype))
    }

    fn imports_for_type(&self, ctype: CTypeId) -> IndexSet<Import> {
        use self::CTypeKind::*;

        let mut imports = IndexSet::default();

        let type_kind = &self.ast_context[ctype].kind;
        match type_kind {
            // libc can be accessed from anywhere as of Rust 2019 by full path
            Void | Char | SChar | UChar | Short | UShort | Int | UInt | Long | ULong | LongLong
            | ULongLong | Int128 | UInt128 | Half | BFloat16 | Float | Double | LongDouble
            | Float128 => {}
            // other libc types
            WChar | IntMax | UIntMax => {}
            // Built-in Rust sized types
            Int8 | Int16 | Int32 | Int64 | IntPtr | UInt8 | UInt16 | UInt32 | UInt64 | UIntPtr
            | Size | SSize | PtrDiff => {}
            // Bool uses the bool type, so no dependency on libc
            Bool => {}
            Paren(ctype)
            | Decayed(ctype)
            | IncompleteArray(ctype)
            | ConstantArray(ctype, _)
            | Elaborated(ctype)
            | Pointer(CQualTypeId { ctype, .. })
            | Attributed(CQualTypeId { ctype, .. }, _)
            | VariableArray(ctype, _)
            | Reference(CQualTypeId { ctype, .. })
            | BlockPointer(CQualTypeId { ctype, .. })
            | TypeOf(ctype)
            | Complex(ctype) => imports.extend(self.imports_for_type(*ctype)),
            Enum(decl_id) | Typedef(decl_id) | Union(decl_id) | Struct(decl_id) => {
                let mut decl_id = *decl_id;
                // if the `decl` has been "squashed", get the corresponding `decl_id`
                if self.ast_context.prenamed_decls.contains_key(&decl_id) {
                    decl_id = *self.ast_context.prenamed_decls.get(&decl_id).unwrap();
                }

                let ident_name = self
                    .type_converter
                    .borrow()
                    .resolve_decl_name(decl_id)
                    .expect("Expected decl name");
                imports.insert(Import {
                    decl_id,
                    ident_name,
                });
            }
            Function(CQualTypeId { ctype, .. }, ref params, ..) => {
                // Return Type
                let type_kind = &self.ast_context[*ctype].kind;

                // Rust doesn't use void for return type, so skip
                if *type_kind != Void {
                    imports.extend(self.imports_for_type(*ctype));
                }

                // Param Types
                for param_id in params {
                    imports.extend(self.imports_for_type(param_id.ctype))
                }
            }
            Vector(..) => {
                // Handled in `import_simd_typedef`
            }
            TypeOfExpr(_) | BuiltinFn | Atomic(..) => {}
            UnhandledSveType => {
                // TODO: handle SVE types
            }
        }
        imports
    }

    fn generate_submodule_imports(&self, decl_id: CDeclId, decl_file_id: Option<FileId>) {
        let decl_file_id = decl_file_id.expect("There should be a decl file path");
        let decl = self.ast_context.get_decl(&decl_id).unwrap();

        let add_use_items_for_type = |ctype| {
            for Import {
                decl_id,
                ident_name,
            } in self.imports_for_type(ctype)
            {
                self.add_use_item(decl_file_id, decl_id, &ident_name)
            }
        };

        match decl.kind {
            CDeclKind::Struct { ref fields, .. } | CDeclKind::Union { ref fields, .. } => {
                let field_ids = fields.as_ref().map(|vec| vec.as_slice()).unwrap_or(&[]);

                for field_id in field_ids.iter() {
                    match self.ast_context[*field_id].kind {
                        CDeclKind::Field { typ, .. } => add_use_items_for_type(typ.ctype),
                        _ => unreachable!("Found something in a struct other than a field"),
                    }
                }
            }
            CDeclKind::EnumConstant { .. } | CDeclKind::Enum { .. } => {}

            CDeclKind::Variable {
                has_static_duration: true,
                is_externally_visible: true,
                typ,
                ..
            }
            | CDeclKind::Variable {
                has_thread_duration: true,
                is_externally_visible: true,
                typ,
                ..
            }
            | CDeclKind::Typedef { typ, .. } => add_use_items_for_type(typ.ctype),
            CDeclKind::Function {
                is_global: true,
                typ,
                ..
            } => add_use_items_for_type(typ),

            CDeclKind::MacroObject { .. } => {
                if let Some(Some(expansion)) = self.macro_expansions.borrow().get(&decl_id) {
                    add_use_items_for_type(expansion.ty)
                }
            }

            CDeclKind::Function { .. } | CDeclKind::MacroFunction { .. } => {
                // TODO: We may need to explicitly skip SIMD functions here when getting types for
                // a fn definition in a header since SIMD headers define functions but we're using imports
                // rather than translating the original definition
            }
            CDeclKind::Variable {
                has_static_duration,
                has_thread_duration,
                is_externally_visible: false,
                ..
            } if has_static_duration || has_thread_duration => {}
            ref e => unimplemented!("{:?}", e),
        }
    }
}