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
use c2rust_ast_exporter::clang_ast::*;
use c_ast::*;
use serde_cbor::Value;
use std::collections::HashMap;
use std::vec::Vec;

/// Possible node types
pub type NodeType = u16;

mod node_types {
    pub const FUNC_TYPE: super::NodeType = 0b000000000001;
    pub const OTHER_TYPE: super::NodeType = 0b000000000010;
    pub const TYPE: super::NodeType = FUNC_TYPE | OTHER_TYPE;

    pub const EXPR: super::NodeType = 0b000000000100;

    pub const FIELD_DECL: super::NodeType = 0b000000001000;
    pub const VAR_DECL: super::NodeType = 0b000000010000;
    pub const RECORD_DECL: super::NodeType = 0b000000100000;
    pub const TYPDEF_DECL: super::NodeType = 0b000001000000;
    pub const ENUM_DECL: super::NodeType = 0b000010000000;
    pub const ENUM_CON: super::NodeType = 0b000100000000;
    pub const OTHER_DECL: super::NodeType = 0b001000000000;
    pub const DECL: super::NodeType =
        FIELD_DECL | VAR_DECL | RECORD_DECL | TYPDEF_DECL | ENUM_DECL | ENUM_CON | OTHER_DECL;

    pub const LABEL_STMT: super::NodeType = 0b010000000000;
    pub const OTHER_STMT: super::NodeType = 0b100000000000;
    pub const STMT: super::NodeType = LABEL_STMT | OTHER_STMT;
}

type ClangId = u64;
type ImporterId = u64;

/// Correspondence between old/new IDs.
///
/// We need to re-ID nodes since the mapping from Clang's AST to ours is not one-to-one. Sometimes
/// we need to add nodes (such as 'Semi' nodes to make the lifting of expressions into statements
/// explicit), sometimes we need to collapse (such as inlining 'FieldDecl' into the 'StructDecl').
#[derive(Debug)]
pub struct IdMapper {
    new_id_source: ImporterId,
    old_to_new: HashMap<ClangId, ImporterId>,
    new_to_old: HashMap<ImporterId, ClangId>,
}

impl IdMapper {
    pub fn new() -> IdMapper {
        IdMapper {
            new_id_source: 0,
            old_to_new: HashMap::new(),
            new_to_old: HashMap::new(),
        }
    }

    /// Create a fresh NEW_ID not corresponding to a CLANG_ID
    fn fresh_id(&mut self) -> ImporterId {
        self.new_id_source += 1;
        self.new_id_source
    }

    /// Lookup the NEW_ID corresponding to a CLANG_ID
    pub fn get_new(&mut self, old_id: ClangId) -> Option<ImporterId> {
        self.old_to_new.get(&old_id).map(|o| *o)
    }

    /// Lookup (or create if not a found) a NEW_ID corresponding to a CLANG_ID
    pub fn get_or_create_new(&mut self, old_id: ClangId) -> ImporterId {
        match self.get_new(old_id) {
            Some(new_id) => new_id,
            None => {
                let new_id = self.fresh_id();
                let inserted = self.old_to_new.insert(old_id, new_id).is_some();
                assert!(
                    !inserted,
                    "get_or_create_new: overwrote an old id at {}",
                    old_id
                );
                new_id
            }
        }
    }

    /// Lookup the CLANG_ID corresponding to a NEW_ID
    pub fn get_old(&mut self, new_id: ImporterId) -> Option<ClangId> {
        self.new_to_old.get(&new_id).map(|n| *n)
    }

    /// If the `old_id` is present in the mapper, make `other_old_id` map to the same value. Note
    /// that `other_old_id` should not already be in the mapper.
    pub fn merge_old(&mut self, old_id: ClangId, other_old_id: ClangId) -> Option<ImporterId> {
        self.get_new(old_id).map(|new_id| {
            let inserted = self.old_to_new.insert(other_old_id, new_id).is_some();
            assert!(
                !inserted,
                "get_or_create_new: overwrote an old id at {}",
                other_old_id
            );
            new_id
        })
    }
}

/// Transfer location information off of an `AstNode` and onto something that is `Located`
fn located<T>(node: &AstNode, t: T) -> Located<T> {
    Located {
        loc: Some(SrcLoc {
            line: node.line,
            column: node.column,
            fileid: node.fileid,
            file_path: node.file_path.clone(),
        }),
        kind: t,
    }
}

/// Wrap something into a `Located` node without any location information
fn not_located<T>(t: T) -> Located<T> {
    Located { loc: None, kind: t }
}

fn parse_cast_kind(kind: &str) -> CastKind {
    match kind {
        "BitCast" => CastKind::BitCast,
        "LValueToRValue" => CastKind::LValueToRValue,
        "NoOp" => CastKind::NoOp,
        "ToUnion" => CastKind::ToUnion,
        "ArrayToPointerDecay" => CastKind::ArrayToPointerDecay,
        "FunctionToPointerDecay" => CastKind::FunctionToPointerDecay,
        "NullToPointer" => CastKind::NullToPointer,
        "IntegralToPointer" => CastKind::IntegralToPointer,
        "PointerToIntegral" => CastKind::PointerToIntegral,
        "ToVoid" => CastKind::ToVoid,
        "IntegralCast" => CastKind::IntegralCast,
        "IntegralToBoolean" => CastKind::IntegralToBoolean,
        "IntegralToFloating" => CastKind::IntegralToFloating,
        "FloatingToIntegral" => CastKind::FloatingToIntegral,
        "FloatingToBoolean" => CastKind::FloatingToBoolean,
        "BooleanToSignedIntegral" => CastKind::BooleanToSignedIntegral,
        "PointerToBoolean" => CastKind::PointerToBoolean,
        "FloatingCast" => CastKind::FloatingCast,
        "FloatingRealToComplex" => CastKind::FloatingRealToComplex,
        "FloatingComplexToReal" => CastKind::FloatingComplexToReal,
        "FloatingComplexCast" => CastKind::FloatingComplexCast,
        "FloatingComplexToIntegralComplex" => CastKind::FloatingComplexToIntegralComplex,
        "IntegralRealToComplex" => CastKind::IntegralRealToComplex,
        "IntegralComplexToReal" => CastKind::IntegralComplexToReal,
        "IntegralComplexToBoolean" => CastKind::IntegralComplexToBoolean,
        "IntegralComplexCast" => CastKind::IntegralComplexCast,
        "IntegralComplexToFloatingComplex" => CastKind::IntegralComplexToFloatingComplex,
        "BuiltinFnToFnPtr" => CastKind::BuiltinFnToFnPtr,
        "ConstCast" => CastKind::ConstCast,
        "VectorSplat" => CastKind::VectorSplat,
        k => panic!("Unsupported implicit cast: {}", k),
    }
}

fn parse_attributes(attributes: &[Value]) -> IndexSet<Attribute> {
    let mut attrs = IndexSet::new();
    let mut expect_section_value = false;
    let mut expect_alias_value = false;

    for attr in attributes {
        let attr_str = attr
            .as_string()
            .expect("Decl attributes should be strings")
            .as_str();

        match attr_str {
            "alias" => expect_alias_value = true,
            "always_inline" => {
                attrs.insert(Attribute::AlwaysInline);
            }
            "cold" => {
                attrs.insert(Attribute::Cold);
            }
            "gnu_inline" => {
                attrs.insert(Attribute::GnuInline);
            }
            "noinline" => {
                attrs.insert(Attribute::NoInline);
            }
            "used" => {
                attrs.insert(Attribute::Used);
            }
            "section" => expect_section_value = true,
            s if expect_section_value => {
                attrs.insert(Attribute::Section(s.into()));

                expect_section_value = false;
            }
            s if expect_alias_value => {
                attrs.insert(Attribute::Alias(s.into()));

                expect_alias_value = false;
            }
            _ => {}
        }
    }

    attrs
}

/// This stores the information needed to convert an `AstContext` into a `TypedAstContext`.
pub struct ConversionContext {
    /// Keeps track of the mapping between IDs used by clang (old) and the AST importer (new)
    pub id_mapper: IdMapper,

    /// Keep track of new nodes already processed and their types
    processed_nodes: HashMap<ImporterId, NodeType>,

    /// Stack of nodes to visit, and the types we expect to see out of them
    visit_as: Vec<(ClangId, NodeType)>,

    /// Typed context we are building up during the conversion
    pub typed_context: TypedAstContext,
}

impl ConversionContext {
    /// Create a new 'ConversionContext' seeded with top-level nodes from an 'AstContext'.
    pub fn new(untyped_context: &AstContext) -> ConversionContext {
        // This starts out as all of the top-level nodes, which we expect to be 'DECL's
        let mut visit_as: Vec<(ClangId, NodeType)> = Vec::new();
        for top_node in untyped_context.top_nodes.iter().rev() {
            if untyped_context.ast_nodes.contains_key(&top_node) {
                visit_as.push((*top_node, node_types::DECL));
            }
        }

        ConversionContext {
            id_mapper: IdMapper::new(),
            processed_nodes: HashMap::new(),
            visit_as,
            typed_context: TypedAstContext::new(),
        }
    }

    /// Records the fact that we will need to visit a Clang node and the type we want it to have.
    ///
    /// Returns the new ID that identifies this new node.
    fn visit_node_type(&mut self, node_id: ClangId, node_ty: NodeType) -> ImporterId {
        // Type node IDs have extra information on them
        let node_id = if node_ty & node_types::TYPE != 0 {
            node_id & TypeNode::ID_MASK
        } else {
            node_id
        };

        self.visit_as.push((node_id, node_ty));
        self.id_mapper.get_or_create_new(node_id)
    }

    /// Like `visit_node_type`, but specifically for type nodes
    fn visit_type(&mut self, node_id: ClangId) -> CTypeId {
        CTypeId(self.visit_node_type(node_id, node_types::TYPE))
    }

    /// Like `visit_node_type`, but specifically for qualified type nodes
    ///
    /// Since we store qualifier information on the low-bits of the `ClangId`, we don't even need to
    /// look the node up in the context.
    fn visit_qualified_type(&mut self, node_id: ClangId) -> CQualTypeId {
        let qualifiers = Qualifiers {
            is_const: node_id & TypeNode::CONST_MASK != 0,
            is_restrict: node_id & TypeNode::RESTRICT_MASK != 0,
            is_volatile: node_id & TypeNode::VOLATILE_MASK != 0,
        };
        let ctype = self.visit_type(node_id);

        CQualTypeId { qualifiers, ctype }
    }

    /// Like `visit_node_type`, but specifically for statement nodes
    fn visit_stmt(&mut self, node_id: ClangId) -> CStmtId {
        CStmtId(self.visit_node_type(node_id, node_types::STMT))
    }

    /// Like `visit_node_type`, but specifically for expression nodes
    fn visit_expr(&mut self, node_id: ClangId) -> CExprId {
        CExprId(self.visit_node_type(node_id, node_types::EXPR))
    }

    /// Like `visit_node_type`, but specifically for declaration nodes
    fn visit_decl(&mut self, node_id: ClangId) -> CDeclId {
        CDeclId(self.visit_node_type(node_id, node_types::DECL))
    }

    /// Add a `CType`node into the `TypedAstContext`
    fn add_type(&mut self, id: ImporterId, typ: CType) -> () {
        self.typed_context.c_types.insert(CTypeId(id), typ);
    }

    /// Add a `CStmt` node into the `TypedAstContext`
    fn add_stmt(&mut self, id: ImporterId, stmt: CStmt) -> () {
        self.typed_context.c_stmts.insert(CStmtId(id), stmt);
    }

    /// Add a `CExpr` node into the `TypedAstContext`
    fn add_expr(&mut self, id: ImporterId, expr: CExpr) -> () {
        self.typed_context.c_exprs.insert(CExprId(id), expr);
    }

    /// Add a `CDecl` node into the `TypedAstContext`
    fn add_decl(&mut self, id: ImporterId, decl: CDecl) -> () {
        self.typed_context.c_decls.insert(CDeclId(id), decl);
    }

    /// Clang has `Expression <: Statement`, but we want to make that explicit via the
    /// `CStmtKind::Expr` statement constructor. This function automatically converts expressions
    /// into statements depending on the expected type argument.
    fn expr_possibly_as_stmt(
        &mut self,
        expected_ty: NodeType, // Should be one of `EXPR` or `STMT`
        new_id: ImporterId,
        node: &AstNode,
        expr: CExprKind,
    ) -> () {
        if expected_ty & node_types::STMT != 0 {
            // This is going to be an extra node not present in the Clang AST
            let new_expr_id = self.id_mapper.fresh_id();
            self.add_expr(new_expr_id, located(node, expr));
            self.processed_nodes.insert(new_expr_id, node_types::EXPR);

            // We wrap the expression in a STMT
            let semi_stmt = CStmtKind::Expr(CExprId(new_expr_id));
            self.add_stmt(new_id, located(node, semi_stmt));
            self.processed_nodes.insert(new_id, node_types::STMT);
        } else if expected_ty & node_types::EXPR != 0 {
            // No special work to do...
            self.add_expr(new_id, located(node, expr));
            self.processed_nodes.insert(new_id, node_types::EXPR);
        } else {
            panic!("'expr_possibly_as_stmt' expects 'expected_ty' to be either 'EXPR' or 'STMT'");
        }
    }

    /// Convert the contents of an `AstContext`, starting from the top-level declarations passed
    /// into the `ConversionContext` on creation.
    ///
    /// This populates the `typed_context` of the `ConversionContext` it is called on.
    pub fn convert(&mut self, untyped_context: &AstContext) -> () {
        for raw_comment in &untyped_context.comments {
            let comment = Located {
                loc: Some(SrcLoc {
                    line: raw_comment.line,
                    column: raw_comment.column,
                    fileid: raw_comment.fileid,
                    // Can/Should we get file paths for comments?
                    file_path: None,
                }),
                kind: raw_comment.string.clone(),
            };
            self.typed_context.comments.push(comment);
        }

        // Continue popping Clang nodes off of the stack of nodes we have promised to visit
        while let Some((node_id, expected_ty)) = self.visit_as.pop() {
            // Check if we've already processed this node. If so, ascertain that it has the right
            // type.
            if let Some(ty) = self
                .id_mapper
                .get_new(node_id)
                .and_then(|new_id| self.processed_nodes.get(&new_id))
            {
                if ty & expected_ty != 0 {
                    continue;
                }
                panic!(
                    "Expected {} to be a node of type {}, not {}",
                    &node_id, expected_ty, ty
                );
            }

            // Create a `NewId` for this node
            let new_id = self.id_mapper.get_or_create_new(node_id);

            // If the node is top-level, add it as such to the new context
            if untyped_context.top_nodes.contains(&node_id) {
                self.typed_context.c_decls_top.push(CDeclId(new_id));
            }

            self.visit_node(untyped_context, node_id, new_id, expected_ty)
        }
    }

    /// Visit one node.
    fn visit_node(
        &mut self,
        untyped_context: &AstContext,
        node_id: ClangId,      // Clang ID of node to visit
        new_id: ImporterId,    // New ID of node to visit
        expected_ty: NodeType, // Expected type of node to visit
    ) -> () {
        use self::node_types::*;

        if expected_ty & TYPE != 0 {
            // Convert the node
            let ty_node: &TypeNode = match untyped_context.type_nodes.get(&node_id) {
                Some(x) => x,
                None => return,
            };

            match ty_node.tag {
                TypeTag::TagBool if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::Bool));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagVoid if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::Void));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagChar if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::Char));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagInt if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::Int));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagShort if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::Short));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagLong if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::Long));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagLongLong if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::LongLong));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagUInt if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::UInt));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagUChar if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::UChar));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagSChar if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::SChar));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagUShort if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::UShort));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagULong if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::ULong));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagULongLong if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::ULongLong));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagDouble if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::Double));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagLongDouble if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::LongDouble));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagFloat if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::Float));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagHalf if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::Half));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagInt128 if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::Int128));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagUInt128 if expected_ty & OTHER_TYPE != 0 => {
                    self.add_type(new_id, not_located(CTypeKind::UInt128));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagPointer if expected_ty & OTHER_TYPE != 0 => {
                    let pointed = ty_node.extras[0].as_u64().expect("Pointer child not found");
                    let pointed_new = self.visit_qualified_type(pointed);

                    let pointer_ty = CTypeKind::Pointer(pointed_new);
                    self.add_type(new_id, not_located(pointer_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagBlockPointer if expected_ty & OTHER_TYPE != 0 => {
                    let pointed = ty_node.extras[0]
                        .as_u64()
                        .expect("Block pointer child not found");
                    let pointed_new = self.visit_qualified_type(pointed);

                    let pointer_ty = CTypeKind::BlockPointer(pointed_new);
                    self.add_type(new_id, not_located(pointer_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagComplexType if expected_ty & OTHER_TYPE != 0 => {
                    let subelt = ty_node.extras[0].as_u64().expect("Complex child not found");
                    let subelt_new = self.visit_type(subelt);

                    let complex_ty = CTypeKind::Complex(subelt_new);
                    self.add_type(new_id, not_located(complex_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagStructType if expected_ty & OTHER_TYPE != 0 => {
                    let decl = ty_node.extras[0].as_u64().expect("Struct decl not found");
                    let decl_new = CDeclId(self.visit_node_type(decl, RECORD_DECL));

                    let record_ty = CTypeKind::Struct(decl_new);
                    self.add_type(new_id, not_located(record_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagUnionType if expected_ty & OTHER_TYPE != 0 => {
                    let decl = ty_node.extras[0].as_u64().expect("Union decl not found");
                    let decl_new = CDeclId(self.visit_node_type(decl, RECORD_DECL));

                    let record_ty = CTypeKind::Union(decl_new);
                    self.add_type(new_id, not_located(record_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagFunctionType if expected_ty & FUNC_TYPE != 0 => {
                    let mut arguments: Vec<CQualTypeId> = ty_node.extras[0]
                        .as_array()
                        .expect("Function type expects array argument")
                        .iter()
                        .map(|cbor| {
                            let arg = cbor.as_u64().expect("Bad function type child id");
                            let arg_new = self.visit_qualified_type(arg);

                            arg_new
                        })
                        .collect();
                    let ret = arguments.remove(0);
                    let is_variadic = ty_node.extras[1]
                        .as_boolean()
                        .expect("Variadicity of function type not found");
                    let is_noreturn = ty_node.extras[2]
                        .as_boolean()
                        .expect("NoReturn of function type not found");
                    let has_proto = ty_node.extras[3]
                        .as_boolean()
                        .expect("HasProto of function type not found");
                    let function_ty =
                        CTypeKind::Function(ret, arguments, is_variadic, is_noreturn, has_proto);
                    self.add_type(new_id, not_located(function_ty));
                    self.processed_nodes.insert(new_id, FUNC_TYPE);
                }

                TypeTag::TagTypeOfType if expected_ty & TYPE != 0 => {
                    let type_of_old = ty_node.extras[0]
                        .as_u64()
                        .expect("Type of (type) child not found");
                    let type_of = self.visit_type(type_of_old);

                    let type_of_ty = CTypeKind::TypeOf(type_of);
                    self.add_type(new_id, not_located(type_of_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagTypedefType => {
                    let decl = ty_node.extras[0].as_u64().expect("Typedef decl not found");
                    let decl_new = CDeclId(self.visit_node_type(decl, TYPDEF_DECL));

                    let typedef_ty = CTypeKind::Typedef(decl_new);
                    self.add_type(new_id, not_located(typedef_ty));
                    self.processed_nodes.insert(new_id, expected_ty);
                }

                TypeTag::TagEnumType if expected_ty & OTHER_TYPE != 0 => {
                    let decl = ty_node.extras[0].as_u64().expect("Enum decl not found");
                    let decl_new = CDeclId(self.visit_node_type(decl, ENUM_DECL));

                    let enum_ty = CTypeKind::Enum(decl_new);
                    self.add_type(new_id, not_located(enum_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagDecayedType if expected_ty & OTHER_TYPE != 0 => {
                    let decayed_id = ty_node.extras[0]
                        .as_u64()
                        .expect("Decayed type child not found");
                    let decayed = self.visit_type(decayed_id);

                    let decayed_ty = CTypeKind::Decayed(decayed);
                    self.add_type(new_id, not_located(decayed_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagElaboratedType if expected_ty & OTHER_TYPE != 0 => {
                    let elaborated_id = ty_node.extras[0]
                        .as_u64()
                        .expect("Elaborated type child not found");
                    let elaborated = self.visit_type(elaborated_id);

                    let elaborated_ty = CTypeKind::Elaborated(elaborated);
                    self.add_type(new_id, not_located(elaborated_ty));
                    self.processed_nodes.insert(new_id, TYPE);
                }

                TypeTag::TagParenType => {
                    let paren_id = ty_node.extras[0]
                        .as_u64()
                        .expect("Paren type child not found");
                    let paren = self.visit_type(paren_id);

                    let paren_ty = CTypeKind::Paren(paren);
                    self.add_type(new_id, not_located(paren_ty));
                    self.processed_nodes.insert(new_id, TYPE);
                }

                TypeTag::TagAttributedType => {
                    let ty_id = ty_node.extras[0]
                        .as_u64()
                        .expect("Attributed type child not found");
                    let ty = self.visit_qualified_type(ty_id);

                    let kind = match expect_opt_str(&ty_node.extras[1])
                        .expect("Attributed type kind not found")
                    {
                        None => None,
                        Some("noreturn") => Some(Attribute::NoReturn),
                        Some("nullable") => Some(Attribute::Nullable),
                        Some("notnull") => Some(Attribute::NotNull),
                        Some(other) => panic!("Unknown type attribute: {}", other),
                    };

                    let ty = CTypeKind::Attributed(ty, kind);
                    self.add_type(new_id, not_located(ty));
                    self.processed_nodes.insert(new_id, TYPE);
                }

                TypeTag::TagConstantArrayType => {
                    let element_id = ty_node.extras[0].as_u64().expect("element id");
                    let element = self.visit_type(element_id);

                    let count = ty_node.extras[1].as_u64().expect("count");

                    let element_ty = CTypeKind::ConstantArray(element, count as usize);
                    self.add_type(new_id, not_located(element_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagIncompleteArrayType => {
                    let element_id = ty_node.extras[0].as_u64().expect("element id");
                    let element = self.visit_type(element_id);

                    let element_ty = CTypeKind::IncompleteArray(element);
                    self.add_type(new_id, not_located(element_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagVariableArrayType => {
                    let element_id = ty_node.extras[0].as_u64().expect("element id");
                    let element = self.visit_type(element_id);

                    let count_id = expect_opt_u64(&ty_node.extras[1]).expect("count id");
                    let count = count_id.map(|x| self.visit_expr(x));

                    let element_ty = CTypeKind::VariableArray(element, count);
                    self.add_type(new_id, not_located(element_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagBuiltinFn => {
                    let ty = CTypeKind::BuiltinFn;
                    self.add_type(new_id, not_located(ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                TypeTag::TagVectorType => {
                    let elt = ty_node.extras[0].as_u64().expect("Vector child not found");
                    let elt_new = self.visit_qualified_type(elt);
                    let count = ty_node.extras[1].as_u64().expect("count");

                    let vector_ty = CTypeKind::Vector(elt_new, count as usize);
                    self.add_type(new_id, not_located(vector_ty));
                    self.processed_nodes.insert(new_id, OTHER_TYPE);
                }

                t => panic!(
                    "Type conversion not implemented for {:?} expecting {:?}",
                    t, expected_ty
                ),
            }
        } else {
            // Convert the node
            let node: &AstNode = match untyped_context.ast_nodes.get(&node_id) {
                Some(x) => x,
                None => return,
            };

            match node.tag {
                // Statements
                ASTEntryTag::TagBreakStmt if expected_ty & OTHER_STMT != 0 => {
                    self.add_stmt(new_id, located(node, CStmtKind::Break));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagContinueStmt if expected_ty & OTHER_STMT != 0 => {
                    self.add_stmt(new_id, located(node, CStmtKind::Continue));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagCompoundStmt if expected_ty & OTHER_STMT != 0 => {
                    let constituent_stmts: Vec<CStmtId> = node
                        .children
                        .iter()
                        .map(|id| {
                            let arg_id = id.expect("Compound stmt child not found");
                            self.visit_stmt(arg_id)
                        })
                        .collect();

                    let compound_stmt = CStmtKind::Compound(constituent_stmts);

                    self.add_stmt(new_id, located(node, compound_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagDeclStmt if expected_ty & OTHER_STMT != 0 => {
                    let decls = node
                        .children
                        .iter()
                        .map(|decl| {
                            let decl_id = decl.expect("Decl not found in decl-statement");
                            self.visit_decl(decl_id)
                        })
                        .collect();

                    let decls_stmt = CStmtKind::Decls(decls);

                    self.add_stmt(new_id, located(node, decls_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagReturnStmt if expected_ty & OTHER_STMT != 0 => {
                    let return_expr_opt = node.children[0].map(|id| self.visit_expr(id));

                    let return_stmt = CStmtKind::Return(return_expr_opt);

                    self.add_stmt(new_id, located(node, return_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagIfStmt if expected_ty & OTHER_STMT != 0 => {
                    let scrutinee_old =
                        node.children[0].expect("If condition expression not found");
                    let scrutinee = self.visit_expr(scrutinee_old);

                    let true_variant_old =
                        node.children[1].expect("If then body statement not found");
                    let true_variant = self.visit_stmt(true_variant_old);

                    let false_variant = node.children[2].map(|id| self.visit_stmt(id));

                    let if_stmt = CStmtKind::If {
                        scrutinee,
                        true_variant,
                        false_variant,
                    };

                    self.add_stmt(new_id, located(node, if_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagGotoStmt if expected_ty & OTHER_STMT != 0 => {
                    let target_label_old = node.children[0].expect("Goto target label not found");
                    let target_label = CStmtId(self.visit_node_type(target_label_old, LABEL_STMT));

                    let goto_stmt = CStmtKind::Goto(target_label);

                    self.add_stmt(new_id, located(node, goto_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagNullStmt if expected_ty & OTHER_STMT != 0 => {
                    let null_stmt = CStmtKind::Empty;

                    self.add_stmt(new_id, located(node, null_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagForStmt if expected_ty & OTHER_STMT != 0 => {
                    let init = node.children[0].map(|id| self.visit_stmt(id));

                    let condition = node.children[1].map(|id| self.visit_expr(id));

                    let increment = node.children[2].map(|id| self.visit_expr(id));

                    let body_old = node.children[3].expect("For loop body not found");
                    let body = self.visit_stmt(body_old);

                    let for_stmt = CStmtKind::ForLoop {
                        init,
                        condition,
                        increment,
                        body,
                    };

                    self.add_stmt(new_id, located(node, for_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagWhileStmt if expected_ty & OTHER_STMT != 0 => {
                    let condition_old = node.children[0].expect("While loop condition not found");
                    let condition = self.visit_expr(condition_old);

                    let body_old = node.children[1].expect("While loop body not found");
                    let body = self.visit_stmt(body_old);

                    let while_stmt = CStmtKind::While { condition, body };

                    self.add_stmt(new_id, located(node, while_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagDoStmt if expected_ty & OTHER_STMT != 0 => {
                    let body_old = node.children[0].expect("Do loop body not found");
                    let body = self.visit_stmt(body_old);

                    let condition_old = node.children[1].expect("Do loop condition not found");
                    let condition = self.visit_expr(condition_old);

                    let do_stmt = CStmtKind::DoWhile { body, condition };

                    self.add_stmt(new_id, located(node, do_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagLabelStmt if expected_ty & LABEL_STMT != 0 => {
                    let substmt_old = node.children[0].expect("Label sub-statement not found");
                    let substmt = self.visit_stmt(substmt_old);

                    let label_stmt = CStmtKind::Label(substmt);

                    self.add_stmt(new_id, located(node, label_stmt));
                    self.processed_nodes.insert(new_id, LABEL_STMT);
                }

                ASTEntryTag::TagSwitchStmt if expected_ty & OTHER_STMT != 0 => {
                    let scrutinee_old = node.children[0].expect("Switch expression not found");
                    let scrutinee = self.visit_expr(scrutinee_old);

                    let body_old = node.children[1].expect("Switch body not found");
                    let body = self.visit_stmt(body_old);

                    let switch_stmt = CStmtKind::Switch { scrutinee, body };

                    self.add_stmt(new_id, located(node, switch_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagCaseStmt if expected_ty & OTHER_STMT != 0 => {
                    let expr_old = node.children[0].expect("Case expression not found");
                    let expr = self.visit_expr(expr_old);

                    let substmt_old = node.children[1].expect("Case sub-statement not found");
                    let substmt = self.visit_stmt(substmt_old);

                    let cie = match node.extras[0] {
                        Value::U64(n) => ConstIntExpr::U(n),
                        Value::I64(n) => ConstIntExpr::I(n),
                        _ => panic!("Expected constant int expr"),
                    };

                    let case_stmt = CStmtKind::Case(expr, substmt, cie);

                    self.add_stmt(new_id, located(node, case_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagDefaultStmt if expected_ty & OTHER_STMT != 0 => {
                    let substmt_old = node.children[0].expect("Default sub-statement not found");
                    let substmt = self.visit_stmt(substmt_old);

                    let default_stmt = CStmtKind::Default(substmt);

                    self.add_stmt(new_id, located(node, default_stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                ASTEntryTag::TagAsmStmt if expected_ty & OTHER_STMT != 0 => {
                    let is_volatile = node.extras[0].as_boolean().expect("volatile flag");
                    let asm = node.extras[1]
                        .as_string()
                        .expect("assembly string")
                        .to_owned();
                    let raw_inputs = node.extras[2].as_array().expect("input constraints array");
                    let raw_outputs = node.extras[3].as_array().expect("output constraints array");
                    let raw_clobbers = node.extras[4].as_array().expect("clobber array");

                    let (input_children, output_children) =
                        node.children.split_at(raw_inputs.len());

                    let inputs: Vec<AsmOperand> = raw_inputs
                        .iter()
                        .zip(input_children)
                        .map(|(c, e)| {
                            let constraints = c.as_string().expect("constraint string").to_owned();
                            let expression = self.visit_expr(e.expect("expression"));
                            AsmOperand {
                                constraints,
                                expression,
                            }
                        })
                        .collect();

                    let outputs: Vec<AsmOperand> = raw_outputs
                        .iter()
                        .zip(output_children)
                        .map(|(c, e)| {
                            let constraints = c.as_string().expect("constraint string").to_owned();
                            let expression = self.visit_expr(e.expect("expression"));
                            AsmOperand {
                                constraints,
                                expression,
                            }
                        })
                        .collect();

                    let clobbers: Vec<String> = raw_clobbers
                        .iter()
                        .map(|c| c.as_string().expect("clobber string").to_owned())
                        .collect();

                    let stmt = CStmtKind::Asm {
                        is_volatile,
                        asm,
                        inputs,
                        outputs,
                        clobbers,
                    };
                    self.add_stmt(new_id, located(node, stmt));
                    self.processed_nodes.insert(new_id, OTHER_STMT);
                }

                // Expressions
                ASTEntryTag::TagParenExpr if expected_ty & (EXPR | STMT) != 0 => {
                    let wrapped = node.children[0].expect("Expected wrapped paren expression");

                    self.id_mapper.merge_old(node_id, wrapped);
                    self.visit_node_type(wrapped, expected_ty);
                }

                ASTEntryTag::TagOffsetOfExpr if expected_ty & (EXPR | STMT) != 0 => {
                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);
                    // Either we're able to evaluate the offsetof to an int constant expr
                    // or else we have to use the offset_of! macro from the memoffset crate
                    let offset_of = if let Some(value) = node.extras[0].as_u64() {
                        let kind = OffsetOfKind::Constant(value);

                        CExprKind::OffsetOf(ty, kind)
                    } else {
                        let qty_int = node.extras[1]
                            .as_u64()
                            .expect("Expected offset of to have struct type");
                        let qty = self.visit_qualified_type(qty_int);
                        let field = node.extras[2].as_u64().expect("Expected offset of field");
                        let field_id = self.visit_decl(field);
                        let index = node.extras[3]
                            .as_u64()
                            .expect("Expected offset of index expr");
                        let index_expr_id = self.visit_expr(index);
                        let kind = OffsetOfKind::Variable(qty, field_id, index_expr_id);

                        CExprKind::OffsetOf(ty, kind)
                    };

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, offset_of);
                }

                ASTEntryTag::TagIntegerLiteral if expected_ty & (EXPR | STMT) != 0 => {
                    let value = node.extras[0]
                        .as_u64()
                        .expect("Expected integer literal value");
                    let base = node.extras[1]
                        .as_u64()
                        .expect("Expected integer base value");

                    let base = match base {
                        8 => IntBase::Oct,
                        10 => IntBase::Dec,
                        16 => IntBase::Hex,
                        _ => panic!("Invalid base: {}", base),
                    };

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let integer_literal = CExprKind::Literal(ty, CLiteral::Integer(value, base));

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, integer_literal);
                }

                ASTEntryTag::TagStringLiteral if expected_ty & (EXPR | STMT) != 0 => {
                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);
                    let width = node.extras[1].as_u64().expect("string literal char width") as u8;
                    let bytes = node.extras[2]
                        .as_bytes()
                        .expect("string literal bytes")
                        .to_owned();
                    let string_literal = CExprKind::Literal(ty, CLiteral::String(bytes, width));
                    self.expr_possibly_as_stmt(expected_ty, new_id, node, string_literal);
                }

                ASTEntryTag::TagCharacterLiteral if expected_ty & (EXPR | STMT) != 0 => {
                    let value = node.extras[0]
                        .as_u64()
                        .expect("Expected character literal value");

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let character_literal = CExprKind::Literal(ty, CLiteral::Character(value));

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, character_literal);
                }

                ASTEntryTag::TagFloatingLiteral if expected_ty & (EXPR | STMT) != 0 => {
                    let value = node.extras[0]
                        .as_f64()
                        .expect("Expected float literal value");
                    let c_str = node.extras[1]
                        .as_string()
                        .expect("Expected float literal string")
                        .to_owned();
                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let floating_literal = CExprKind::Literal(ty, CLiteral::Floating(value, c_str));

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, floating_literal);
                }

                ASTEntryTag::TagUnaryOperator if expected_ty & (EXPR | STMT) != 0 => {
                    let prefix = node.extras[1]
                        .as_boolean()
                        .expect("Expected prefix information");

                    let operator = match node.extras[0]
                        .as_string()
                        .expect("Expected operator")
                        .as_str()
                    {
                        "&" => UnOp::AddressOf,
                        "*" => UnOp::Deref,
                        "+" => UnOp::Plus,
                        "-" => UnOp::Negate,
                        "~" => UnOp::Complement,
                        "!" => UnOp::Not,
                        "++" => {
                            if prefix {
                                UnOp::PreIncrement
                            } else {
                                UnOp::PostIncrement
                            }
                        }
                        "--" => {
                            if prefix {
                                UnOp::PreDecrement
                            } else {
                                UnOp::PostDecrement
                            }
                        }
                        "__real" => UnOp::Real,
                        "__imag" => UnOp::Imag,
                        "__extension__" => UnOp::Extension,
                        "co_await" => UnOp::Coawait,
                        o => panic!("Unexpected operator: {}", o),
                    };

                    let operand_old = node.children[0].expect("Expected operand");
                    let operand = self.visit_expr(operand_old);

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let unary = CExprKind::Unary(ty, operator, operand, node.rvalue);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, unary);
                }

                ASTEntryTag::TagImplicitCastExpr if expected_ty & (EXPR | STMT) != 0 => {
                    let expression_old =
                        node.children[0].expect("Expected expression for implicit cast");
                    let expression = self.visit_expr(expression_old);

                    let typ_old = node.type_id.expect("Expected type for implicit cast");
                    let typ = self.visit_qualified_type(typ_old);

                    let kind =
                        parse_cast_kind(node.extras[0].as_string().expect("Expected cast kind"));
                    let implicit =
                        CExprKind::ImplicitCast(typ, expression, kind, None, node.rvalue);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, implicit);
                }

                ASTEntryTag::TagCStyleCastExpr if expected_ty & (EXPR | STMT) != 0 => {
                    let expression_old =
                        node.children[0].expect("Expected expression for explicit cast");
                    let expression = self.visit_expr(expression_old);

                    let typ_old = node.type_id.expect("Expected type for explicit cast");
                    let typ = self.visit_qualified_type(typ_old);

                    let kind =
                        parse_cast_kind(node.extras[0].as_string().expect("Expected cast kind"));

                    let opt_field_id = match kind {
                        CastKind::ToUnion => {
                            let id = node.children[1].expect("Expected field for union cast");
                            Some(self.visit_decl(id))
                        }
                        _ => None,
                    };

                    let implicit =
                        CExprKind::ExplicitCast(typ, expression, kind, opt_field_id, node.rvalue);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, implicit);
                }

                ASTEntryTag::TagCallExpr if expected_ty & (EXPR | STMT) != 0 => {
                    let func_old = node.children[0].expect("Expected function for function call");
                    let func = self.visit_expr(func_old);

                    let args: Vec<CExprId> = node
                        .children
                        .iter()
                        .skip(1)
                        .map(|id| {
                            let arg_id = id.expect("Expected call expression argument");
                            self.visit_expr(arg_id)
                        })
                        .collect();

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let call = CExprKind::Call(ty, func, args);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, call);
                }

                ASTEntryTag::TagMemberExpr if expected_ty & (EXPR | STMT) != 0 => {
                    let base_old = node.children[0].expect("Expected base for member expression");
                    let base = self.visit_expr(base_old);

                    let field_old = node.children[1].expect("Expected field for member expression");
                    let field = self.visit_decl(field_old);

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let member_kind = if node.extras[0].as_boolean().expect("is arrow") {
                        MemberKind::Arrow
                    } else {
                        MemberKind::Dot
                    };

                    let member = CExprKind::Member(ty, base, field, member_kind, node.rvalue);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, member);
                }

                ASTEntryTag::TagBinaryOperator if expected_ty & (EXPR | STMT) != 0 => {
                    let operator = match node.extras[0]
                        .as_string()
                        .expect("Expected operator")
                        .as_str()
                    {
                        "*" => BinOp::Multiply,
                        "/" => BinOp::Divide,
                        "%" => BinOp::Modulus,
                        "+" => BinOp::Add,
                        "-" => BinOp::Subtract,
                        "<<" => BinOp::ShiftLeft,
                        ">>" => BinOp::ShiftRight,
                        "<" => BinOp::Less,
                        ">" => BinOp::Greater,
                        "<=" => BinOp::LessEqual,
                        ">=" => BinOp::GreaterEqual,
                        "==" => BinOp::EqualEqual,
                        "!=" => BinOp::NotEqual,
                        "&" => BinOp::BitAnd,
                        "^" => BinOp::BitXor,
                        "|" => BinOp::BitOr,
                        "&&" => BinOp::And,
                        "||" => BinOp::Or,
                        "+=" => BinOp::AssignAdd,
                        "-=" => BinOp::AssignSubtract,
                        "*=" => BinOp::AssignMultiply,
                        "/=" => BinOp::AssignDivide,
                        "%=" => BinOp::AssignModulus,
                        "^=" => BinOp::AssignBitXor,
                        "<<=" => BinOp::AssignShiftLeft,
                        ">>=" => BinOp::AssignShiftRight,
                        "|=" => BinOp::AssignBitOr,
                        "&=" => BinOp::AssignBitAnd,
                        "=" => BinOp::Assign,
                        "," => BinOp::Comma,
                        _ => unimplemented!(),
                    };

                    let left_operand_old = node.children[0].expect("Expected left operand");
                    let left_operand = self.visit_expr(left_operand_old);

                    let right_operand_old = node.children[1].expect("Expected right operand");
                    let right_operand = self.visit_expr(right_operand_old);

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let opt_lhs_type_id =
                        expect_opt_u64(&node.extras[1]).expect("Expected compute lhs type");
                    let opt_lhs_type = opt_lhs_type_id.map(|x| self.visit_qualified_type(x));

                    let opt_res_type_id =
                        expect_opt_u64(&node.extras[2]).expect("Expected compute lhs type");
                    let opt_res_type = opt_res_type_id.map(|x| self.visit_qualified_type(x));

                    let binary = CExprKind::Binary(
                        ty,
                        operator,
                        left_operand,
                        right_operand,
                        opt_lhs_type,
                        opt_res_type,
                    );

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, binary);
                }

                ASTEntryTag::TagDeclRefExpr if expected_ty & (EXPR | STMT) != 0 => {
                    let declaration_old =
                        node.children[0].expect("Expected declaration on expression tag decl");
                    let declaration = self.visit_decl(declaration_old);

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let decl = CExprKind::DeclRef(ty, declaration, node.rvalue);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, decl);
                }

                ASTEntryTag::TagArraySubscriptExpr if expected_ty & (EXPR | STMT) != 0 => {
                    let lhs_old =
                        node.children[0].expect("Expected LHS on array subscript expression");
                    let lhs = self.visit_expr(lhs_old);

                    let rhs_old =
                        node.children[1].expect("Expected RHS on array subscript expression");
                    let rhs = self.visit_expr(rhs_old);

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let subscript = CExprKind::ArraySubscript(ty, lhs, rhs, node.rvalue);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, subscript);
                }

                ASTEntryTag::TagConditionalOperator if expected_ty & (EXPR | STMT) != 0 => {
                    let cond_old = node.children[0].expect("Expected condition on if expression");
                    let cond = self.visit_expr(cond_old);

                    let lhs_old = node.children[1].expect("Expected 'then' on if expression");
                    let lhs = self.visit_expr(lhs_old);

                    let rhs_old = node.children[2].expect("Expected 'else' on if expression");
                    let rhs = self.visit_expr(rhs_old);

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let conditional = CExprKind::Conditional(ty, cond, lhs, rhs);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, conditional);
                }

                ASTEntryTag::TagBinaryConditionalOperator if expected_ty & (EXPR | STMT) != 0 => {
                    let lhs_old = node.children[0].expect("Expected condition on if expression");
                    let lhs = self.visit_expr(lhs_old);

                    let rhs_old = node.children[1].expect("Expected 'else' on if expression");
                    let rhs = self.visit_expr(rhs_old);

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let conditional = CExprKind::BinaryConditional(ty, lhs, rhs);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, conditional);
                }

                ASTEntryTag::TagUnaryExprOrTypeTraitExpr if expected_ty & (EXPR | STMT) != 0 => {
                    let ty = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty);

                    let expr = node.children[0].map(|x| self.visit_expr(x));

                    let kind_name = node.extras[0].as_string().expect("expected kind").as_str();
                    let kind = match kind_name {
                        "sizeof" => UnTypeOp::SizeOf,
                        "alignof" => UnTypeOp::AlignOf,
                        "preferredalignof" => UnTypeOp::PreferredAlignOf,
                        str => panic!("Unsupported operation: {}", str),
                    };

                    let arg_ty = node.extras[1].as_u64().expect("expected type id");
                    let arg_ty = self.visit_qualified_type(arg_ty);

                    let operator = CExprKind::UnaryType(ty, kind, expr, arg_ty);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, operator);
                }

                ASTEntryTag::TagCompoundLiteralExpr => {
                    let ty_old = node
                        .type_id
                        .expect("Expected compound literal to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let val_old = node.children[0].expect("Expected child on compound literal");
                    let val = self.visit_expr(val_old);

                    self.expr_possibly_as_stmt(
                        expected_ty,
                        new_id,
                        node,
                        CExprKind::CompoundLiteral(ty, val),
                    )
                }

                ASTEntryTag::TagPredefinedExpr => {
                    let ty_old = node.type_id.expect("Expected predefined expr to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let val_old = node.children[0].expect("Expected child on predefined expr");
                    let val = self.visit_expr(val_old);

                    self.expr_possibly_as_stmt(
                        expected_ty,
                        new_id,
                        node,
                        CExprKind::Predefined(ty, val),
                    )
                }

                ASTEntryTag::TagImplicitValueInitExpr => {
                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    self.expr_possibly_as_stmt(
                        expected_ty,
                        new_id,
                        node,
                        CExprKind::ImplicitValueInit(ty),
                    )
                }

                ASTEntryTag::TagInitListExpr => {
                    let exprs: Vec<CExprId> = node
                        .children
                        .iter()
                        .map(|id| {
                            let expr_id = id.expect("init expression id");
                            self.visit_expr(expr_id)
                        })
                        .collect();

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let union_field_id = expect_opt_u64(&node.extras[0])
                        .expect("Bad union field ID entry")
                        .map(|x| self.visit_decl(x));
                    let syntax_id = expect_opt_u64(&node.extras[1])
                        .expect("Bad syntax ID entry")
                        .map(|x| self.visit_expr(x));

                    let kind = CExprKind::InitList(ty, exprs, union_field_id, syntax_id);
                    self.expr_possibly_as_stmt(expected_ty, new_id, node, kind)
                }

                ASTEntryTag::TagDesignatedInitExpr => {
                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let designator_cbors = node.extras[0]
                        .as_array()
                        .expect("Expected designators array");
                    let designators = designator_cbors
                        .into_iter()
                        .map(|x| {
                            let entry = x.as_array().expect("expected designator array");
                            match entry[0].as_u64().expect("expected designator tag") {
                                1 => Designator::Index(
                                    entry[1].as_u64().expect("expected array index"),
                                ),
                                2 => Designator::Field(CDeclId(
                                    entry[1].as_u64().expect("expected field id"),
                                )),
                                3 => Designator::Range(
                                    entry[1].as_u64().expect("expected array start"),
                                    entry[2].as_u64().expect("expected array end"),
                                ),
                                n => panic!("invalid designator tag: {}", n),
                            }
                        })
                        .collect();

                    let init_id = node.children[0]
                        .expect("Expected initializer expression on designated init expr");
                    let init_expr = self.visit_expr(init_id);

                    let kind = CExprKind::DesignatedInitExpr(ty, designators, init_expr);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, kind)
                }

                ASTEntryTag::TagStmtExpr => {
                    let child_id = node.children[0].expect("Expected compound statement ID");
                    let child = self.visit_stmt(child_id);

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let stmt_expr = CExprKind::Statements(ty, child);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, stmt_expr)
                }

                ASTEntryTag::TagVAArgExpr => {
                    let child_id = node.children[0].expect("Expected subexpression");
                    let child = self.visit_expr(child_id);

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let vaarg_expr = CExprKind::VAArg(ty, child);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, vaarg_expr)
                }

                ASTEntryTag::TagShuffleVectorExpr => {
                    let kids: Vec<CExprId> = node
                        .children
                        .iter()
                        .map(|id| {
                            let child_id = id.expect("Missing shuffle argument");
                            self.visit_expr(child_id)
                        })
                        .collect();

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let e = CExprKind::ShuffleVector(ty, kids);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, e)
                }

                ASTEntryTag::TagConvertVectorExpr => {
                    let kids: Vec<CExprId> = node
                        .children
                        .iter()
                        .map(|id| {
                            let child_id = id.expect("Missing convert argument");
                            self.visit_expr(child_id)
                        })
                        .collect();

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let e = CExprKind::ConvertVector(ty, kids);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, e)
                }

                ASTEntryTag::TagConstantExpr => {
                    let kids: Vec<CExprId> = node
                        .children
                        .iter()
                        .map(|id| {
                            let child_id = id.expect("Missing constant subexpr");
                            self.visit_expr(child_id)
                        })
                        .collect();

                    let ty_old = node.type_id.expect("Expected expression to have type");
                    let ty = self.visit_qualified_type(ty_old);

                    let e = CExprKind::ConvertVector(ty, kids);

                    self.expr_possibly_as_stmt(expected_ty, new_id, node, e)
                }

                // Declarations
                ASTEntryTag::TagFunctionDecl if expected_ty & OTHER_DECL != 0 => {
                    let name = node.extras[0]
                        .as_string()
                        .expect("Expected to find function name")
                        .to_owned();

                    let is_global = node.extras[1]
                        .as_boolean()
                        .expect("Expected to find visibility");
                    let mut is_inline = node.extras[2]
                        .as_boolean()
                        .expect("Expected to find inline");

                    let is_main = node.extras[3].as_boolean().expect("Expected to find main");
                    if is_main {
                        self.typed_context.c_main = Some(CDeclId(new_id));
                    }

                    let is_implicit = node.extras[4]
                        .as_boolean()
                        .expect("Expected to find implicit");
                    let is_extern = node.extras[5]
                        .as_boolean()
                        .expect("Expected to find externness");
                    let attributes = node.extras[6]
                        .as_array()
                        .expect("Expected to find attributes");
                    let attrs = parse_attributes(attributes);

                    // The always_inline attribute implies inline even if the
                    // inline keyword is not present.
                    is_inline |= attrs.contains(&Attribute::AlwaysInline);

                    let typ_old = node
                        .type_id
                        .expect("Expected to find a type on a function decl");
                    let typ = CTypeId(self.visit_node_type(typ_old, TYPE));

                    let (body_id, parameter_ids) = node
                        .children
                        .split_last()
                        .expect("Expected to find a function body");

                    let body = body_id.map(|b| self.visit_stmt(b));

                    let parameters = parameter_ids
                        .iter()
                        .map(|id| {
                            let param = id.expect("Param field decl not found");
                            CDeclId(self.visit_node_type(param, VAR_DECL))
                        })
                        .collect();

                    let function_decl = CDeclKind::Function {
                        attrs,
                        body,
                        is_extern,
                        is_global,
                        is_implicit,
                        is_inline,
                        name,
                        parameters,
                        typ,
                    };

                    self.add_decl(new_id, located(node, function_decl));
                    self.processed_nodes.insert(new_id, OTHER_DECL);
                }

                ASTEntryTag::TagTypedefDecl if expected_ty & TYPDEF_DECL != 0 => {
                    let name = node.extras[0]
                        .as_string()
                        .expect("Expected to find typedef name")
                        .to_owned();
                    let is_implicit = node.extras[1]
                        .as_boolean()
                        .expect("Expected to find implicit");

                    let typ_old = node
                        .type_id
                        .expect("Expected to find type on typedef declaration");
                    let typ = self.visit_qualified_type(typ_old);

                    let typdef_decl = CDeclKind::Typedef {
                        name,
                        typ,
                        is_implicit,
                    };

                    self.add_decl(new_id, located(node, typdef_decl));
                    self.processed_nodes.insert(new_id, TYPDEF_DECL);
                }

                ASTEntryTag::TagEnumDecl if expected_ty & ENUM_DECL != 0 => {
                    let name = expect_opt_str(&node.extras[0]).unwrap().map(str::to_string);

                    let variants = node
                        .children
                        .iter()
                        .map(|id| {
                            let con = id.expect("Enum constant not found");
                            let id = CDeclId(self.visit_node_type(con, ENUM_CON));
                            self.typed_context.parents.insert(id, CDeclId(new_id));
                            id
                        })
                        .collect();

                    let integral_type = node.type_id.map(|x| self.visit_qualified_type(x));

                    let enum_decl = CDeclKind::Enum {
                        name,
                        variants,
                        integral_type,
                    };

                    self.add_decl(new_id, located(node, enum_decl));
                    self.processed_nodes.insert(new_id, ENUM_DECL);
                }

                ASTEntryTag::TagEnumConstantDecl if expected_ty & ENUM_CON != 0 => {
                    let name = node.extras[0]
                        .as_string()
                        .expect("Expected to find enum constant name")
                        .to_owned();
                    let value = match node.extras[1] {
                        Value::U64(n) => ConstIntExpr::U(n),
                        Value::I64(n) => ConstIntExpr::I(n),
                        _ => panic!("Expected constant int expr"),
                    };

                    let enum_constant_decl = CDeclKind::EnumConstant { name, value };

                    self.add_decl(new_id, located(node, enum_constant_decl));
                    self.processed_nodes.insert(new_id, ENUM_CON);
                }

                ASTEntryTag::TagVarDecl if expected_ty & VAR_DECL != 0 => {
                    let ident = node.extras[0]
                        .as_string()
                        .expect("Expected to find variable name")
                        .to_owned();

                    let has_static_duration = node.extras[1]
                        .as_boolean()
                        .expect("Expected to find static duration");
                    let has_thread_duration = node.extras[2]
                        .as_boolean()
                        .expect("Expected to find thread duration");
                    let is_externally_visible = node.extras[3]
                        .as_boolean()
                        .expect("Expected to find visibility");
                    let is_defn = node.extras[4]
                        .as_boolean()
                        .expect("Expected to find whether decl is definition");
                    let attributes = node.extras[5]
                        .as_array()
                        .expect("Expected attribute array on var decl");

                    assert!(has_static_duration || has_thread_duration || !is_externally_visible,
                            format!("Variable cannot be extern without also being static or thread-local: {}", ident));

                    let initializer = node.children[0].map(|id| self.visit_expr(id));

                    let typ_id = node
                        .type_id
                        .expect("Expected to find type on variable declaration");
                    let typ = self.visit_qualified_type(typ_id);

                    let mut attrs = parse_attributes(attributes);

                    let variable_decl = CDeclKind::Variable {
                        has_static_duration,
                        has_thread_duration,
                        is_externally_visible,
                        is_defn,
                        ident,
                        initializer,
                        typ,
                        attrs,
                    };

                    self.add_decl(new_id, located(node, variable_decl));
                    self.processed_nodes.insert(new_id, VAR_DECL);
                }

                ASTEntryTag::TagStructDecl if expected_ty & RECORD_DECL != 0 => {
                    let name = expect_opt_str(&node.extras[0]).unwrap().map(str::to_string);
                    let has_def = node.extras[1]
                        .as_boolean()
                        .expect("Expected has_def flag on struct");
                    let attrs = node.extras[2]
                        .as_array()
                        .expect("Expected attribute array on record");
                    let manual_alignment =
                        expect_opt_u64(&node.extras[3]).expect("Expected struct alignment");
                    let max_field_alignment =
                        expect_opt_u64(&node.extras[4]).expect("Expected struct field align");
                    let platform_byte_size = node.extras[5].as_u64().expect("Expected struct size");
                    let platform_alignment =
                        node.extras[6].as_u64().expect("Expected struct alignment");

                    let fields: Option<Vec<CDeclId>> = if has_def {
                        Some(
                            node.children
                                .iter()
                                .map(|id| {
                                    let field = id.expect("Record field decl not found");
                                    let id = CDeclId(self.visit_node_type(field, FIELD_DECL));
                                    self.typed_context.parents.insert(id, CDeclId(new_id));
                                    id
                                })
                                .collect(),
                        )
                    } else {
                        None
                    };

                    let mut is_packed = false;
                    for attr in attrs {
                        match attr
                            .as_string()
                            .expect("Records attributes should be strings")
                            .as_str()
                        {
                            "packed" => is_packed = true,
                            _ => {}
                        }
                    }

                    let record = CDeclKind::Struct {
                        name,
                        fields,
                        is_packed,
                        manual_alignment,
                        max_field_alignment,
                        platform_byte_size,
                        platform_alignment,
                    };

                    self.add_decl(new_id, located(node, record));
                    self.processed_nodes.insert(new_id, RECORD_DECL);
                }

                ASTEntryTag::TagUnionDecl if expected_ty & RECORD_DECL != 0 => {
                    let name = expect_opt_str(&node.extras[0]).unwrap().map(str::to_string);
                    let has_def = node.extras[1]
                        .as_boolean()
                        .expect("Expected has_def flag on struct");
                    let fields: Option<Vec<CDeclId>> = if has_def {
                        Some(
                            node.children
                                .iter()
                                .map(|id| {
                                    let field = id.expect("Record field decl not found");
                                    let id = CDeclId(self.visit_node_type(field, FIELD_DECL));
                                    self.typed_context.parents.insert(id, CDeclId(new_id));
                                    id
                                })
                                .collect(),
                        )
                    } else {
                        None
                    };

                    let record = CDeclKind::Union { name, fields };

                    self.add_decl(new_id, located(node, record));
                    self.processed_nodes.insert(new_id, RECORD_DECL);
                }

                ASTEntryTag::TagFieldDecl if expected_ty & FIELD_DECL != 0 => {
                    let name = node.extras[0]
                        .as_string()
                        .expect("A field needs a name")
                        .to_owned();
                    let typ_id = node
                        .type_id
                        .expect("Expected to find type on field declaration");
                    let typ = self.visit_qualified_type(typ_id);
                    let bitfield_width = node.extras[1].as_u64();
                    let platform_bit_offset = node.extras[2]
                        .as_u64()
                        .expect("Did not find field bit offset");
                    let platform_type_bitwidth = node.extras[3]
                        .as_u64()
                        .expect("Did not find field bitwidth");
                    let field = CDeclKind::Field {
                        name,
                        typ,
                        bitfield_width,
                        platform_bit_offset,
                        platform_type_bitwidth,
                    };
                    self.add_decl(new_id, located(node, field));
                    self.processed_nodes.insert(new_id, FIELD_DECL);
                }

                t => panic!("Could not translate node {:?} as type {}", t, expected_ty),
            }
        }
    }
}