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
use std::cell::RefCell;
use std::fmt::{self, Debug, Display};
use std::ops::Index;
use std::path::{self, PathBuf};
use std::sync::Arc;
use std::{char, io, mem};

use dtoa;

use failure::{err_msg, Backtrace, Context, Error, Fail};
use indexmap::{IndexMap, IndexSet};

use rustc_data_structures::sync::Lrc;
use syntax::ast::*;
use syntax::parse::token::{DelimToken, Nonterminal, Token};
use syntax::print::pprust::*;
use syntax::ptr::*;
use syntax::tokenstream::{TokenStream, TokenTree};
use syntax::{ast, with_globals};
use syntax_pos::{Span, DUMMY_SP};

use c2rust_ast_builder::{mk, Builder};
use rust_ast::comment_store::CommentStore;
use rust_ast::item_store::ItemStore;
use rust_ast::traverse::Traversal;

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

mod assembly;
mod bitfields;
mod builtins;
mod literals;
mod main_function;
mod named_references;
mod operators;
mod simd;
mod variadic;

use crate::PragmaVec;
use crate::CrateSet;

#[derive(Debug, Clone)]
pub struct TranslationError {
    loc: Option<SrcLoc>,
    inner: Arc<Context<TranslationErrorKind>>,
}

#[derive(Clone, Eq, PartialEq, Debug)]
pub enum TranslationErrorKind {
    Generic,

    // Not enough simd intrinsics are available in LLVM < 7
    OldLLVMSimd,

    // We are waiting for va_copy support to land in rustc
    VaCopyNotImplemented,
}

impl Display for TranslationErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::TranslationErrorKind::*;
        match self {
            Generic => {}

            OldLLVMSimd => {
                if let Some(version) = get_clang_major_version() {
                    if version < 7 {
                        return write!(f, "SIMD intrinsics require LLVM 7 or newer. Please build C2Rust against a newer LLVM version.");
                    }
                }
            }

            VaCopyNotImplemented => {
                return write!(f, "Rust does not yet support a C-compatible va_copy which is required to translate this function. See https://github.com/rust-lang/rust/pull/59625");
            }
        }
        Ok(())
    }
}

impl Fail for TranslationError {
    fn cause(&self) -> Option<&Fail> {
        self.inner.cause()
    }

    fn backtrace(&self) -> Option<&Backtrace> {
        self.inner.backtrace()
    }
}

impl Display for TranslationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ref loc) = self.loc {
            write!(f, "{}\n    ", loc)?;
        }
        Debug::fmt(&*self.inner, f)
    }
}

impl TranslationError {
    pub fn kind(&self) -> TranslationErrorKind {
        self.inner.get_context().clone()
    }

    pub fn new(loc: &Option<SrcLoc>, inner: Context<TranslationErrorKind>) -> Self {
        TranslationError {
            loc: loc.clone(),
            inner: Arc::new(inner),
        }
    }

    pub fn generic(msg: &'static str) -> Self {
        TranslationError {
            loc: None,
            inner: Arc::new(err_msg(msg).context(TranslationErrorKind::Generic)),
        }
    }
}

impl From<&'static str> for TranslationError {
    fn from(msg: &'static str) -> TranslationError {
        TranslationError {
            loc: None,
            inner: Arc::new(err_msg(msg).context(TranslationErrorKind::Generic)),
        }
    }
}

impl From<Error> for TranslationError {
    fn from(e: Error) -> TranslationError {
        TranslationError {
            loc: None,
            inner: Arc::new(e.context(TranslationErrorKind::Generic)),
        }
    }
}

impl From<TranslationErrorKind> for TranslationError {
    fn from(kind: TranslationErrorKind) -> TranslationError {
        TranslationError {
            loc: None,
            inner: Arc::new(Context::new(kind)),
        }
    }
}

impl From<Context<TranslationErrorKind>> for TranslationError {
    fn from(ctx: Context<TranslationErrorKind>) -> TranslationError {
        TranslationError {
            loc: None,
            inner: Arc::new(ctx),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
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,
}

#[derive(Copy, Clone, Debug)]
pub struct ExprContext {
    used: bool,
    is_static: bool,
    decay_ref: DecayRef,
    is_bitfield_write: bool,
    needs_address: bool,
}

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 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
        }
    }
}

#[derive(Clone, Debug)]
pub struct FunContext {
    /// The name of the function we're currently translating
    name: Option<String>,
    /// The va_list decl that we promote to a Rust function arg
    promoted_va_decl: Option<CDeclId>,
    /// The va_list decls that we did not promote because they were `va_copy`ed.
    copied_va_decls: Option<IndexSet<CDeclId>>,
}

impl FunContext {
    pub fn new() -> Self {
        FunContext {
            name: None,
            promoted_va_decl: None,
            copied_va_decls: None,
        }
    }

    pub fn enter_new(&mut self, fn_name: &str) {
        self.name = Some(fn_name.to_string());
        self.promoted_va_decl = None;
        self.copied_va_decls = None;
    }

    pub fn get_name<'a>(&'a self) -> &'a str {
        return self.name.as_ref().unwrap();
    }
}

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

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

    // Translation state and utilities
    type_converter: RefCell<TypeConverter>,
    renamer: RefCell<Renamer<CDeclId>>,
    zero_inits: RefCell<IndexMap<CDeclId, Result<P<Expr>, TranslationError>>>,
    function_context: RefCell<FunContext>,

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

    // Mod block defintion reorganization
    mod_blocks: RefCell<IndexMap<PathBuf, ItemStore>>,

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

    // The file that the translator is operating on w/o its extension
    main_file: PathBuf,
}

fn simple_metaitem(name: &str) -> NestedMetaItem {
    let meta_item = mk().meta_item(vec![name], MetaItemKind::Word);

    mk().nested_meta_item(NestedMetaItem::MetaItem(meta_item))
}

fn cast_int(val: P<Expr>, name: &str) -> P<Expr> {
    let opt_literal_val = match val.node {
        ExprKind::Lit(ref l) => match l.node {
            LitKind::Int(i, _) => Some(i),
            _ => None,
        },
        _ => None,
    };
    match opt_literal_val {
        Some(i) => mk().lit_expr(mk().int_lit(i, name)),
        None => mk().cast_expr(val, mk().path_ty(vec![name])),
    }
}

/// Pointer offset that casts its argument to isize
fn pointer_offset(ptr: P<Expr>, offset: P<Expr>) -> P<Expr> {
    pointer_offset_isize(ptr, cast_int(offset, "isize"))
}

/// Pointer offset that requires its argument to have type isize
fn pointer_offset_isize(ptr: P<Expr>, offset: P<Expr>) -> P<Expr> {
    mk().method_call_expr(ptr, "offset", vec![offset])
}

fn pointer_neg_offset(ptr: P<Expr>, offset: P<Expr>) -> P<Expr> {
    let offset = cast_int(offset, "isize");
    pointer_neg_offset_isize(ptr, offset)
}

fn pointer_neg_offset_isize(ptr: P<Expr>, offset: P<Expr>) -> P<Expr> {
    mk().method_call_expr(ptr, "offset", vec![mk().unary_expr(ast::UnOp::Neg, offset)])
}

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

fn transmute_expr(source_ty: P<Ty>, target_ty: P<Ty>, expr: P<Expr>, no_std: bool) -> P<Expr> {
    let type_args = match (&source_ty.node, &target_ty.node) {
        (TyKind::Infer, TyKind::Infer) => Vec::new(),
        (_, TyKind::Infer) => vec![source_ty],
        _ => vec![source_ty, target_ty],
    };
    let std_or_core = if no_std { "core" } else { "std" };
    let mut path = vec![
        mk().path_segment(""),
        mk().path_segment(std_or_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().path_expr(path), vec![expr])
}

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

pub fn stmts_block(mut stmts: Vec<Stmt>) -> P<Block> {
    if stmts.len() == 1 {
        if let StmtKind::Expr(ref e) = stmts[0].node {
            if let ExprKind::Block(ref b, None) = e.node {
                return b.clone();
            }
        }
    }

    if stmts.len() > 0 {
        let n = stmts.len() - 1;
        let s = stmts.remove(n);
        stmts.push(s.add_trailing_semicolon())
    }

    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 {
        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) -> P<Expr> {
    if value < 0 {
        mk().unary_expr(
            ast::UnOp::Neg,
            mk().lit_expr(mk().int_lit((-value) as u128, "")),
        )
    } 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 &mut translation.ast_context.c_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: &path::Path) -> String {
    fn path_to_str(path: &path::Path) -> String {
        path.file_name()
            .unwrap()
            .to_str()
            .unwrap()
            .replace('.', "_")
            .replace('-', "_")
    }

    let mut file_path: String = path_to_str(path);
    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 occured.
        // Ex: types.h can be included from
        // /usr/include/bits and /usr/include/sys
        if mod_path != path {
            let path_copy = path.to_path_buf();
            let split_path: Vec<PathBuf> = path_copy
                .parent()
                .unwrap()
                .iter()
                .map(|os| PathBuf::from(os))
                .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 translate_failure(tcfg: &TranspilerConfig, msg: &str) {
    if tcfg.fail_on_error {
        panic!("{}", msg)
    } else {
        eprintln!("{}", msg)
    }
}

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

    if t.tcfg.reorganize_definitions {
        t.use_feature("custom_attribute");
    }

    if tcfg.emit_no_std {
        t.extern_crates.borrow_mut().insert("core");
    }

    t.extern_crates.borrow_mut().insert("libc");

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

    enum Name<'a> {
        VarName(&'a str),
        TypeName(&'a str),
        AnonymousType,
        NoName,
    }

    fn some_type_name(s: Option<&str>) -> Name {
        match s {
            None => Name::AnonymousType,
            Some(r) => Name::TypeName(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);
    }

    // `with_globals` sets up a thread-local variable required by the syntax crate.
    with_globals(|| {
        // Identify typedefs that name unnamed types and collapse the two declarations
        // into a single name and declaration, eliminating the typedef altogether.
        for (&decl_id, decl) in &t.ast_context.c_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()
                {
                    let is_unnamed = match t.ast_context[subdecl_id].kind {
                        CDeclKind::Struct { name: None, .. }
                        | CDeclKind::Union { name: None, .. }
                        | CDeclKind::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 refering to the type name.
                        CDeclKind::Struct {
                            name: Some(ref target_name),
                            ..
                        }
                        | CDeclKind::Union {
                            name: Some(ref target_name),
                            ..
                        }
                        | CDeclKind::Enum {
                            name: Some(ref target_name),
                            ..
                        } => name == target_name,

                        _ => false,
                    };

                    if is_unnamed
                        && !t
                            .ast_context
                            .prenamed_decls
                            .values()
                            .find(|decl_id| *decl_id == &subdecl_id)
                            .is_some()
                    {
                        t.ast_context.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);
                    }
                }
            }
        }

        // 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().find(|id| *id == decl_id).is_some())
        }

        // Populate renamer with top-level names
        for (&decl_id, decl) in &t.ast_context.c_decls {
            let decl_name = match decl.kind {
                _ if contains(&t.ast_context.prenamed_decls, &decl_id) => Name::NoName,
                CDeclKind::Struct { ref name, .. } => {
                    some_type_name(name.as_ref().map(String::as_str))
                }
                CDeclKind::Enum { ref name, .. } => {
                    some_type_name(name.as_ref().map(String::as_str))
                }
                CDeclKind::Union { ref name, .. } => {
                    some_type_name(name.as_ref().map(String::as_str))
                }
                CDeclKind::Typedef { ref name, .. } => Name::TypeName(name),
                CDeclKind::Function { ref name, .. } => Name::VarName(name),
                CDeclKind::EnumConstant { ref name, .. } => Name::VarName(name),
                CDeclKind::Variable { ref ident, .. }
                    if t.ast_context.c_decls_top.contains(&decl_id) =>
                {
                    Name::VarName(ident)
                }
                _ => Name::NoName,
            };
            match decl_name {
                Name::NoName => (),
                Name::AnonymousType => {
                    t.type_converter
                        .borrow_mut()
                        .declare_decl_name(decl_id, "unnamed");
                }
                Name::TypeName(name) => {
                    t.type_converter
                        .borrow_mut()
                        .declare_decl_name(decl_id, name);
                }
                Name::VarName(name) => {
                    t.renamer.borrow_mut().insert(decl_id, &name);
                }
            }
        }

        // Export all types
        for (&decl_id, decl) in &t.ast_context.c_decls {
            let needs_export = match decl.kind {
                CDeclKind::Struct { .. } => true,
                CDeclKind::Enum { .. } => true,
                CDeclKind::EnumConstant { .. } => true,
                CDeclKind::Union { .. } => true,
                CDeclKind::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 {
                let decl_file_path = decl
                    .loc
                    .as_ref()
                    .map(|loc| &loc.file_path)
                    .into_iter()
                    .flatten()
                    .next();
                let main_file_path = &t.main_file;

                if t.tcfg.reorganize_definitions && decl_file_path != Some(main_file_path) {
                    t.generate_submodule_imports(decl_id, decl_file_path);
                }

                match t.convert_decl(ctx, true, decl_id) {
                    Ok(ConvertedDecl::Item(item)) => {
                        t.insert_item(item, decl_file_path, main_file_path)
                    }
                    Ok(ConvertedDecl::ForeignItem(item)) => {
                        t.insert_foreign_item(item, decl_file_path, &main_file_path)
                    }
                    Ok(ConvertedDecl::NoItem) => {}
                    Err(e) => {
                        let ref k = t.ast_context.c_decls.get(&decl_id).map(|x| &x.kind);
                        let msg =
                            format!("Skipping declaration due to error: {}, kind: {:?}", e, k);
                        translate_failure(&t.tcfg, &msg)
                    }
                }
            }
        }

        // Export top-level value declarations
        for top_id in &t.ast_context.c_decls_top {
            let needs_export = match t.ast_context.c_decls[top_id].kind {
                CDeclKind::Function { is_implicit, .. } => !is_implicit,
                CDeclKind::Variable { .. } => true,
                _ => false,
            };
            if needs_export {
                let decl_opt = t.ast_context.c_decls.get(top_id);
                let decl = decl_opt.as_ref().unwrap();
                let decl_file_path = match decl.loc.as_ref().map(|loc| &loc.file_path) {
                    Some(Some(s)) => Some(s),
                    _ => None,
                };
                let main_file_path = &t.main_file;

                if t.tcfg.reorganize_definitions && decl_file_path != Some(main_file_path) {
                    t.generate_submodule_imports(*top_id, decl_file_path);
                }

                match t.convert_decl(ctx, true, *top_id) {
                    Ok(ConvertedDecl::Item(mut item)) => t.item_store.borrow_mut().items.push(item),
                    Ok(ConvertedDecl::ForeignItem(item)) => {
                        t.insert_foreign_item(item, decl_file_path, main_file_path)
                    }
                    Ok(ConvertedDecl::NoItem) => {}
                    Err(e) => {
                        let ref decl = t.ast_context.c_decls.get(top_id);
                        let msg = match decl {
                            Some(decl) if !tcfg.verbose => {
                                let decl_identifier = decl.kind.get_name().map_or_else(
                                    || {
                                        decl.loc
                                            .as_ref()
                                            .map_or("Unknown".to_string(), |l| format!("at {}", l))
                                    },
                                    |name| name.clone(),
                                );
                                format!(
                                    "Failed to translate declaration {} due to error:\n\n{}",
                                    decl_identifier, e
                                )
                            }
                            _ => format!(
                                "Failed to translate declaration due to error: {}, decl: {:?}",
                                e, decl
                            ),
                        };
                        translate_failure(&t.tcfg, &msg)
                    }
                }
            }
        }

        // Add the main entry point
        if let Some(main_id) = t.ast_context.c_main {
            match t.convert_main(main_id) {
                Ok(item) => t.item_store.borrow_mut().items.push(item),
                Err(e) => {
                    let msg = format!("Failed translating main declaration due to error: {}", 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 items = &mut t.item_store.borrow_mut().items;

            items.push(initializer_fn);
            items.push(initializer_static);
        }

        let pragmas = t.get_pragmas();
        let crates = t.extern_crates.borrow().clone();
        // pass all converted items to the Rust pretty printer
        let translation = to_string(|s| {
            print_header(s, &t)?;

            // Re-order comments
            let mut traverser = t.comment_store.into_inner().into_comment_traverser();
            let mut mod_items: Vec<P<Item>> = Vec::new();

            // Header Reorganization: Submodule Item Stores
            for (file_path, ref mut mod_item_store) in t.mod_blocks.borrow_mut().iter_mut() {
                mod_items.push(make_submodule(
                    mod_item_store,
                    file_path,
                    &t.item_store,
                    &t.mod_names,
                ));
            }

            // Global Item Store
            let (items, foreign_items, uses) = t.item_store.borrow_mut().drain();

            mod_items = mod_items
                .into_iter()
                .map(|p_i| p_i.map(|i| traverser.traverse_item(i)))
                .collect();
            let foreign_items: Vec<ForeignItem> = foreign_items
                .into_iter()
                .map(|fi| traverser.traverse_foreign_item(fi))
                .collect();
            let items: Vec<P<Item>> = items
                .into_iter()
                .map(|p_i| p_i.map(|i| traverser.traverse_item(i)))
                .collect();

            s.comments()
                .get_or_insert(vec![])
                .extend(traverser.into_comment_store().into_comments());

            for mod_item in mod_items {
                s.print_item(&*mod_item)?;
            }

            // 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
            for use_item in uses.into_items() {
                s.print_item(&use_item)?;
            }

            if !foreign_items.is_empty() {
                s.print_item(&mk().abi("C").foreign_items(foreign_items))?
            }

            // Add the items accumulated
            for x in items {
                s.print_item(&*x)?;
            }

            Ok(())
        });
        (translation, pragmas, crates)
    })
}

fn make_submodule(
    submodule_item_store: &mut ItemStore,
    file_path: &path::Path,
    global_item_store: &RefCell<ItemStore>,
    mod_names: &RefCell<IndexMap<String, PathBuf>>,
) -> P<Item> {
    let (mut items, foreign_items, uses) = submodule_item_store.drain();
    let file_path_str = file_path.to_str().expect("Found invalid unicode");
    let mod_name = clean_path(mod_names, file_path);
    let mut global_item_store = global_item_store.borrow_mut();

    for item in items.iter() {
        let ident_name = item.ident.name.as_str();
        let use_path = vec!["self".into(), mod_name.clone()];

        global_item_store
            .uses
            .get_mut(use_path)
            .insert(&*ident_name);
    }

    for foreign_item in foreign_items.iter() {
        let ident_name = foreign_item.ident.name.as_str();
        let use_path = vec!["self".into(), mod_name.clone()];

        global_item_store
            .uses
            .get_mut(use_path)
            .insert(&*ident_name);
    }

    for item in uses.into_items() {
        items.push(item);
    }

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

    mk().vis("pub")
        .str_attr("header_src", file_path_str)
        .mod_item(mod_name, mk().mod_(items))
}

/// Pretty-print the leading pragmas and extern crate declarations
fn print_header(s: &mut State, t: &Translation) -> io::Result<()> {
    if t.tcfg.emit_modules {
        s.print_item(&mk().use_item(vec!["libc"], None as Option<Ident>))?;
    } else {
        let pragmas = t.get_pragmas();
        for (key, mut values) in pragmas {
            values.sort();
            let value_attr_vec = values
                .into_iter()
                .map(|value| mk().nested_meta_item(mk().meta_item(vec![value], MetaItemKind::Word)))
                .collect::<Vec<_>>();
            let item = mk().meta_item(vec![key], MetaItemKind::List(value_attr_vec));
            for attr in mk().meta_item_attr(AttrStyle::Inner, item).as_inner_attrs() {
                s.print_attribute(&attr)?;
            }
        }

        if t.tcfg.cross_checks {
            let mut xcheck_plugin_args: Vec<NestedMetaItem> = vec![];
            for config_file in &t.tcfg.cross_check_configs {
                let file_lit = mk().str_lit(config_file);
                let file_item = mk().meta_item(vec!["config_file"], file_lit);
                xcheck_plugin_args.push(mk().nested_meta_item(file_item));
            }
            let xcheck_plugin_item = mk().meta_item(
                vec!["c2rust_xcheck_plugin"],
                MetaItemKind::List(xcheck_plugin_args),
            );
            let plugin_args = vec![mk().nested_meta_item(xcheck_plugin_item)];
            let plugin_item = mk().meta_item(vec!["plugin"], MetaItemKind::List(plugin_args));
            for attr in mk()
                .meta_item_attr(AttrStyle::Inner, plugin_item)
                .as_inner_attrs()
            {
                s.print_attribute(&attr)?;
            }
        }

        if t.tcfg.emit_no_std {
            s.print_attribute(&mk().single_attr("no_std").as_inner_attrs()[0])?;
        }

        // Add `extern crate X;` to the top of the file
        for crate_name in t.extern_crates.borrow().iter() {
            s.print_item(&mk().extern_crate_item(*crate_name, None))?;
        }

        if t.tcfg.cross_checks {
            s.print_item(
                &mk()
                    .single_attr("macro_use")
                    .extern_crate_item("c2rust_xcheck_derive", None),
            )?;
            s.print_item(
                &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"];
            s.print_item(&mk().single_attr("global_allocator").static_item(
                "C2RUST_ALLOC",
                mk().path_ty(sys_alloc_path.clone()),
                mk().path_expr(sys_alloc_path),
            ))?;
        }
    }
    Ok(())
}

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

/// This represents all of the ways a C expression can be used in a C program. Making this
/// distinction is important for:
///
///   * not generating a bunch of unnecessary code, e.g., the expression `p = 1` evaluates `1`,
///     but when used in a statement like `p = 1;`, we don't care about this, so we can translate
///     to the Rust `p = 1` (even if it evaluates to the unit type). We get this behaviour by
///     translating expression statements using `ExprUse::Unused`.
///
///   * handling `volatile` properly, e.g., suppose `volatile int n, *p;` and `int x;`.
///     Then, `x = n` is a volatile read of `n` but `p = &n` is not. We get this behaviour
///     by translating the argument of `&` using `ExprUse::LValue` and the right hand side of `=`
///
///     using `ExprUse::RValue`.
///
///   * handling `volatile` properly
///
/// See `Translation::convert_expr` for more details.
#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)]
pub enum ExprUse {
    /// expressions interesting only for their side-effects - we don't care about their values
    Unused,
    /// expressions used for their values
    Used,
}

/// 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(ForeignItem),
    Item(P<Item>),
    NoItem,
}

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

        if tcfg.translate_valist {
            type_converter.translate_valist = true
        }

        Translation {
            features: RefCell::new(IndexSet::new()),
            item_store: RefCell::new(ItemStore::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",
                "yield", // Prevent use for other reasons
                "main",  // prelude names
                "drop", "Some", "None", "Ok", "Err",
            ])),
            zero_inits: RefCell::new(IndexMap::new()),
            function_context: RefCell::new(FunContext::new()),
            comment_context,
            comment_store: RefCell::new(CommentStore::new()),
            sectioned_static_initializers: RefCell::new(Vec::new()),
            mod_blocks: RefCell::new(IndexMap::new()),
            mod_names: RefCell::new(IndexMap::new()),
            main_file,
            extern_crates: RefCell::new(IndexSet::new()),
        }
    }

    /// 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",
                "mutable_transmutes",
                "unused_mut",
                "unused_assignments",
            ],
        )];
        if self.tcfg.cross_checks {
            features.append(&mut vec!["plugin", "custom_attribute"]);
            pragmas.push(("cross_check", vec!["yes"]));
        }

        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) -> P<Expr> {
        self.panic_or_err_helper(msg, self.tcfg.panic_on_translator_failure)
    }

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

    fn panic_or_err_helper(&self, msg: &str, panic: bool) -> P<Expr> {
        let macro_name = if panic { "panic" } else { "compile_error" };
        let macro_msg = vec![Token::Interpolated(Lrc::new(Nonterminal::NtExpr(
            mk().lit_expr(mk().str_lit(msg)),
        )))]
        .into_iter()
        .collect::<TokenStream>();
        mk().mac_expr(mk().mac(vec![macro_name], macro_msg, MacDelimiter::Parenthesis))
    }

    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"),
            };

            match self.ast_context[expr_id].kind {
                CExprKind::DeclRef(_, _, LRValue::LValue) => return true,
                CExprKind::ImplicitCast(_, _, CastKind::IntegralToPointer, _, _)
                | CExprKind::ExplicitCast(_, _, CastKind::IntegralToPointer, _, _) => {
                    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>) -> bool {
        use c_ast::BinOp::{Add, Divide, Modulus, Multiply, Subtract};
        use c_ast::CastKind::{IntegralToPointer, PointerToIntegral};
        use c_ast::UnOp::{AddressOf, Negate};

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

        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"),
            };

            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
                CExprKind::ArraySubscript(..) => return true,
                CExprKind::Member(..) => return true,

                CExprKind::Conditional(..) => return true,
                CExprKind::Unary(typ, Negate, _, _) => {
                    if self
                        .ast_context
                        .resolve_type(typ.ctype)
                        .kind
                        .is_unsigned_integral_type()
                    {
                        return true;
                    }
                }
                CExprKind::ImplicitCast(_, _, PointerToIntegral, _, _) => return true,
                CExprKind::Binary(typ, op, _, _, _, _) => {
                    let problematic_op = match op {
                        Add | Subtract | Multiply | Divide | Modulus => true,
                        _ => false,
                    };

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

                    match ty {
                        CTypeKind::Struct(decl_id) => {
                            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;
                                    }
                                }
                            }
                        }
                        _ => {}
                    }
                }
                CExprKind::ImplicitCast(qtype, _, IntegralToPointer, _, _) |
                CExprKind::ExplicitCast(qtype, _, IntegralToPointer, _, _) => {
                    if let CTypeKind::Pointer(qtype) = self.ast_context[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 P<Expr>,
    ) -> Result<(), TranslationError> {
        let mut default_init = self.implicit_default_expr(typ.ctype, true)?;

        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) -> (P<Item>, P<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 = FunctionRetTy::Default(DUMMY_SP);
        let fn_decl = mk().fn_decl(vec![], fn_ty, false);
        let fn_block = mk().block(sectioned_static_initializers);
        let fn_attributes = self.mk_cross_check(mk(), vec!["none"]);
        let fn_item = fn_attributes
            .unsafe_()
            .abi("C")
            .fn_item(&fn_name, &fn_decl, fn_block);

        let static_attributes = mk()
            .single_attr("used")
            .call_attr(
                "cfg_attr",
                vec!["target_os = \"linux\"", "link_section = \".init_array\""],
            )
            .call_attr(
                "cfg_attr",
                vec!["target_os = \"windows\"", "link_section = \".CRT$XIB\""],
            )
            .call_attr(
                "cfg_attr",
                vec![
                    "target_os = \"macos\"",
                    "link_section = \"__DATA,__mod_init_func\"",
                ],
            );
        let static_array_size = mk().lit_expr(mk().int_lit(1, LitIntType::Unsuffixed));
        let static_ty = mk().array_ty(
            mk().unsafe_().abi("C").barefn_ty(fn_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,
        toplevel: bool,
        decl_id: CDeclId,
    ) -> Result<ConvertedDecl, TranslationError> {
        let mut s = {
            let decl_cmt = self
                .comment_context
                .borrow_mut()
                .remove_decl_comment(decl_id);
            self.comment_store.borrow_mut().add_comment_lines(decl_cmt)
        };

        match self
            .ast_context
            .c_decls
            .get(&decl_id)
            .ok_or_else(|| format_err!("Missing decl {:?}", decl_id))?
            .kind
        {
            CDeclKind::Struct { fields: None, .. }
            | CDeclKind::Union { fields: None, .. }
            | CDeclKind::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(s).pub_().ty_foreign_item(name);
                Ok(ConvertedDecl::ForeignItem(extern_item))
            }

            CDeclKind::Struct {
                fields: Some(ref fields),
                is_packed,
                manual_alignment,
                max_field_alignment,
                platform_byte_size,
                ..
            } => {
                let name = self
                    .type_converter
                    .borrow()
                    .resolve_decl_name(decl_id)
                    .unwrap();
                let mut has_bitfields = false;

                // Gather up all the field names and field types
                let mut field_entries = vec![];
                let mut field_info = Vec::new();

                for &x in fields {
                    match self.ast_context.index(x).kind {
                        CDeclKind::Field {
                            ref name,
                            typ,
                            bitfield_width,
                            platform_bit_offset,
                            platform_type_bitwidth,
                        } => {
                            let name = self
                                .type_converter
                                .borrow_mut()
                                .declare_field_name(decl_id, x, name);

                            has_bitfields |= bitfield_width.is_some();

                            field_info.push((
                                name.clone(),
                                typ.clone(),
                                bitfield_width,
                                platform_bit_offset,
                                platform_type_bitwidth,
                            ));

                            let typ = self.convert_type(typ.ctype)?;

                            field_entries.push(mk().span(s).pub_().struct_field(name, typ));
                        }
                        _ => {
                            return Err(TranslationError::generic(
                                "Found non-field in record field list",
                            ))
                        }
                    }
                }

                if has_bitfields {
                    return self.convert_bitfield_struct_decl(
                        name,
                        manual_alignment,
                        platform_byte_size,
                        s,
                        field_info,
                    );
                }

                let mut reprs = vec![simple_metaitem("C")];

                if is_packed || max_field_alignment == Some(1) {
                    reprs.push(simple_metaitem("packed"));
                };
                // https://github.com/rust-lang/rust/issues/33626
                if let Some(alignment) = manual_alignment {
                    let lit = mk().int_lit(alignment as u128, LitIntType::Unsuffixed);
                    let inner = mk().meta_item(
                        vec!["align"],
                        MetaItemKind::List(vec![
                            mk().nested_meta_item(NestedMetaItem::Literal(lit))
                        ]),
                    );
                    reprs.push(mk().nested_meta_item(NestedMetaItem::MetaItem(inner)));
                };

                let repr_attr = mk().meta_item(vec!["repr"], MetaItemKind::List(reprs));

                Ok(ConvertedDecl::Item(
                    mk().span(s)
                        .pub_()
                        .call_attr("derive", vec!["Copy", "Clone"])
                        .meta_item_attr(AttrStyle::Outer, repr_attr)
                        .struct_item(name, field_entries),
                ))
            }

            CDeclKind::Union {
                fields: Some(ref fields),
                ..
            } => {
                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().span(s).pub_().struct_field(name, typ))
                        }
                        _ => {
                            return Err(TranslationError::generic(
                                "Found non-field in record field list",
                            ))
                        }
                    }
                }

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

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

            CDeclKind::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(s).pub_().type_item(enum_name, ty),
                ))
            }

            CDeclKind::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");
                let ty = mk().path_ty(mk().path(vec![enum_name]));
                let val = match value {
                    ConstIntExpr::I(value) => signed_int_expr(value),
                    ConstIntExpr::U(value) => {
                        mk().lit_expr(mk().int_lit(value as u128, LitIntType::Unsuffixed))
                    }
                };

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

            CDeclKind::Function { .. } if !toplevel => Err(TranslationError::generic(
                "Function declarations must be top-level",
            )),
            CDeclKind::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_var): (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, s, is_global, is_inline, is_main, is_var, 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, s, is_global, false, is_main, is_var, is_extern, new_name, name,
                        &args, ret, None, attrs,
                    ),
                    _ => Err(e),
                })
            }

            CDeclKind::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);
                }

                let ty = self.convert_type(typ.ctype)?;
                Ok(ConvertedDecl::Item(
                    mk().span(s).pub_().type_item(new_name, ty),
                ))
            }

            // Externally-visible variable without initializer (definition elsewhere)
            CDeclKind::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 (ty, mutbl, _) = self.convert_variable(ctx.static_(), None, typ)?;
                // When putting extern statics into submodules, they need to be public to be accessible
                let visibility = if self.tcfg.reorganize_definitions {
                    "pub"
                } else {
                    ""
                };
                let mut extern_item = mk_linkage(true, &new_name, ident)
                    .span(s)
                    .set_mutbl(mutbl)
                    .vis(visibility);
                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)
            CDeclKind::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) {
                    // Note: We don't pass has_static_duration through here. Extracted initializers
                    // are run outside of the static initializer.
                    let (ty, _, init) =
                        self.convert_variable(ctx.not_static(), initializer, typ)?;

                    let mut init = init?;
                    init.stmts.push(mk().expr_stmt(init.val));
                    let init = mk().block(init.stmts);
                    let mut init = mk().block_expr(init);

                    let comment = String::from("// Initialized in run_static_initializers");
                    // REVIEW: We might want to add the comment to the original span comments
                    s = self
                        .comment_store
                        .borrow_mut()
                        .add_comment_lines(vec![comment]);

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

                    (ty, init)
                } else {
                    let (ty, _, init) = self.convert_variable(ctx.static_(), initializer, typ)?;

                    let init = if self.static_initializer_is_unsafe(initializer, typ) {
                        let mut init = init?;
                        init.stmts.push(mk().expr_stmt(init.val));
                        let init = mk().unsafe_().block(init.stmts);

                        mk().block_expr(init)
                    } else {
                        let init = init?;
                        assert!(
                            init.stmts.is_empty(),
                            "Expected no side-effects in static initializer"
                        );
                        init.val
                    };

                    (ty, init)
                };

                let static_def = if is_externally_visible {
                    mk_linkage(false, new_name, ident).pub_().abi("C")
                } else {
                    mk()
                };

                // Force mutability due to the potential for raw pointers occuring in the type
                // and because we may be assigning to these variables in the external initializer
                let mut static_def = static_def.span(s).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),
                ))
            }

            CDeclKind::Variable { .. } => Err(TranslationError::generic(
                "This should be handled in 'convert_decl_stmt'",
            )),
            //ref k => Err(format_err!("Translation not implemented for {:?}", k).into()),
        }
    }

    /// Returns true iff type is a (pointer to)* the `va_list` structure type.
    /// Note: the logic is based on `TypeConverter::convert_pointer`.
    pub fn is_inner_type_valist(ctxt: &TypedAstContext, qtype: CQualTypeId) -> bool {
        match ctxt.resolve_type(qtype.ctype).kind {
            CTypeKind::Struct(struct_id) => {
                if let CDeclKind::Struct {
                    name: Some(ref struct_name),
                    ..
                } = ctxt[struct_id].kind
                {
                    if struct_name == "__va_list_tag" {
                        return true;
                    }
                }
                false
            }
            CTypeKind::Pointer(pointer_id) => Self::is_inner_type_valist(ctxt, pointer_id),
            _ => false,
        }
    }

    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>,
    ) -> Result<ConvertedDecl, TranslationError> {
        self.function_context.borrow_mut().enter_new(name);

        let is_valist: bool = arguments
            .iter()
            .any(|&(_, _, typ)| Self::is_inner_type_valist(&self.ast_context, typ));
        if is_variadic || is_valist {
            if let Some(body_id) = body {
                if !self.is_well_formed_variadic(body_id) {
                    return Err(format_err!(
                        "Failed to translate {}; unsupported variadic function.",
                        name
                    )
                    .into());
                }
            }
        }

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

            // handle regular (non-variadic) arguments
            for &(decl_id, ref var, typ) in arguments {
                let (ty, mutbl, _) = self.convert_variable(ctx, None, 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())
                        .expect(&format!(
                            "Failed to insert argument '{}' while converting '{}'",
                            var, name
                        ));

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

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

            // handle variadic arguments
            if is_variadic {
                if let Some(va_decl_id) = self.get_promoted_va_decl() {
                    // `register_va_arg` succeeded
                    let var = self
                        .renamer
                        .borrow_mut()
                        .get(&va_decl_id)
                        .expect(&format!("Failed to get name for variadic argument"));

                    // FIXME: detect mutability requirements
                    let pat = mk().set_mutbl(Mutability::Mutable).ident_pat(var);
                    args.push(mk().arg(mk().cvar_args_ty(), pat))
                } else {
                    args.push(mk().arg(mk().cvar_args_ty(), mk().wild_pat()))
                }
            }

            // 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 {
                FunctionRetTy::Default(DUMMY_SP)
            } else {
                FunctionRetTy::Ty(ret)
            };

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

            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"),
                };
                body_stmts.append(&mut self.convert_function_body(ctx, name, body_ids, ret)?);
                let block = stmts_block(body_stmts);

                // 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 {
                    mk_linkage(false, new_name, name).abi("C").pub_()
                } else if is_inline && is_extern && !attrs.contains(&c_ast::Attribute::GnuInline) {
                    // c99 extern inline functions should be pub, but not gnu_inline attributed
                    // extern inlines, which become subject to their gnu89 visibility (private)

                    mk_linkage(false, new_name, name).abi("C").pub_()
                } else {
                    mk().abi("C")
                };

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

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

                Ok(ConvertedDecl::Item(
                    mk_.span(span).unsafe_().fn_item(new_name, decl, block),
                ))
            } else {
                // Translating an extern function declaration

                // When putting extern fns into submodules, they need to be public to be accessible
                let visibility = if self.tcfg.reorganize_definitions {
                    "pub"
                } else {
                    ""
                };

                let mut mk_ = mk_linkage(true, new_name, name).span(span).vis(visibility);

                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(new_name, 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,
    ) -> Result<Vec<Stmt>, TranslationError> {
        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 as Option<P<Expr>>,
            );
            stmts.push(mk().local_stmt(P(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: cfg::ImplicitReturnType,
    ) -> Result<Vec<Stmt>, TranslationError> {
        // Function body scope
        self.with_scope(|| {
            let (graph, store) = cfg::Cfg::from_stmts(self, ctx, body_ids, ret)?;
            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,
    ) -> Result<WithStmts<P<Expr>>, TranslationError> {
        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| -> Result<WithStmts<P<Expr>>, TranslationError> {
                let val = self.convert_expr(ctx.used().decay_ref(), ptr)?;
                let ptr_type = self.ast_context[ptr]
                    .kind
                    .get_type()
                    .ok_or_else(|| format_err!("bad pointer type for condition"))?;
                Ok(val.map(|e| {
                    if self.ast_context.is_function_pointer(ptr_type) {
                        if negated {
                            mk().method_call_expr(e, "is_some", vec![] as Vec<P<Expr>>)
                        } else {
                            mk().method_call_expr(e, "is_none", vec![] as Vec<P<Expr>>)
                        }
                    } else {
                        let is_null = mk().method_call_expr(e, "is_null", vec![] as Vec<P<Expr>>);
                        if negated {
                            mk().unary_expr(ast::UnOp::Not, 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)?;
                Ok(val.map(|e| self.match_bool(target, ty_id, e)))
            }
        }
    }

    pub fn convert_decl_stmt(
        &self,
        ctx: ExprContext,
        decl_id: CDeclId,
    ) -> Result<Vec<Stmt>, TranslationError> {
        match self.convert_decl_stmt_info(ctx, decl_id)? {
            cfg::DeclStmtInfo {
                decl_and_assign: Some(d),
                ..
            } => Ok(d),
            _ => Err(TranslationError::generic(
                "convert_decl_stmt: couldn't get declaration and initialization info",
            )),
        }
    }

    /// 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,
    ) -> Result<cfg::DeclStmtInfo, TranslationError> {
        if self.is_promoted_va_decl(decl_id) {
            // `va_list` decl was promoted to arg
            self.use_feature("c_variadic");
            return Ok(cfg::DeclStmtInfo::empty());
        }

        match self.ast_context.index(decl_id).kind {
            CDeclKind::Variable {
                ref ident,
                has_static_duration: true,
                is_externally_visible: false,
                is_defn: true,
                initializer,
                typ,
                ..
            } => {
                if self.static_initializer_is_uncompilable(initializer) {
                    let ident2 = self
                        .renamer
                        .borrow_mut()
                        .insert_root(decl_id, ident)
                        .ok_or_else(|| {
                            TranslationError::generic(
                                "Unable to rename function scoped static initializer",
                            )
                        })?;
                    let (ty, _, init) = self.convert_variable(ctx.static_(), initializer, typ)?;
                    let default_init = self.implicit_default_expr(typ.ctype, true)?;
                    let comment = String::from("// Initialized in run_static_initializers");
                    let span = self
                        .comment_store
                        .borrow_mut()
                        .add_comment_lines(vec![comment]);
                    let static_item =
                        mk().span(span)
                            .mutbl()
                            .static_item(&ident2, ty, default_init);
                    let mut init = init?;

                    init.stmts.push(mk().expr_stmt(init.val));

                    let init = mk().unsafe_().block(init.stmts);
                    let mut init = mk().block_expr(init);

                    self.add_static_initializer_to_section(&ident2, typ, &mut init)?;
                    self.item_store.borrow_mut().items.push(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)
                    .expect(&format!("Failed to insert variable '{}'", ident));

                if self.is_copied_va_decl(decl_id) {
                    // translate `va_list` declarations not promoted to an arg
                    // to `VaList` and do not emit an initializer.
                    let pat_mut = mk().set_mutbl("mut").ident_pat(rust_name.clone());
                    let ty = {
                        let std_or_core = if self.tcfg.emit_no_std { "core" } else { "std" };
                        let path = vec!["", std_or_core, "ffi", "VaList"];
                        mk().path_ty(path)
                    };
                    let local_mut = mk().local::<_, _, P<Expr>>(pat_mut, Some(ty), None);

                    return Ok(cfg::DeclStmtInfo::new(
                        vec![],                              // decl
                        vec![],                              // assign
                        vec![mk().local_stmt(P(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 (ty, mutbl, init) = self.convert_variable(ctx, initializer, typ)?;
                let mut init = init?;

                stmts.append(&mut init.stmts);

                if has_self_reference {
                    let pat_mut = mk().set_mutbl("mut").ident_pat(rust_name.clone());
                    let zeroed = self.implicit_default_expr(typ.ctype, false)?;
                    let local_mut = mk().local(pat_mut, Some(ty), Some(zeroed));

                    let assign = mk().assign_expr(mk().ident_expr(rust_name), init.val);

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

                    let mut decl_and_assign = vec![mk().local_stmt(P(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(P(local_mut))],
                        assign_stmts,
                        decl_and_assign,
                    ))
                } else {
                    let pat_mut = mk().set_mutbl("mut").ident_pat(rust_name.clone());
                    let zeroed = self.implicit_default_expr(typ.ctype, false)?;
                    let local_mut = mk().local(pat_mut, Some(ty.clone()), Some(zeroed));

                    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.val.clone()));
                    let assign = mk().assign_expr(mk().ident_expr(rust_name), init.val);

                    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(P(local)));

                    Ok(cfg::DeclStmtInfo::new(
                        vec![mk().local_stmt(P(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.
                let skip = match decl {
                    &CDeclKind::Variable { .. } => !inserted,
                    &CDeclKind::Struct { .. } => true,
                    &CDeclKind::Union { .. } => true,
                    &CDeclKind::Enum { .. } => true,
                    &CDeclKind::Typedef { .. } => true,
                    _ => false,
                };

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

                    Ok(cfg::DeclStmtInfo::new(
                        vec![mk().item_stmt(item.clone())],
                        vec![],
                        vec![mk().item_stmt(item)],
                    ))
                }
            }
        }
    }

    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;
        }

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

                        // None assignments don't prove 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 `= 0 as *const 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
            CTypeKind::Bool
            | CTypeKind::Char
            | CTypeKind::SChar
            | CTypeKind::Short
            | CTypeKind::Int
            | CTypeKind::Long
            | CTypeKind::LongLong
            | CTypeKind::UChar
            | CTypeKind::UShort
            | CTypeKind::UInt
            | CTypeKind::ULong
            | CTypeKind::ULongLong
            | CTypeKind::LongDouble
            | CTypeKind::Int128
            | CTypeKind::UInt128 => initializer.is_none(),
            CTypeKind::Float | CTypeKind::Double => initializer.is_none(),
            CTypeKind::Struct(_) | CTypeKind::Union(_) | CTypeKind::Enum(_) => false,
            CTypeKind::Function(..) => unreachable!("Can't have a function directly as a type"),
            CTypeKind::Typedef(_) => unreachable!("Typedef should be expanded though resolve_type"),
            _ => true,
        }
    }

    fn convert_variable(
        &self,
        ctx: ExprContext,
        initializer: Option<CExprId>,
        typ: CQualTypeId,
    ) -> Result<
        (
            P<Ty>,
            Mutability,
            Result<WithStmts<P<Expr>>, TranslationError>,
        ),
        TranslationError,
    > {
        let init = match initializer {
            Some(x) => self.convert_expr(ctx.used(), x),
            None => self
                .implicit_default_expr(typ.ctype, ctx.is_static)
                .map(WithStmts::new),
        };

        // 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((ty, mutbl, init))
    }

    fn convert_type(&self, type_id: CTypeId) -> Result<P<Ty>, TranslationError> {
        self.type_converter
            .borrow_mut()
            .convert(&self.ast_context, type_id)
    }

    /// Construct an expression for a NULL at any type, including forward declarations,
    /// function pointers, and normal pointers.
    fn null_ptr(&self, type_id: CTypeId, is_static: bool) -> Result<P<Expr>, TranslationError> {
        if self.ast_context.is_function_pointer(type_id) {
            return Ok(mk().path_expr(vec!["None"]));
        }

        let pointee = match self.ast_context.resolve_type(type_id).kind {
            CTypeKind::Pointer(pointee) => pointee,
            _ => return Err(TranslationError::generic("null_ptr requires a pointer")),
        };
        let ty = self.convert_type(type_id)?;
        let mut zero = mk().lit_expr(mk().int_lit(0, LitIntType::Unsuffixed));
        if is_static && !pointee.qualifiers.is_const {
            let mut qtype = pointee;
            qtype.qualifiers.is_const = true;
            self.use_feature("const_raw_ptr_to_usize_cast");
            let ty_ = self
                .type_converter
                .borrow_mut()
                .convert_pointer(&self.ast_context, qtype)?;
            zero = mk().cast_expr(zero, ty_);
        }
        Ok(mk().cast_expr(zero, ty))
    }

    /// Write to a `lhs` that is volatile
    pub fn volatile_write(
        &self,
        lhs: &P<Expr>,
        lhs_type: CQualTypeId,
        rhs: P<Expr>,
    ) -> Result<P<Expr>, TranslationError> {
        let addr_lhs = match lhs.node {
            ExprKind::Unary(ast::UnOp::Deref, ref e) => {
                if lhs_type.qualifiers.is_const {
                    let lhs_type = self.convert_type(lhs_type.ctype)?;
                    let ty = mk().mutbl().ptr_ty(lhs_type);

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

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

                mk().cast_expr(addr_lhs, ty)
            }
        };
        let std_or_core = if self.tcfg.emit_no_std { "core" } else { "std" };

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

    /// Read from a `lhs` that is volatile
    pub fn volatile_read(
        &self,
        lhs: &P<Expr>,
        lhs_type: CQualTypeId,
    ) -> Result<P<Expr>, TranslationError> {
        let addr_lhs = match lhs.node {
            ExprKind::Unary(ast::UnOp::Deref, ref e) => {
                if !lhs_type.qualifiers.is_const {
                    let lhs_type = self.convert_type(lhs_type.ctype)?;
                    let ty = mk().ptr_ty(lhs_type);

                    mk().cast_expr(e, ty)
                } else {
                    e.clone()
                }
            }
            _ => {
                let addr_lhs = mk().addr_of_expr(lhs);

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

                mk().cast_expr(addr_lhs, ty)
            }
        };
        let std_or_core = if self.tcfg.emit_no_std { "core" } else { "std" };

        // 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 vec!["", std_or_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().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<P<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(BinOpKind::Mul, 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,
    ) -> Result<Vec<Stmt>, TranslationError> {
        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 mut expr = self.convert_expr(ctx.used(), expr_id)?;
                    stmts.append(&mut expr.stmts);
                    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 as Option<P<Ty>>,
                        Some(mk().cast_expr(expr.val, mk().path_ty(vec!["usize"]))),
                    );

                    stmts.push(mk().local_stmt(P(local)));
                }
                _ => break,
            }
        }

        Ok(stmts)
    }

    // Compute the size of a type
    // Rust type: usize
    pub fn compute_size_of_type(
        &self,
        ctx: ExprContext,
        type_id: CTypeId,
    ) -> Result<WithStmts<P<Expr>>, TranslationError> {
        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 mut elts = self.compute_size_of_type(ctx, elts)?;
            let mut len = self.convert_expr(ctx.used().not_static(), len)?;

            let mut stmts = elts.stmts;
            stmts.append(&mut len.stmts);

            let lhs = elts.val;
            let rhs = cast_int(len.val, "usize");

            let val = mk().binary_expr(BinOpKind::Mul, lhs, rhs);

            return Ok(WithStmts { stmts, val });
        }
        let std_or_core = if self.tcfg.emit_no_std { "core" } else { "std" };
        let ty = self.convert_type(type_id)?;
        let name = "size_of";
        let params = mk().angle_bracketed_args(vec![ty]);
        let path = vec![
            mk().path_segment(""),
            mk().path_segment(std_or_core),
            mk().path_segment("mem"),
            mk().path_segment_with_args(name, params),
        ];
        let call = mk().call_expr(mk().path_expr(path), vec![] as Vec<P<Expr>>);

        Ok(WithStmts::new(call))
    }

    pub fn compute_align_of_type(
        &self,
        mut type_id: CTypeId,
        preferred: bool,
    ) -> Result<WithStmts<P<Expr>>, TranslationError> {
        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("")];
        if self.tcfg.emit_no_std {
            path.push(mk().path_segment("core"));
        } else {
            path.push(mk().path_segment("std"));
        }
        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().path_expr(path), vec![] as Vec<P<Expr>>);
        Ok(WithStmts::new(call))
    }

    /// Translate a C expression into a Rust one, possibly collecting side-effecting statements
    /// to run before the expression.
    ///
    /// The `use_` argument informs us how the C expression we are translating is used in the C
    /// program. See `ExprUse` for more information.
    ///
    /// In the case that `use_` 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.
    pub fn convert_expr(
        &self,
        mut ctx: ExprContext,
        expr_id: CExprId,
    ) -> Result<WithStmts<P<Expr>>, TranslationError> {
        let src_loc = &self.ast_context[expr_id].loc;
        match self.ast_context[expr_id].kind {
            CExprKind::DesignatedInitExpr(..) => {
                Err(TranslationError::generic("Unexpected designated init expr"))
            }
            CExprKind::BadExpr => Err(TranslationError::generic(
                "convert_expr: expression kind not supported",
            )),
            CExprKind::ShuffleVector(_, ref child_expr_ids) => self
                .convert_shuffle_vector(ctx, child_expr_ids)
                .map_err(|e| {
                    TranslationError::new(src_loc, e.context(TranslationErrorKind::OldLLVMSimd))
                }),
            CExprKind::ConvertVector(..) => {
                Err(TranslationError::generic("convert vector not supported"))
            }

            CExprKind::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)?,
                        Some(_) => {
                            let inner = self.variable_array_base_type(arg_ty.ctype);
                            let inner_size = self.compute_size_of_type(ctx, inner)?;

                            if let Some(sz) = self.compute_size_of_expr(arg_ty.ctype) {
                                inner_size.map(|x| mk().binary_expr(BinOpKind::Mul, 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.map(|x| mk().cast_expr(x, mk().path_ty(vec!["libc", "c_ulong"]))))
            }

            CExprKind::DeclRef(qual_ty, decl_id, lrvalue) => {
                let decl = &self
                    .ast_context
                    .c_decls
                    .get(&decl_id)
                    .ok_or_else(|| format_err!("Missing declref {:?}", decl_id))?
                    .kind;
                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))?;

                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 let CTypeKind::VariableArray(..) =
                    self.ast_context.resolve_type(qual_ty.ctype).kind
                {
                    val = mk().method_call_expr(val, "as_mut_ptr", vec![] as Vec<P<Expr>>);
                }

                Ok(WithStmts::new(val))
            }

            CExprKind::OffsetOf(ty, ref kind) => match kind {
                OffsetOfKind::Constant(val) => {
                    Ok(WithStmts::new(self.mk_int_lit(ty, *val, IntBase::Dec)))
                }
                OffsetOfKind::Variable(qty, field_id, expr_id) => {
                    self.extern_crates.borrow_mut().insert("memoffset");
                    self.item_store
                        .borrow_mut()
                        .uses
                        .get_mut(vec!["memoffset".into()])
                        .insert("offset_of");

                    // Struct Type
                    let decl_id = {
                        let kind = match self.ast_context.c_types[&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
                        .type_converter
                        .borrow()
                        .resolve_decl_name(decl_id)
                        .expect("Did not find name for offsetof struct");
                    let ty_ident = Nonterminal::NtIdent(mk().ident(name), false);

                    // 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 = Nonterminal::NtIdent(mk().ident(field_name), false);

                    // Index Expr
                    let expr = self.convert_expr(ctx, *expr_id)?.val;
                    let expr = mk().cast_expr(expr, mk().ident_ty("usize"));
                    let index_expr = Nonterminal::NtExpr(expr);

                    // offset_of!(Struct, field[expr as usize]) as ty
                    let mut macro_body = vec![
                        TokenTree::Token(DUMMY_SP, Token::Interpolated(Lrc::new(ty_ident))),
                        TokenTree::Token(DUMMY_SP, Token::Comma),
                        TokenTree::Token(DUMMY_SP, Token::Interpolated(Lrc::new(field_ident))),
                        TokenTree::Token(DUMMY_SP, Token::OpenDelim(DelimToken::Bracket)),
                        TokenTree::Token(DUMMY_SP, Token::Interpolated(Lrc::new(index_expr))),
                        TokenTree::Token(DUMMY_SP, Token::CloseDelim(DelimToken::Bracket)),
                    ];
                    let path = mk().path("offset_of");
                    let mac = mk().mac_expr(mk().mac(path, macro_body, MacDelimiter::Parenthesis));

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

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

            CExprKind::Literal(ty, ref kind) => self.convert_literal(ctx.is_static, ty, kind),

            CExprKind::ImplicitCast(ty, expr, kind, opt_field_id, _) => {
                self.convert_cast(ctx, ty, expr, kind, opt_field_id, false)
            }

            CExprKind::ExplicitCast(ty, expr, kind, opt_field_id, _) => {
                self.convert_cast(ctx, ty, expr, kind, opt_field_id, true)
            }

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

            CExprKind::Conditional(_, cond, lhs, rhs) => {
                let cond = self.convert_condition(ctx, true, cond)?;

                let lhs = self.convert_expr(ctx, lhs)?;
                let rhs = self.convert_expr(ctx, rhs)?;

                if ctx.is_unused() {
                    let then: P<Block> = mk().block(lhs.stmts);
                    let els: P<Expr> = mk().block_expr(mk().block(rhs.stmts));

                    Ok(cond.and_then(|c| WithStmts {
                        stmts: vec![mk().semi_stmt(mk().ifte_expr(c, then, Some(els)))],
                        val: self.panic_or_err("Conditional expression is not supposed to be used"),
                    }))
                } else {
                    let then: P<Block> = lhs.to_block();
                    let els: P<Expr> = rhs.to_expr();

                    Ok(cond.map(|c| mk().ifte_expr(c, then, Some(els))))
                }
            }

            CExprKind::BinaryConditional(ty, lhs, rhs) => {
                if ctx.is_unused() {
                    let mut lhs = self.convert_condition(ctx, false, lhs)?;

                    lhs.stmts.push(mk().semi_stmt(mk().ifte_expr(
                        lhs.val,
                        mk().block(self.convert_expr(ctx, rhs)?.stmts),
                        None as Option<P<Expr>>,
                    )));
                    Ok(WithStmts {
                        stmts: lhs.stmts,
                        val: self.panic_or_err(
                            "Binary conditional expression is not supposed to be used",
                        ),
                    })
                } else {
                    self.name_reference_write_read(ctx, lhs)?
                        .result_map(|(_, lhs_val)| {
                            let cond = self.match_bool(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)?.to_expr()),
                            );
                            Ok(ite)
                        })
                }
            }

            CExprKind::Binary(type_id, op, lhs, rhs, opt_lhs_type_id, opt_res_type_id) => self
                .convert_binary_expr(ctx, type_id, op, lhs, rhs, opt_lhs_type_id, opt_res_type_id),

            CExprKind::ArraySubscript(_, ref lhs, ref rhs, _) => {
                let lhs_node = &self.ast_context.index(*lhs).kind;
                let rhs_node = &self.ast_context.index(*rhs).kind;

                let lhs_node_type = lhs_node
                    .get_type()
                    .ok_or_else(|| format_err!("lhs node bad type"))?;
                let lhs_node_kind = &self.ast_context.resolve_type(lhs_node_type).kind;
                let lhs_is_indexable = lhs_node_kind.is_pointer() || lhs_node_kind.is_vector();

                // From here on in, the LHS is the pointer/array and the RHS the index
                let (lhs, rhs, lhs_node) = if lhs_is_indexable {
                    (lhs, rhs, lhs_node)
                } else {
                    (rhs, lhs, rhs_node)
                };

                let lhs_node_type = lhs_node
                    .get_type()
                    .ok_or_else(|| format_err!("lhs node bad type"))?;
                if self
                    .ast_context
                    .resolve_type(lhs_node_type)
                    .kind
                    .is_vector()
                {
                    return Err(TranslationError::new(
                        src_loc,
                        err_msg("Attempting to index a vector type")
                            .context(TranslationErrorKind::OldLLVMSimd),
                    ));
                }

                let mut stmts = vec![];

                let mut rhs = self.convert_expr(ctx.used(), *rhs)?;
                stmts.extend(rhs.stmts);

                let simple_index_array = if ctx.needs_address() {
                    // We can't necessarily index into an array if we're using
                    // that element to compute an address.
                    None
                } else {
                    match lhs_node {
                        &CExprKind::ImplicitCast(_, arr, CastKind::ArrayToPointerDecay, _, _) => {
                            let arr_type = self.ast_context[arr]
                                .kind
                                .get_type()
                                .ok_or_else(|| format_err!("bad arr type"))?;
                            match self.ast_context.resolve_type(arr_type).kind {
                                // These get translated to 0-element arrays, this avoids the bounds check
                                // that using an array subscript in Rust would cause
                                CTypeKind::IncompleteArray(_) => None,
                                _ => Some(arr),
                            }
                        }
                        _ => None,
                    }
                };

                let val = if let Some(arr) = simple_index_array {
                    // If the LHS just underwent an implicit cast from array to pointer, bypass that
                    // to make an actual Rust indexing operation

                    let t = self.ast_context[arr]
                        .kind
                        .get_type()
                        .ok_or_else(|| format_err!("bad arr type"))?;
                    let var_elt_type_id = match self.ast_context.resolve_type(t).kind {
                        CTypeKind::ConstantArray(..) => None,
                        CTypeKind::IncompleteArray(..) => None,
                        CTypeKind::VariableArray(elt, _) => Some(elt),
                        ref other => panic!("Unexpected array type {:?}", other),
                    };

                    let lhs = self.convert_expr(ctx.used(), arr)?;
                    stmts.extend(lhs.stmts);

                    // Don't dereference the offset if we're still within the variable portion
                    if let Some(elt_type_id) = var_elt_type_id {
                        match self.compute_size_of_expr(elt_type_id) {
                            None => {
                                mk().unary_expr(ast::UnOp::Deref, pointer_offset(lhs.val, rhs.val))
                            }
                            Some(sz) => pointer_offset(
                                lhs.val,
                                mk().binary_expr(BinOpKind::Mul, sz, cast_int(rhs.val, "usize")),
                            ),
                        }
                    } else {
                        mk().index_expr(lhs.val, cast_int(rhs.val, "usize"))
                    }
                } else {
                    let lhs = self.convert_expr(ctx.used(), *lhs)?;
                    stmts.extend(lhs.stmts);

                    let lhs_type_id = lhs_node
                        .get_type()
                        .ok_or_else(|| format_err!("bad lhs type"))?;

                    // Determine the type of element being indexed
                    let pointee_type_id = match self.ast_context.resolve_type(lhs_type_id).kind {
                        CTypeKind::Pointer(pointee_id) => pointee_id,
                        _ => {
                            return Err(format_err!(
                                "Subscript applied to non-pointer: {:?}",
                                lhs.val
                            )
                            .into())
                        }
                    };

                    if let Some(sz) = self.compute_size_of_expr(pointee_type_id.ctype) {
                        let offset =
                            mk().binary_expr(BinOpKind::Mul, sz, cast_int(rhs.val, "usize"));
                        pointer_offset(lhs.val, offset)
                    } else {
                        // Otherwise, use the pointer and make a deref of a pointer offset expression
                        mk().unary_expr(ast::UnOp::Deref, pointer_offset(lhs.val, rhs.val))
                    }
                };

                Ok(WithStmts { stmts, val })
            }

            CExprKind::Call(_, func, ref args) => {
                let is_variadic = self.fn_expr_is_variadic(func);
                let WithStmts {
                    mut stmts,
                    val: func,
                } = match self.ast_context.index(func).kind {
                    CExprKind::ImplicitCast(_, fexp, CastKind::FunctionToPointerDecay, _, _) => {
                        self.convert_expr(ctx.used(), fexp)?
                    }
                    CExprKind::ImplicitCast(_, fexp, CastKind::BuiltinFnToFnPtr, _, _) => {
                        return self.convert_builtin(ctx, fexp, args)
                    }

                    _ => self
                        .convert_expr(ctx.used(), func)?
                        .map(unwrap_function_pointer),
                };

                let mut args_new: Vec<P<Expr>> = vec![];
                ctx.decay_ref = DecayRef::from(is_variadic);

                for arg in args {
                    // We want to decay refs only when function is variadic
                    let WithStmts { stmts: ss, val } = self.convert_expr(ctx.used(), *arg)?;
                    stmts.extend(ss);
                    args_new.push(val);
                }

                let call_expr = mk().call_expr(func, args_new);
                Ok(self.convert_side_effects_expr(
                    ctx,
                    stmts,
                    call_expr,
                    "Function call expression is not supposed to be used",
                ))
            }

            CExprKind::Member(_, expr, decl, kind, _) => {
                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 {
                    let field_name = self
                        .type_converter
                        .borrow()
                        .resolve_field_name(None, decl)
                        .unwrap();

                    self.convert_bitfield_member_expr(ctx, field_name, expr, kind)
                } else if ctx.is_unused() {
                    self.convert_expr(ctx, expr)
                } else {
                    let field_name = self
                        .type_converter
                        .borrow()
                        .resolve_field_name(None, decl)
                        .unwrap();
                    match kind {
                        MemberKind::Dot => {
                            let val = self.convert_expr(ctx, expr)?;
                            Ok(val.map(|v| mk().field_expr(v, field_name)))
                        }
                        MemberKind::Arrow => {
                            if let CExprKind::Unary(_, c_ast::UnOp::AddressOf, subexpr_id, _) =
                                self.ast_context[expr].kind
                            {
                                let val = self.convert_expr(ctx, subexpr_id)?;
                                Ok(val.map(|v| mk().field_expr(v, field_name)))
                            } else {
                                let val = self.convert_expr(ctx, expr)?;
                                Ok(val.map(|v| {
                                    mk().field_expr(
                                        mk().unary_expr(ast::UnOp::Deref, v),
                                        field_name,
                                    )
                                }))
                            }
                        }
                    }
                }
            }

            CExprKind::CompoundLiteral(_, val) => self.convert_expr(ctx, val),

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

            CExprKind::ImplicitValueInit(ty) => Ok(WithStmts::new(
                self.implicit_default_expr(ty.ctype, ctx.is_static)?,
            )),

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

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

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

    fn fn_expr_is_variadic(&self, expr_id: CExprId) -> bool {
        let fn_expr = &self.ast_context.c_exprs[&expr_id];
        let fn_ty = &self.ast_context.c_types[&fn_expr.kind.get_type().unwrap()];
        if let CTypeKind::Pointer(qual_ty) = fn_ty.kind {
            match self.ast_context.c_types[&qual_ty.ctype].kind {
                CTypeKind::Function(_, _, is_variadic, _, _) => is_variadic,
                _ => false,
            }
        } else {
            false
        }
    }

    fn convert_side_effects_expr(
        &self,
        ctx: ExprContext,
        mut stmts: Vec<Stmt>,
        expr: P<Expr>,
        panic_msg: &str,
    ) -> WithStmts<P<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)
            stmts.push(mk().semi_stmt(expr));
            WithStmts {
                stmts,
                val: self.panic_or_err(panic_msg),
            }
        } else {
            WithStmts { stmts, val: expr }
        }
    }

    fn convert_statement_expression(
        &self,
        ctx: ExprContext,
        compound_stmt_id: CStmtId,
    ) -> Result<WithStmts<P<Expr>>, TranslationError> {
        fn as_semi_break_stmt(stmt: &ast::Stmt, lbl: &cfg::Label) -> Option<Option<P<ast::Expr>>> {
            if let ast::Stmt {
                node: ast::StmtKind::Semi(ref expr),
                ..
            } = *stmt
            {
                if let ast::Expr {
                    node: ast::ExprKind::Break(Some(ref blbl), ref ret_val),
                    ..
                } = **expr
                {
                    if blbl.ident == mk().label(lbl.pretty_print()).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 = cfg::Label::FromC(compound_stmt_id);

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

                    _ => self.convert_function_body(
                        ctx,
                        &name,
                        &substmt_ids,
                        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 {
                                    None => mk().block(stmts),
                                    Some(val) => WithStmts { stmts, val }.to_block(),
                                }
                            });
                            // enclose block in parentheses to work around
                            // https://github.com/rust-lang/rust/issues/54482
                            return Ok(WithStmts::new(mk().paren_expr(block)));
                        }
                        _ => {
                            self.use_feature("label_break_value");
                            stmts.push(stmt)
                        }
                    }
                }

                let block_body = mk().block(stmts.clone());
                let val: P<Expr> = mk().labelled_block_expr(block_body, lbl.pretty_print());

                Ok(WithStmts { stmts, val })
            }
            _ => {
                if ctx.is_unused() {
                    let val =
                        self.panic_or_err("Empty statement expression is not supposed to be used");
                    Ok(WithStmts { stmts: vec![], val })
                } else {
                    Err(TranslationError::generic("Bad statement expression"))
                }
            }
        }
    }

    fn convert_cast(
        &self,
        mut ctx: ExprContext,
        ty: CQualTypeId,
        expr: CExprId,
        kind: CastKind,
        opt_field_id: Option<CFieldId>,
        is_explicit: bool,
    ) -> Result<WithStmts<P<Expr>>, TranslationError> {
        // A reference must be decayed if a bitcast is required
        if kind == CastKind::BitCast || kind == CastKind::PointerToIntegral {
            ctx.decay_ref = DecayRef::Yes;
        }

        if kind == CastKind::IntegralToPointer && ctx.is_static {
            self.use_feature("const_transmute");
        }

        let val = if is_explicit {
            let mut stmts = self.compute_variable_array_sizes(ctx, ty.ctype)?;
            let mut val = self.convert_expr(ctx, expr)?;
            stmts.append(&mut val.stmts);
            val.stmts = stmts;
            val
        } else {
            self.convert_expr(ctx, expr)?
        };

        // 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);
        }

        match kind {
            CastKind::BitCast | CastKind::NoOp => {
                val.result_map(|x| {
                    let source_ty_id = self.ast_context[expr]
                        .kind
                        .get_type()
                        .ok_or_else(|| format_err!("bad source type"))?;

                    if self.ast_context.is_function_pointer(ty.ctype)
                        || self.ast_context.is_function_pointer(source_ty_id)
                    {
                        let source_ty = self.convert_type(source_ty_id)?;
                        let target_ty = self.convert_type(ty.ctype)?;
                        Ok(transmute_expr(
                            source_ty,
                            target_ty,
                            x,
                            self.tcfg.emit_no_std,
                        ))
                    } else {
                        // Normal case
                        let target_ty = self.convert_type(ty.ctype)?;
                        Ok(mk().cast_expr(x, target_ty))
                    }
                })
            }

            CastKind::IntegralToPointer if self.ast_context.is_function_pointer(ty.ctype) => {
                let target_ty = self.convert_type(ty.ctype)?;
                Ok(val.map(|x| {
                    let intptr_t = mk().path_ty(vec!["libc", "intptr_t"]);
                    let intptr = mk().cast_expr(x, intptr_t.clone());
                    transmute_expr(intptr_t, target_ty, intptr, self.tcfg.emit_no_std)
                }))
            }

            CastKind::IntegralToPointer
            | CastKind::PointerToIntegral
            | CastKind::IntegralCast
            | CastKind::FloatingCast
            | CastKind::FloatingToIntegral
            | CastKind::IntegralToFloating => {
                let target_ty = self.convert_type(ty.ctype)?;
                let target_ty_ctype = &self.ast_context.resolve_type(ty.ctype).kind;

                let source_ty_ctype_id = self.ast_context[expr]
                    .kind
                    .get_type()
                    .ok_or_else(|| format_err!("bad source expression"))?;

                let source_ty = self.convert_type(source_ty_ctype_id)?;
                if let CTypeKind::LongDouble = target_ty_ctype {
                    self.extern_crates.borrow_mut().insert("f128");

                    let fn_path = mk().path_expr(vec!["f128", "f128", "new"]);
                    let args = vec![val.val];

                    Ok(WithStmts::new(mk().call_expr(fn_path, args)))
                } else if let CTypeKind::LongDouble = self.ast_context[source_ty_ctype_id].kind {
                    self.extern_crates.borrow_mut().insert("num_traits");
                    self.item_store
                        .borrow_mut()
                        .uses
                        .get_mut(vec!["num_traits".into()])
                        .insert("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_i128",
                        CTypeKind::ULongLong => "to_u128",
                        _ => {
                            return Err(format_err!(
                                "Tried casting long double to unsupported type: {:?}",
                                target_ty_ctype
                            )
                            .into())
                        }
                    };

                    let to_call =
                        mk().method_call_expr(val.val, to_method_name, Vec::<P<Expr>>::new());

                    Ok(WithStmts::new(mk().method_call_expr(
                        to_call,
                        "unwrap",
                        Vec::<P<Expr>>::new(),
                    )))
                } else if let &CTypeKind::Enum(enum_decl_id) = target_ty_ctype {
                    // Casts targeting `enum` types...
                    Ok(self.enum_cast(ty.ctype, enum_decl_id, expr, val, source_ty, target_ty))
                } else {
                    // Other numeric casts translate to Rust `as` casts,
                    // unless the cast is to a function pointer then use `transmute`.
                    Ok(val.map(|x| {
                        if self.ast_context.is_function_pointer(source_ty_ctype_id) {
                            transmute_expr(source_ty, target_ty, x, self.tcfg.emit_no_std)
                        } else {
                            mk().cast_expr(x, target_ty)
                        }
                    }))
                }
            }

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

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

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

            CastKind::ArrayToPointerDecay => {
                let pointee = match self.ast_context.resolve_type(ty.ctype).kind {
                    CTypeKind::Pointer(pointee) => pointee,
                    _ => panic!("Dereferencing a non-pointer"),
                };

                // Because va_list is defined as a single-element array in order for it to allocate
                // memory as a local variable and to be a pointer as a function argument we would
                // get spurious casts when trying to treat it like a VaList which has reference
                // semantics.
                if let CTypeKind::Struct(struct_id) = self.ast_context[pointee.ctype].kind {
                    if let CDeclKind::Struct {
                        name: Some(ref struct_name),
                        ..
                    } = self.ast_context[struct_id].kind
                    {
                        if struct_name == "__va_list_tag" {
                            return Ok(val);
                        }
                    }
                }

                let is_const = pointee.qualifiers.is_const;

                match self.ast_context.index(expr).kind {
                    CExprKind::Literal(_, CLiteral::String(ref bytes, 1)) if is_const => {
                        let target_ty = self.convert_type(ty.ctype)?;

                        let mut bytes = bytes.to_owned();
                        bytes.push(0);
                        let byte_literal = mk().lit_expr(mk().bytestr_lit(bytes));
                        let val =
                            mk().cast_expr(byte_literal, mk().ptr_ty(mk().path_ty(vec!["u8"])));
                        let val = mk().cast_expr(val, target_ty);
                        Ok(WithStmts {
                            stmts: vec![],
                            val: val,
                        })
                    }
                    _ => {
                        // Variable length arrays are already represented as pointers.
                        let source_ty = self.ast_context[expr]
                            .kind
                            .get_type()
                            .ok_or_else(|| format_err!("bad variable array source type"))?;
                        if let CTypeKind::VariableArray(..) =
                            self.ast_context.resolve_type(source_ty).kind
                        {
                            Ok(val)
                        } else {
                            let method = if is_const || ctx.is_static {
                                "as_ptr"
                            } else {
                                "as_mut_ptr"
                            };

                            let mut call = val
                                .map(|x| mk().method_call_expr(x, method, vec![] as Vec<P<Expr>>));

                            // Static arrays can now use as_ptr. Can also cast that const ptr to a
                            // mutable pointer as we do here:
                            if ctx.is_static {
                                if !is_const {
                                    let WithStmts { val, stmts } = call;
                                    let inferred_type = mk().infer_ty();
                                    let ptr_type = mk().mutbl().ptr_ty(inferred_type);
                                    let val = mk().cast_expr(val, ptr_type);

                                    call = WithStmts { val, stmts };
                                }
                            }

                            Ok(call)
                        }
                    }
                }
            }

            CastKind::NullToPointer => {
                assert!(val.stmts.is_empty());
                Ok(WithStmts::new(self.null_ptr(ty.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 => self.convert_condition(ctx, true, expr),

            // I don't know how to actually cause clang to generate this
            CastKind::BooleanToSignedIntegral => Err(TranslationError::generic(
                "TODO boolean to signed integral not supported",
            )),

            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",
            )),
        }
    }

    /// 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<P<Expr>>, // translated Rust argument to cast
        _source_ty: P<Ty>,  // source type of cast
        target_ty: P<Ty>,   // target type of cast
    ) -> WithStmts<P<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"),
        };

        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 x.node {
                    ast::ExprKind::Cast(ref e, _) => e.clone(),
                    _ => panic!(format!(
                        "DeclRef {:?} of enum {:?} is not cast",
                        expr, enum_decl
                    )),
                })
            }

            CExprKind::Literal(_, CLiteral::Integer(i, _)) => {
                let new_val = self.enum_for_i64(enum_type, i as i64);
                return WithStmts {
                    stmts: val.stmts,
                    val: new_val,
                };
            }

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

            // 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,
    ) -> Result<P<Expr>, TranslationError> {
        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(mk().lit_expr(mk().bool_lit(false)))
        } else if resolved_ty.is_integral_type() {
            Ok(mk().lit_expr(mk().int_lit(0, LitIntType::Unsuffixed)))
        } else if resolved_ty.is_floating_type() {
            match self.ast_context[ty_id].kind {
                CTypeKind::LongDouble => Ok(mk().path_expr(vec!["f128", "f128", "ZERO"])),
                _ => Ok(mk().lit_expr(mk().float_unsuffixed_lit("0."))),
            }
        } else if let &CTypeKind::Pointer(_) = resolved_ty {
            self.null_ptr(resolved_ty_id, is_static)
        } else if let &CTypeKind::ConstantArray(elt, sz) = resolved_ty {
            let sz = mk().lit_expr(mk().int_lit(sz as u128, LitIntType::Unsuffixed));
            Ok(mk().repeat_expr(self.implicit_default_expr(elt, is_static)?, sz))
        } else if let &CTypeKind::IncompleteArray(_) = resolved_ty {
            // Incomplete arrays are translated to zero length arrays
            Ok(mk().array_expr(vec![] as Vec<P<Expr>>))
        } 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();
            let val = self.implicit_default_expr(inner, is_static)?;
            Ok(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,
    ) -> Result<P<Expr>, TranslationError> {
        // Look up the decl in the cache and return what we find (if we find anything)
        if let Some(init) = self.zero_inits.borrow().get(&decl_id) {
            return init.clone();
        }

        // Otherwise, construct the initializer
        let init = match self.ast_context.index(decl_id).kind {
            // Zero initialize all of the fields
            CDeclKind::Struct {
                ref fields,
                platform_byte_size,
                ..
            } => {
                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 has_bitfields = fields
                    .iter()
                    .map(|field_id| match self.ast_context.index(*field_id).kind {
                        CDeclKind::Field { bitfield_width, .. } => bitfield_width.is_some(),
                        _ => unreachable!("Found non-field in record field list"),
                    })
                    .any(|x| x);

                if has_bitfields {
                    self.bitfield_zero_initializer(name, fields, platform_byte_size, is_static)
                } else {
                    let fields: Result<Vec<Field>, TranslationError> = fields
                        .into_iter()
                        .map(|field_id| {
                            let name = self
                                .type_converter
                                .borrow()
                                .resolve_field_name(Some(decl_id), *field_id)
                                .unwrap();

                            match self.ast_context.index(*field_id).kind {
                                CDeclKind::Field { typ, .. } => {
                                    let field_init =
                                        self.implicit_default_expr(typ.ctype, is_static)?;
                                    Ok(mk().field(name, field_init))
                                }
                                _ => Err(TranslationError::generic(
                                    "Found non-field in record field list",
                                )),
                            }
                        })
                        .collect();

                    Ok(mk().struct_expr(vec![name], fields?))
                }
            }

            // 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(format_err!("A union should have a field"))?;

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

                        Ok(mk().field(name, field_init))
                    }
                    _ => Err(format_err!("Found non-field in record field list")),
                }?;

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

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

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

        // Insert the initializer into the cache, then return it
        self.zero_inits.borrow_mut().insert(decl_id, init.clone());
        init
    }

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

        if self.ast_context.is_function_pointer(ty_id) {
            if target {
                mk().method_call_expr(val, "is_some", vec![] as Vec<P<Expr>>)
            } else {
                mk().method_call_expr(val, "is_none", vec![] as Vec<P<Expr>>)
            }
        } else if ty.is_pointer() {
            let mut res = mk().method_call_expr(val, "is_null", vec![] as Vec<P<Expr>>);
            if target {
                res = mk().unary_expr(ast::UnOp::Not, res)
            }
            res
        } else if ty.is_bool() {
            if target {
                val
            } else {
                mk().unary_expr(ast::UnOp::Not, val)
            }
        } else {
            let zero = if ty.is_floating_type() {
                mk().lit_expr(mk().float_unsuffixed_lit("0."))
            } else {
                mk().lit_expr(mk().int_lit(0, LitIntType::Unsuffixed))
            };

            // 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 ExprKind::Cast(ref arg, _) = val.node {
                if let ExprKind::Binary(op, _, _) = arg.node {
                    match op.node {
                        BinOpKind::Or
                        | BinOpKind::And
                        | BinOpKind::Eq
                        | BinOpKind::Ne
                        | BinOpKind::Lt
                        | BinOpKind::Le
                        | BinOpKind::Gt
                        | BinOpKind::Ge => {
                            if target {
                                // If target == true, just return the argument
                                return arg.clone();
                            } else {
                                // If target == false, return !arg
                                return mk().unary_expr(ast::UnOp::Not, 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
            if target {
                mk().binary_expr(BinOpKind::Ne, zero, val)
            } else {
                mk().binary_expr(BinOpKind::Eq, zero, val)
            }
        }
    }

    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,
        item: P<Item>,
        decl_file_path: Option<&PathBuf>,
        main_file_path: &PathBuf,
    ) {
        if self.tcfg.reorganize_definitions
            && decl_file_path.expect("There should be a decl file path.") != main_file_path
        {
            let mut mod_blocks = self.mod_blocks.borrow_mut();
            let mod_block_items = mod_blocks
                .entry(decl_file_path.unwrap().clone())
                .or_insert(ItemStore::new());

            mod_block_items.items.push(item);
        } else {
            self.item_store.borrow_mut().items.push(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,
        item: ForeignItem,
        decl_file_path: Option<&PathBuf>,
        main_file_path: &PathBuf,
    ) {
        if self.tcfg.reorganize_definitions && decl_file_path.unwrap() != main_file_path {
            let mut mod_blocks = self.mod_blocks.borrow_mut();
            let mod_block_items = mod_blocks
                .entry(decl_file_path.unwrap().clone())
                .or_insert(ItemStore::new());

            mod_block_items.foreign_items.push(item);
        } else {
            self.item_store.borrow_mut().foreign_items.push(item)
        }
    }

    fn match_type_kind(&self, ctype: CTypeId, store: &mut ItemStore, decl_file_path: &path::Path) {
        use self::CTypeKind::*;

        match self.ast_context[ctype].kind {
            Void | Char | SChar | UChar | Short | UShort | Int | UInt | Long | ULong | LongLong
            | ULongLong | Int128 | UInt128 | Half | Float | Double => {
                store.uses.get_mut(vec!["super".into()]).insert("libc");
            }
            LongDouble => {
                store.uses.get_mut(vec!["super".into()]).insert("f128");
            }
            // Bool uses the bool type, so no dependency on libc
            Bool => {}
            Paren(ctype)
            | Decayed(ctype)
            | IncompleteArray(ctype)
            | ConstantArray(ctype, _)
            | Elaborated(ctype)
            | Pointer(CQualTypeId { ctype, .. }) => {
                self.match_type_kind(ctype, store, decl_file_path)
            }
            Enum(decl_id) | Typedef(decl_id) | Union(decl_id) | Struct(decl_id) => {
                let mut decl_id = decl_id.clone();
                // 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 decl = &self.ast_context.c_decls[&decl_id];
                let decl_loc = &decl.loc.as_ref().unwrap();

                // If the definition lives in the same header, there is no need to import it
                // in fact, this would be a hard rust error
                if decl_loc.file_path.as_ref().unwrap() == decl_file_path {
                    return;
                }

                let ident_name = self
                    .type_converter
                    .borrow()
                    .resolve_decl_name(decl_id)
                    .unwrap();

                // Either the decl lives in the parent module, or else in a sibling submodule
                match decl_loc.file_path {
                    Some(ref decl_path) if decl_path == &self.main_file => {
                        store.uses.get_mut(vec!["super".into()]).insert(ident_name);
                    }
                    _ => {
                        let file_path = decl_loc.file_path.as_ref().unwrap();
                        let file_name = clean_path(&self.mod_names, &file_path);

                        store
                            .uses
                            .get_mut(vec!["super".into(), file_name])
                            .insert(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 {
                    self.match_type_kind(ctype, store, decl_file_path);
                }

                // Param Types
                for param_id in params {
                    self.match_type_kind(param_id.ctype, store, decl_file_path);
                }
            }
            Vector(CQualTypeId { ctype, .. }, len) => {
                // Since vector imports are global, we can find the correct type name in the parent scope
                let type_name = match (&self.ast_context[ctype].kind, len) {
                    (CTypeKind::Float, 4) => "__m128",
                    (CTypeKind::Float, 8) => "__m256",
                    (CTypeKind::Double, 2) => "__m128d",
                    (CTypeKind::Double, 4) => "__m256d",
                    (CTypeKind::LongLong, 4) => "__m256i",
                    (CTypeKind::LongLong, 2)
                    | (CTypeKind::Char, 16)
                    | (CTypeKind::Int, 4)
                    | (CTypeKind::Short, 8) => "__m128i",
                    (CTypeKind::LongLong, 1) | (CTypeKind::Int, 2) => "__m64",
                    (kind, len) => unimplemented!("Unknown vector type: {:?} x {}", kind, len),
                };

                store
                    .uses
                    .get_mut(vec!["super".into()])
                    .insert_with_attr(type_name, mk().pub_());
            }
            ref e => unimplemented!("{:?}", e),
        }
    }

    fn generate_submodule_imports(&self, decl_id: CDeclId, decl_file_path: Option<&PathBuf>) {
        let decl_file_path = decl_file_path.expect("There should be a decl file path");
        let decl = self.ast_context.c_decls.get(&decl_id).unwrap();
        let mut sumbodule_items = self.mod_blocks.borrow_mut();
        let item_store = sumbodule_items
            .entry(decl_file_path.to_path_buf())
            .or_insert(ItemStore::new());

        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.c_decls[field_id].kind {
                        CDeclKind::Field { typ, .. } => {
                            self.match_type_kind(typ.ctype, item_store, decl_file_path)
                        }
                        _ => unreachable!("Found something in a struct other than a field"),
                    }
                }
            }
            CDeclKind::EnumConstant { .. } => {}
            // REVIEW: Enums can only be integer types? So libc is likely always required?
            CDeclKind::Enum { .. } => {
                item_store.uses.get_mut(vec!["super".into()]).insert("libc");
            }
            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, .. } => {
                self.match_type_kind(typ.ctype, item_store, decl_file_path)
            }
            CDeclKind::Function {
                is_global: true,
                typ,
                ..
            } => self.match_type_kind(typ, item_store, decl_file_path),
            CDeclKind::Function { .. } => {
                // 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),
        }
    }
}