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

#include "clang/Config/config.h"
#include "clang-c/Index.h"
#include "clang-c/CXCompilationDatabase.h"
#include "clang-c/BuildSystem.h"
#include "clang-c/Documentation.h"
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>

#ifdef CLANG_HAVE_LIBXML
#include <libxml/parser.h>
#include <libxml/relaxng.h>
#include <libxml/xmlerror.h>
#endif

#ifdef _WIN32
#  include <direct.h>
#else
#  include <unistd.h>
#endif

extern int indextest_core_main(int argc, const char **argv);

/******************************************************************************/
/* Utility functions.                                                         */
/******************************************************************************/

#ifdef _MSC_VER
char *basename(const char* path)
{
    char* base1 = (char*)strrchr(path, '/');
    char* base2 = (char*)strrchr(path, '\\');
    if (base1 && base2)
        return((base1 > base2) ? base1 + 1 : base2 + 1);
    else if (base1)
        return(base1 + 1);
    else if (base2)
        return(base2 + 1);

    return((char*)path);
}
char *dirname(char* path)
{
    char* base1 = (char*)strrchr(path, '/');
    char* base2 = (char*)strrchr(path, '\\');
    if (base1 && base2)
        if (base1 > base2)
          *base1 = 0;
        else
          *base2 = 0;
    else if (base1)
        *base1 = 0;
    else if (base2)
        *base2 = 0;

    return path;
}
#else
extern char *basename(const char *);
extern char *dirname(char *);
#endif

/** Return the default parsing options. */
static unsigned getDefaultParsingOptions() {
  unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;

  if (getenv("CINDEXTEST_EDITING"))
    options |= clang_defaultEditingTranslationUnitOptions();
  if (getenv("CINDEXTEST_COMPLETION_CACHING"))
    options |= CXTranslationUnit_CacheCompletionResults;
  if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
    options &= ~CXTranslationUnit_CacheCompletionResults;
  if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
    options |= CXTranslationUnit_SkipFunctionBodies;
  if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
    options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
  if (getenv("CINDEXTEST_CREATE_PREAMBLE_ON_FIRST_PARSE"))
    options |= CXTranslationUnit_CreatePreambleOnFirstParse;
  if (getenv("CINDEXTEST_KEEP_GOING"))
    options |= CXTranslationUnit_KeepGoing;
  if (getenv("CINDEXTEST_LIMIT_SKIP_FUNCTION_BODIES_TO_PREAMBLE"))
    options |= CXTranslationUnit_LimitSkipFunctionBodiesToPreamble;
  if (getenv("CINDEXTEST_INCLUDE_ATTRIBUTED_TYPES"))
    options |= CXTranslationUnit_IncludeAttributedTypes;
  if (getenv("CINDEXTEST_VISIT_IMPLICIT_ATTRIBUTES"))
    options |= CXTranslationUnit_VisitImplicitAttributes;
  if (getenv("CINDEXTEST_IGNORE_NONERRORS_FROM_INCLUDED_FILES"))
    options |= CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles;

  return options;
}

static void ModifyPrintingPolicyAccordingToEnv(CXPrintingPolicy Policy) {
  struct Mapping {
    const char *name;
    enum CXPrintingPolicyProperty property;
  };
  struct Mapping mappings[] = {
      {"CINDEXTEST_PRINTINGPOLICY_INDENTATION", CXPrintingPolicy_Indentation},
      {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSSPECIFIERS",
       CXPrintingPolicy_SuppressSpecifiers},
      {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSTAGKEYWORD",
       CXPrintingPolicy_SuppressTagKeyword},
      {"CINDEXTEST_PRINTINGPOLICY_INCLUDETAGDEFINITION",
       CXPrintingPolicy_IncludeTagDefinition},
      {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSSCOPE",
       CXPrintingPolicy_SuppressScope},
      {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSUNWRITTENSCOPE",
       CXPrintingPolicy_SuppressUnwrittenScope},
      {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSINITIALIZERS",
       CXPrintingPolicy_SuppressInitializers},
      {"CINDEXTEST_PRINTINGPOLICY_CONSTANTARRAYSIZEASWRITTEN",
       CXPrintingPolicy_ConstantArraySizeAsWritten},
      {"CINDEXTEST_PRINTINGPOLICY_ANONYMOUSTAGLOCATIONS",
       CXPrintingPolicy_AnonymousTagLocations},
      {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSSTRONGLIFETIME",
       CXPrintingPolicy_SuppressStrongLifetime},
      {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSLIFETIMEQUALIFIERS",
       CXPrintingPolicy_SuppressLifetimeQualifiers},
      {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSTEMPLATEARGSINCXXCONSTRUCTORS",
       CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors},
      {"CINDEXTEST_PRINTINGPOLICY_BOOL", CXPrintingPolicy_Bool},
      {"CINDEXTEST_PRINTINGPOLICY_RESTRICT", CXPrintingPolicy_Restrict},
      {"CINDEXTEST_PRINTINGPOLICY_ALIGNOF", CXPrintingPolicy_Alignof},
      {"CINDEXTEST_PRINTINGPOLICY_UNDERSCOREALIGNOF",
       CXPrintingPolicy_UnderscoreAlignof},
      {"CINDEXTEST_PRINTINGPOLICY_USEVOIDFORZEROPARAMS",
       CXPrintingPolicy_UseVoidForZeroParams},
      {"CINDEXTEST_PRINTINGPOLICY_TERSEOUTPUT", CXPrintingPolicy_TerseOutput},
      {"CINDEXTEST_PRINTINGPOLICY_POLISHFORDECLARATION",
       CXPrintingPolicy_PolishForDeclaration},
      {"CINDEXTEST_PRINTINGPOLICY_HALF", CXPrintingPolicy_Half},
      {"CINDEXTEST_PRINTINGPOLICY_MSWCHAR", CXPrintingPolicy_MSWChar},
      {"CINDEXTEST_PRINTINGPOLICY_INCLUDENEWLINES",
       CXPrintingPolicy_IncludeNewlines},
      {"CINDEXTEST_PRINTINGPOLICY_MSVCFORMATTING",
       CXPrintingPolicy_MSVCFormatting},
      {"CINDEXTEST_PRINTINGPOLICY_CONSTANTSASWRITTEN",
       CXPrintingPolicy_ConstantsAsWritten},
      {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSIMPLICITBASE",
       CXPrintingPolicy_SuppressImplicitBase},
      {"CINDEXTEST_PRINTINGPOLICY_FULLYQUALIFIEDNAME",
       CXPrintingPolicy_FullyQualifiedName},
  };

  unsigned i;
  for (i = 0; i < sizeof(mappings) / sizeof(struct Mapping); i++) {
    char *value = getenv(mappings[i].name);
    if (value) {
      clang_PrintingPolicy_setProperty(Policy, mappings[i].property,
                                       (unsigned)strtoul(value, 0L, 10));
    }
  }
}

/** Returns 0 in case of success, non-zero in case of a failure. */
static int checkForErrors(CXTranslationUnit TU);

static void describeLibclangFailure(enum CXErrorCode Err) {
  switch (Err) {
  case CXError_Success:
    fprintf(stderr, "Success\n");
    return;

  case CXError_Failure:
    fprintf(stderr, "Failure (no details available)\n");
    return;

  case CXError_Crashed:
    fprintf(stderr, "Failure: libclang crashed\n");
    return;

  case CXError_InvalidArguments:
    fprintf(stderr, "Failure: invalid arguments passed to a libclang routine\n");
    return;

  case CXError_ASTReadError:
    fprintf(stderr, "Failure: AST deserialization error occurred\n");
    return;
  }
}

static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
                        unsigned end_line, unsigned end_column) {
  fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
          end_line, end_column);
}

static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
                                      CXTranslationUnit *TU) {
  enum CXErrorCode Err = clang_createTranslationUnit2(Idx, file, TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
    describeLibclangFailure(Err);
    *TU = 0;
    return 0;
  }
  return 1;
}

void free_remapped_files(struct CXUnsavedFile *unsaved_files,
                         int num_unsaved_files) {
  int i;
  for (i = 0; i != num_unsaved_files; ++i) {
    free((char *)unsaved_files[i].Filename);
    free((char *)unsaved_files[i].Contents);
  }
  free(unsaved_files);
}

static int parse_remapped_files_with_opt(const char *opt_name,
                                         int argc, const char **argv,
                                         int start_arg,
                                         struct CXUnsavedFile **unsaved_files,
                                         int *num_unsaved_files) {
  int i;
  int arg;
  int prefix_len = strlen(opt_name);
  int arg_indices[20];
  *unsaved_files = 0;
  *num_unsaved_files = 0;

  /* Count the number of remapped files. */
  for (arg = start_arg; arg < argc; ++arg) {
    if (strncmp(argv[arg], opt_name, prefix_len))
      continue;

    assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
    arg_indices[*num_unsaved_files] = arg;
    ++*num_unsaved_files;
  }

  if (*num_unsaved_files == 0)
    return 0;

  *unsaved_files
    = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
                                     *num_unsaved_files);
  assert(*unsaved_files);
  for (i = 0; i != *num_unsaved_files; ++i) {
    struct CXUnsavedFile *unsaved = *unsaved_files + i;
    const char *arg_string = argv[arg_indices[i]] + prefix_len;
    int filename_len;
    char *filename;
    char *contents;
    FILE *to_file;
    const char *sep = strchr(arg_string, ',');
    if (!sep) {
      fprintf(stderr,
              "error: %sfrom:to argument is missing comma\n", opt_name);
      free_remapped_files(*unsaved_files, i);
      *unsaved_files = 0;
      *num_unsaved_files = 0;
      return -1;
    }

    /* Open the file that we're remapping to. */
    to_file = fopen(sep + 1, "rb");
    if (!to_file) {
      fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
              sep + 1);
      free_remapped_files(*unsaved_files, i);
      *unsaved_files = 0;
      *num_unsaved_files = 0;
      return -1;
    }

    /* Determine the length of the file we're remapping to. */
    fseek(to_file, 0, SEEK_END);
    unsaved->Length = ftell(to_file);
    fseek(to_file, 0, SEEK_SET);

    /* Read the contents of the file we're remapping to. */
    contents = (char *)malloc(unsaved->Length + 1);
    assert(contents);
    if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
      fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
              (feof(to_file) ? "EOF" : "error"), sep + 1);
      fclose(to_file);
      free_remapped_files(*unsaved_files, i);
      free(contents);
      *unsaved_files = 0;
      *num_unsaved_files = 0;
      return -1;
    }
    contents[unsaved->Length] = 0;
    unsaved->Contents = contents;

    /* Close the file. */
    fclose(to_file);

    /* Copy the file name that we're remapping from. */
    filename_len = sep - arg_string;
    filename = (char *)malloc(filename_len + 1);
    assert(filename);
    memcpy(filename, arg_string, filename_len);
    filename[filename_len] = 0;
    unsaved->Filename = filename;
  }

  return 0;
}

static int parse_remapped_files(int argc, const char **argv, int start_arg,
                                struct CXUnsavedFile **unsaved_files,
                                int *num_unsaved_files) {
  return parse_remapped_files_with_opt("-remap-file=", argc, argv, start_arg,
      unsaved_files, num_unsaved_files);
}

static int parse_remapped_files_with_try(int try_idx,
                                         int argc, const char **argv,
                                         int start_arg,
                                         struct CXUnsavedFile **unsaved_files,
                                         int *num_unsaved_files) {
  struct CXUnsavedFile *unsaved_files_no_try_idx;
  int num_unsaved_files_no_try_idx;
  struct CXUnsavedFile *unsaved_files_try_idx;
  int num_unsaved_files_try_idx;
  int ret;
  char opt_name[32];

  ret = parse_remapped_files(argc, argv, start_arg,
      &unsaved_files_no_try_idx, &num_unsaved_files_no_try_idx);
  if (ret)
    return ret;

  sprintf(opt_name, "-remap-file-%d=", try_idx);
  ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
      &unsaved_files_try_idx, &num_unsaved_files_try_idx);
  if (ret)
    return ret;

  if (num_unsaved_files_no_try_idx == 0) {
    *unsaved_files = unsaved_files_try_idx;
    *num_unsaved_files = num_unsaved_files_try_idx;
    return 0;
  }
  if (num_unsaved_files_try_idx == 0) {
    *unsaved_files = unsaved_files_no_try_idx;
    *num_unsaved_files = num_unsaved_files_no_try_idx;
    return 0;
  }

  *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
  *unsaved_files
    = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
                                      sizeof(struct CXUnsavedFile) *
                                        *num_unsaved_files);
  assert(*unsaved_files);
  memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
         unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
            num_unsaved_files_try_idx);
  free(unsaved_files_try_idx);
  return 0;
}

static const char *parse_comments_schema(int argc, const char **argv) {
  const char *CommentsSchemaArg = "-comments-xml-schema=";
  const char *CommentSchemaFile = NULL;

  if (argc == 0)
    return CommentSchemaFile;

  if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
    CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);

  return CommentSchemaFile;
}

/******************************************************************************/
/* Pretty-printing.                                                           */
/******************************************************************************/

static const char *FileCheckPrefix = "CHECK";

static void PrintCString(const char *CStr) {
  if (CStr != NULL && CStr[0] != '\0') {
    for ( ; *CStr; ++CStr) {
      const char C = *CStr;
      switch (C) {
        case '\n': printf("\\n"); break;
        case '\r': printf("\\r"); break;
        case '\t': printf("\\t"); break;
        case '\v': printf("\\v"); break;
        case '\f': printf("\\f"); break;
        default:   putchar(C);    break;
      }
    }
  }
}

static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
  printf(" %s=[", Prefix);
  PrintCString(CStr);
  printf("]");
}

static void PrintCXStringAndDispose(CXString Str) {
  PrintCString(clang_getCString(Str));
  clang_disposeString(Str);
}

static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
  PrintCStringWithPrefix(Prefix, clang_getCString(Str));
}

static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
                                              CXString Str) {
  PrintCStringWithPrefix(Prefix, clang_getCString(Str));
  clang_disposeString(Str);
}

static void PrintRange(CXSourceRange R, const char *str) {
  CXFile begin_file, end_file;
  unsigned begin_line, begin_column, end_line, end_column;

  clang_getSpellingLocation(clang_getRangeStart(R),
                            &begin_file, &begin_line, &begin_column, 0);
  clang_getSpellingLocation(clang_getRangeEnd(R),
                            &end_file, &end_line, &end_column, 0);
  if (!begin_file || !end_file)
    return;

  if (str)
    printf(" %s=", str);
  PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
}

static enum DisplayType {
    DisplayType_Spelling,
    DisplayType_DisplayName,
    DisplayType_Pretty
} wanted_display_type = DisplayType_Spelling;

static void printVersion(const char *Prefix, CXVersion Version) {
  if (Version.Major < 0)
    return;
  printf("%s%d", Prefix, Version.Major);
  
  if (Version.Minor < 0)
    return;
  printf(".%d", Version.Minor);

  if (Version.Subminor < 0)
    return;
  printf(".%d", Version.Subminor);
}

struct CommentASTDumpingContext {
  int IndentLevel;
};

static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
                                  CXComment Comment) {
  unsigned i;
  unsigned e;
  enum CXCommentKind Kind = clang_Comment_getKind(Comment);

  Ctx->IndentLevel++;
  for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
    printf("  ");

  printf("(");
  switch (Kind) {
  case CXComment_Null:
    printf("CXComment_Null");
    break;
  case CXComment_Text:
    printf("CXComment_Text");
    PrintCXStringWithPrefixAndDispose("Text",
                                      clang_TextComment_getText(Comment));
    if (clang_Comment_isWhitespace(Comment))
      printf(" IsWhitespace");
    if (clang_InlineContentComment_hasTrailingNewline(Comment))
      printf(" HasTrailingNewline");
    break;
  case CXComment_InlineCommand:
    printf("CXComment_InlineCommand");
    PrintCXStringWithPrefixAndDispose(
        "CommandName",
        clang_InlineCommandComment_getCommandName(Comment));
    switch (clang_InlineCommandComment_getRenderKind(Comment)) {
    case CXCommentInlineCommandRenderKind_Normal:
      printf(" RenderNormal");
      break;
    case CXCommentInlineCommandRenderKind_Bold:
      printf(" RenderBold");
      break;
    case CXCommentInlineCommandRenderKind_Monospaced:
      printf(" RenderMonospaced");
      break;
    case CXCommentInlineCommandRenderKind_Emphasized:
      printf(" RenderEmphasized");
      break;
    }
    for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
         i != e; ++i) {
      printf(" Arg[%u]=", i);
      PrintCXStringAndDispose(
          clang_InlineCommandComment_getArgText(Comment, i));
    }
    if (clang_InlineContentComment_hasTrailingNewline(Comment))
      printf(" HasTrailingNewline");
    break;
  case CXComment_HTMLStartTag: {
    unsigned NumAttrs;
    printf("CXComment_HTMLStartTag");
    PrintCXStringWithPrefixAndDispose(
        "Name",
        clang_HTMLTagComment_getTagName(Comment));
    NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
    if (NumAttrs != 0) {
      printf(" Attrs:");
      for (i = 0; i != NumAttrs; ++i) {
        printf(" ");
        PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
        printf("=");
        PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
      }
    }
    if (clang_HTMLStartTagComment_isSelfClosing(Comment))
      printf(" SelfClosing");
    if (clang_InlineContentComment_hasTrailingNewline(Comment))
      printf(" HasTrailingNewline");
    break;
  }
  case CXComment_HTMLEndTag:
    printf("CXComment_HTMLEndTag");
    PrintCXStringWithPrefixAndDispose(
        "Name",
        clang_HTMLTagComment_getTagName(Comment));
    if (clang_InlineContentComment_hasTrailingNewline(Comment))
      printf(" HasTrailingNewline");
    break;
  case CXComment_Paragraph:
    printf("CXComment_Paragraph");
    if (clang_Comment_isWhitespace(Comment))
      printf(" IsWhitespace");
    break;
  case CXComment_BlockCommand:
    printf("CXComment_BlockCommand");
    PrintCXStringWithPrefixAndDispose(
        "CommandName",
        clang_BlockCommandComment_getCommandName(Comment));
    for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
         i != e; ++i) {
      printf(" Arg[%u]=", i);
      PrintCXStringAndDispose(
          clang_BlockCommandComment_getArgText(Comment, i));
    }
    break;
  case CXComment_ParamCommand:
    printf("CXComment_ParamCommand");
    switch (clang_ParamCommandComment_getDirection(Comment)) {
    case CXCommentParamPassDirection_In:
      printf(" in");
      break;
    case CXCommentParamPassDirection_Out:
      printf(" out");
      break;
    case CXCommentParamPassDirection_InOut:
      printf(" in,out");
      break;
    }
    if (clang_ParamCommandComment_isDirectionExplicit(Comment))
      printf(" explicitly");
    else
      printf(" implicitly");
    PrintCXStringWithPrefixAndDispose(
        "ParamName",
        clang_ParamCommandComment_getParamName(Comment));
    if (clang_ParamCommandComment_isParamIndexValid(Comment))
      printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
    else
      printf(" ParamIndex=Invalid");
    break;
  case CXComment_TParamCommand:
    printf("CXComment_TParamCommand");
    PrintCXStringWithPrefixAndDispose(
        "ParamName",
        clang_TParamCommandComment_getParamName(Comment));
    if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
      printf(" ParamPosition={");
      for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
           i != e; ++i) {
        printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
        if (i != e - 1)
          printf(", ");
      }
      printf("}");
    } else
      printf(" ParamPosition=Invalid");
    break;
  case CXComment_VerbatimBlockCommand:
    printf("CXComment_VerbatimBlockCommand");
    PrintCXStringWithPrefixAndDispose(
        "CommandName",
        clang_BlockCommandComment_getCommandName(Comment));
    break;
  case CXComment_VerbatimBlockLine:
    printf("CXComment_VerbatimBlockLine");
    PrintCXStringWithPrefixAndDispose(
        "Text",
        clang_VerbatimBlockLineComment_getText(Comment));
    break;
  case CXComment_VerbatimLine:
    printf("CXComment_VerbatimLine");
    PrintCXStringWithPrefixAndDispose(
        "Text",
        clang_VerbatimLineComment_getText(Comment));
    break;
  case CXComment_FullComment:
    printf("CXComment_FullComment");
    break;
  }
  if (Kind != CXComment_Null) {
    const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
    unsigned i;
    for (i = 0; i != NumChildren; ++i) {
      printf("\n// %s: ", FileCheckPrefix);
      DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
    }
  }
  printf(")");
  Ctx->IndentLevel--;
}

static void DumpCXComment(CXComment Comment) {
  struct CommentASTDumpingContext Ctx;
  Ctx.IndentLevel = 1;
  printf("\n// %s:  CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
  DumpCXCommentInternal(&Ctx, Comment);
  printf("]");
}

static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
#ifdef CLANG_HAVE_LIBXML
  xmlRelaxNGParserCtxtPtr RNGParser;
  xmlRelaxNGPtr Schema;
  xmlDocPtr Doc;
  xmlRelaxNGValidCtxtPtr ValidationCtxt;
  int status;

  if (!CommentSchemaFile)
    return;

  RNGParser = xmlRelaxNGNewParserCtxt(CommentSchemaFile);
  if (!RNGParser) {
    printf(" libXMLError");
    return;
  }
  Schema = xmlRelaxNGParse(RNGParser);

  Doc = xmlParseDoc((const xmlChar *) Str);

  if (!Doc) {
    xmlErrorPtr Error = xmlGetLastError();
    printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
    return;
  }

  ValidationCtxt = xmlRelaxNGNewValidCtxt(Schema);
  status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
  if (!status)
    printf(" CommentXMLValid");
  else if (status > 0) {
    xmlErrorPtr Error = xmlGetLastError();
    printf(" CommentXMLInvalid [not valid XML: %s]", Error->message);
  } else
    printf(" libXMLError");

  xmlRelaxNGFreeValidCtxt(ValidationCtxt);
  xmlFreeDoc(Doc);
  xmlRelaxNGFree(Schema);
  xmlRelaxNGFreeParserCtxt(RNGParser);
#endif
}

static void PrintCursorComments(CXCursor Cursor,
                                const char *CommentSchemaFile) {
  {
    CXString RawComment;
    const char *RawCommentCString;
    CXString BriefComment;
    const char *BriefCommentCString;

    RawComment = clang_Cursor_getRawCommentText(Cursor);
    RawCommentCString = clang_getCString(RawComment);
    if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
      PrintCStringWithPrefix("RawComment", RawCommentCString);
      PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");

      BriefComment = clang_Cursor_getBriefCommentText(Cursor);
      BriefCommentCString = clang_getCString(BriefComment);
      if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
        PrintCStringWithPrefix("BriefComment", BriefCommentCString);
      clang_disposeString(BriefComment);
    }
    clang_disposeString(RawComment);
  }

  {
    CXComment Comment = clang_Cursor_getParsedComment(Cursor);
    if (clang_Comment_getKind(Comment) != CXComment_Null) {
      PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
                                        clang_FullComment_getAsHTML(Comment));
      {
        CXString XML;
        XML = clang_FullComment_getAsXML(Comment);
        PrintCXStringWithPrefix("FullCommentAsXML", XML);
        ValidateCommentXML(clang_getCString(XML), CommentSchemaFile);
        clang_disposeString(XML);
      }

      DumpCXComment(Comment);
    }
  }
}

typedef struct {
  unsigned line;
  unsigned col;
} LineCol;

static int lineCol_cmp(const void *p1, const void *p2) {
  const LineCol *lhs = p1;
  const LineCol *rhs = p2;
  if (lhs->line != rhs->line)
    return (int)lhs->line - (int)rhs->line;
  return (int)lhs->col - (int)rhs->col;
}

static CXString CursorToText(CXCursor Cursor) {
  CXString text;
  switch (wanted_display_type) {
  case DisplayType_Spelling:
    return clang_getCursorSpelling(Cursor);
  case DisplayType_DisplayName:
    return clang_getCursorDisplayName(Cursor);
  case DisplayType_Pretty: {
    CXPrintingPolicy Policy = clang_getCursorPrintingPolicy(Cursor);
    ModifyPrintingPolicyAccordingToEnv(Policy);
    text = clang_getCursorPrettyPrinted(Cursor, Policy);
    clang_PrintingPolicy_dispose(Policy);
    return text;
  }
  }
  assert(0 && "unknown display type"); /* no llvm_unreachable in C. */
  /* Set to NULL to prevent uninitialized variable warnings. */
  text.data = NULL;
  text.private_flags = 0;
  return text;
}

static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
  CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
  if (clang_isInvalid(Cursor.kind)) {
    CXString ks = clang_getCursorKindSpelling(Cursor.kind);
    printf("Invalid Cursor => %s", clang_getCString(ks));
    clang_disposeString(ks);
  }
  else {
    CXString string, ks;
    CXCursor Referenced;
    unsigned line, column;
    CXCursor SpecializationOf;
    CXCursor *overridden;
    unsigned num_overridden;
    unsigned RefNameRangeNr;
    CXSourceRange CursorExtent;
    CXSourceRange RefNameRange;
    int AlwaysUnavailable;
    int AlwaysDeprecated;
    CXString UnavailableMessage;
    CXString DeprecatedMessage;
    CXPlatformAvailability PlatformAvailability[2];
    int NumPlatformAvailability;
    int I;

    ks = clang_getCursorKindSpelling(Cursor.kind);
    string = CursorToText(Cursor);
    printf("%s=%s", clang_getCString(ks),
                    clang_getCString(string));
    clang_disposeString(ks);
    clang_disposeString(string);

    Referenced = clang_getCursorReferenced(Cursor);
    if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
      if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
        unsigned I, N = clang_getNumOverloadedDecls(Referenced);
        printf("[");
        for (I = 0; I != N; ++I) {
          CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
          CXSourceLocation Loc;
          if (I)
            printf(", ");
          
          Loc = clang_getCursorLocation(Ovl);
          clang_getSpellingLocation(Loc, 0, &line, &column, 0);
          printf("%d:%d", line, column);          
        }
        printf("]");
      } else {
        CXSourceLocation Loc = clang_getCursorLocation(Referenced);
        clang_getSpellingLocation(Loc, 0, &line, &column, 0);
        printf(":%d:%d", line, column);
      }

      if (clang_getCursorKind(Referenced) == CXCursor_TypedefDecl) {
        CXType T = clang_getCursorType(Referenced);
        if (clang_Type_isTransparentTagTypedef(T)) {
          CXType Underlying = clang_getTypedefDeclUnderlyingType(Referenced);
          CXString S = clang_getTypeSpelling(Underlying);
          printf(" (Transparent: %s)", clang_getCString(S));
          clang_disposeString(S);
        }
      }
    }

    if (clang_isCursorDefinition(Cursor))
      printf(" (Definition)");
    
    switch (clang_getCursorAvailability(Cursor)) {
      case CXAvailability_Available:
        break;
        
      case CXAvailability_Deprecated:
        printf(" (deprecated)");
        break;
        
      case CXAvailability_NotAvailable:
        printf(" (unavailable)");
        break;

      case CXAvailability_NotAccessible:
        printf(" (inaccessible)");
        break;
    }
    
    NumPlatformAvailability
      = clang_getCursorPlatformAvailability(Cursor,
                                            &AlwaysDeprecated,
                                            &DeprecatedMessage,
                                            &AlwaysUnavailable,
                                            &UnavailableMessage,
                                            PlatformAvailability, 2);
    if (AlwaysUnavailable) {
      printf("  (always unavailable: \"%s\")",
             clang_getCString(UnavailableMessage));
    } else if (AlwaysDeprecated) {
      printf("  (always deprecated: \"%s\")",
             clang_getCString(DeprecatedMessage));
    } else {
      for (I = 0; I != NumPlatformAvailability; ++I) {
        if (I >= 2)
          break;
        
        printf("  (%s", clang_getCString(PlatformAvailability[I].Platform));
        if (PlatformAvailability[I].Unavailable)
          printf(", unavailable");
        else {
          printVersion(", introduced=", PlatformAvailability[I].Introduced);
          printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
          printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
        }
        if (clang_getCString(PlatformAvailability[I].Message)[0])
          printf(", message=\"%s\"",
                 clang_getCString(PlatformAvailability[I].Message));
        printf(")");
      }
    }
    for (I = 0; I != NumPlatformAvailability; ++I) {
      if (I >= 2)
        break;
      clang_disposeCXPlatformAvailability(PlatformAvailability + I);
    }
    
    clang_disposeString(DeprecatedMessage);
    clang_disposeString(UnavailableMessage);

    if (clang_CXXConstructor_isDefaultConstructor(Cursor))
      printf(" (default constructor)");

    if (clang_CXXConstructor_isMoveConstructor(Cursor))
      printf(" (move constructor)");
    if (clang_CXXConstructor_isCopyConstructor(Cursor))
      printf(" (copy constructor)");
    if (clang_CXXConstructor_isConvertingConstructor(Cursor))
      printf(" (converting constructor)");
    if (clang_CXXField_isMutable(Cursor))
      printf(" (mutable)");
    if (clang_CXXMethod_isDefaulted(Cursor))
      printf(" (defaulted)");
    if (clang_CXXMethod_isStatic(Cursor))
      printf(" (static)");
    if (clang_CXXMethod_isVirtual(Cursor))
      printf(" (virtual)");
    if (clang_CXXMethod_isConst(Cursor))
      printf(" (const)");
    if (clang_CXXMethod_isPureVirtual(Cursor))
      printf(" (pure)");
    if (clang_CXXRecord_isAbstract(Cursor))
      printf(" (abstract)");
    if (clang_EnumDecl_isScoped(Cursor))
      printf(" (scoped)");
    if (clang_Cursor_isVariadic(Cursor))
      printf(" (variadic)");
    if (clang_Cursor_isObjCOptional(Cursor))
      printf(" (@optional)");
    if (clang_isInvalidDeclaration(Cursor))
      printf(" (invalid)");

    switch (clang_getCursorExceptionSpecificationType(Cursor))
    {
      case CXCursor_ExceptionSpecificationKind_None:
        break;

      case CXCursor_ExceptionSpecificationKind_DynamicNone:
        printf(" (noexcept dynamic none)");
        break;

      case CXCursor_ExceptionSpecificationKind_Dynamic:
        printf(" (noexcept dynamic)");
        break;

      case CXCursor_ExceptionSpecificationKind_MSAny:
        printf(" (noexcept dynamic any)");
        break;

      case CXCursor_ExceptionSpecificationKind_BasicNoexcept:
        printf(" (noexcept)");
        break;

      case CXCursor_ExceptionSpecificationKind_ComputedNoexcept:
        printf(" (computed-noexcept)");
        break;

      case CXCursor_ExceptionSpecificationKind_Unevaluated:
      case CXCursor_ExceptionSpecificationKind_Uninstantiated:
      case CXCursor_ExceptionSpecificationKind_Unparsed:
        break;
    }

    {
      CXString language;
      CXString definedIn;
      unsigned generated;
      if (clang_Cursor_isExternalSymbol(Cursor, &language, &definedIn,
                                        &generated)) {
        printf(" (external lang: %s, defined: %s, gen: %d)",
            clang_getCString(language), clang_getCString(definedIn), generated);
        clang_disposeString(language);
        clang_disposeString(definedIn);
      }
    }

    if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
      CXType T =
        clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
      CXString S = clang_getTypeKindSpelling(T.kind);
      printf(" [IBOutletCollection=%s]", clang_getCString(S));
      clang_disposeString(S);
    }
    
    if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
      enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
      unsigned isVirtual = clang_isVirtualBase(Cursor);
      const char *accessStr = 0;

      switch (access) {
        case CX_CXXInvalidAccessSpecifier:
          accessStr = "invalid"; break;
        case CX_CXXPublic:
          accessStr = "public"; break;
        case CX_CXXProtected:
          accessStr = "protected"; break;
        case CX_CXXPrivate:
          accessStr = "private"; break;
      }      
      
      printf(" [access=%s isVirtual=%s]", accessStr,
             isVirtual ? "true" : "false");
    }

    SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
    if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
      CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
      CXString Name = clang_getCursorSpelling(SpecializationOf);
      clang_getSpellingLocation(Loc, 0, &line, &column, 0);
      printf(" [Specialization of %s:%d:%d]",
             clang_getCString(Name), line, column);
      clang_disposeString(Name);

      if (Cursor.kind == CXCursor_FunctionDecl) {
        /* Collect the template parameter kinds from the base template. */
        int NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
        int I;
        if (NumTemplateArgs < 0) {
          printf(" [no template arg info]");
        }
        for (I = 0; I < NumTemplateArgs; I++) {
          enum CXTemplateArgumentKind TAK =
              clang_Cursor_getTemplateArgumentKind(Cursor, I);
          switch(TAK) {
            case CXTemplateArgumentKind_Type:
              {
                CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
                CXString S = clang_getTypeSpelling(T);
                printf(" [Template arg %d: kind: %d, type: %s]",
                       I, TAK, clang_getCString(S));
                clang_disposeString(S);
              }
              break;
            case CXTemplateArgumentKind_Integral:
              printf(" [Template arg %d: kind: %d, intval: %lld]",
                     I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
              break;
            default:
              printf(" [Template arg %d: kind: %d]\n", I, TAK);
          }
        }
      }
    }

    clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
    if (num_overridden) {      
      unsigned I;
      LineCol lineCols[50];
      assert(num_overridden <= 50);
      printf(" [Overrides ");
      for (I = 0; I != num_overridden; ++I) {
        CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
        clang_getSpellingLocation(Loc, 0, &line, &column, 0);
        lineCols[I].line = line;
        lineCols[I].col = column;
      }
      /* Make the order of the override list deterministic. */
      qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
      for (I = 0; I != num_overridden; ++I) {
        if (I)
          printf(", ");
        printf("@%d:%d", lineCols[I].line, lineCols[I].col);
      }
      printf("]");
      clang_disposeOverriddenCursors(overridden);
    }
    
    if (Cursor.kind == CXCursor_InclusionDirective) {
      CXFile File = clang_getIncludedFile(Cursor);
      CXString Included = clang_getFileName(File);
      const char *IncludedString = clang_getCString(Included);
      printf(" (%s)", IncludedString ? IncludedString : "(null)");
      clang_disposeString(Included);
      
      if (clang_isFileMultipleIncludeGuarded(TU, File))
        printf("  [multi-include guarded]");
    }
    
    CursorExtent = clang_getCursorExtent(Cursor);
    RefNameRange = clang_getCursorReferenceNameRange(Cursor, 
                                                   CXNameRange_WantQualifier
                                                 | CXNameRange_WantSinglePiece
                                                 | CXNameRange_WantTemplateArgs,
                                                     0);
    if (!clang_equalRanges(CursorExtent, RefNameRange))
      PrintRange(RefNameRange, "SingleRefName");
    
    for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
      RefNameRange = clang_getCursorReferenceNameRange(Cursor, 
                                                   CXNameRange_WantQualifier
                                                 | CXNameRange_WantTemplateArgs,
                                                       RefNameRangeNr);
      if (clang_equalRanges(clang_getNullRange(), RefNameRange))
        break;
      if (!clang_equalRanges(CursorExtent, RefNameRange))
        PrintRange(RefNameRange, "RefName");
    }

    PrintCursorComments(Cursor, CommentSchemaFile);

    {
      unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
      if (PropAttrs != CXObjCPropertyAttr_noattr) {
        printf(" [");
        #define PRINT_PROP_ATTR(A) \
          if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
        PRINT_PROP_ATTR(readonly);
        PRINT_PROP_ATTR(getter);
        PRINT_PROP_ATTR(assign);
        PRINT_PROP_ATTR(readwrite);
        PRINT_PROP_ATTR(retain);
        PRINT_PROP_ATTR(copy);
        PRINT_PROP_ATTR(nonatomic);
        PRINT_PROP_ATTR(setter);
        PRINT_PROP_ATTR(atomic);
        PRINT_PROP_ATTR(weak);
        PRINT_PROP_ATTR(strong);
        PRINT_PROP_ATTR(unsafe_unretained);
        PRINT_PROP_ATTR(class);
        printf("]");
      }
    }

    if (Cursor.kind == CXCursor_ObjCPropertyDecl) {
      CXString Name = clang_Cursor_getObjCPropertyGetterName(Cursor);
      CXString Spelling = clang_getCursorSpelling(Cursor);
      const char *CName = clang_getCString(Name);
      const char *CSpelling = clang_getCString(Spelling);
      if (CName && strcmp(CName, CSpelling)) {
        printf(" (getter=%s)", CName);
      }
      clang_disposeString(Spelling);
      clang_disposeString(Name);
    }

    if (Cursor.kind == CXCursor_ObjCPropertyDecl) {
      CXString Name = clang_Cursor_getObjCPropertySetterName(Cursor);
      CXString Spelling = clang_getCursorSpelling(Cursor);
      const char *CName = clang_getCString(Name);
      const char *CSpelling = clang_getCString(Spelling);
      char *DefaultSetter = malloc(strlen(CSpelling) + 5);
      sprintf(DefaultSetter, "set%s:", CSpelling);
      DefaultSetter[3] &= ~(1 << 5); /* Make uppercase */
      if (CName && strcmp(CName, DefaultSetter)) {
        printf(" (setter=%s)", CName);
      }
      free(DefaultSetter);
      clang_disposeString(Spelling);
      clang_disposeString(Name);
    }

    {
      unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
      if (QT != CXObjCDeclQualifier_None) {
        printf(" [");
        #define PRINT_OBJC_QUAL(A) \
          if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
        PRINT_OBJC_QUAL(In);
        PRINT_OBJC_QUAL(Inout);
        PRINT_OBJC_QUAL(Out);
        PRINT_OBJC_QUAL(Bycopy);
        PRINT_OBJC_QUAL(Byref);
        PRINT_OBJC_QUAL(Oneway);
        printf("]");
      }
    }
  }
}

static const char* GetCursorSource(CXCursor Cursor) {
  CXSourceLocation Loc = clang_getCursorLocation(Cursor);
  CXString source;
  CXFile file;
  clang_getExpansionLocation(Loc, &file, 0, 0, 0);
  source = clang_getFileName(file);
  if (!clang_getCString(source)) {
    clang_disposeString(source);
    return "<invalid loc>";
  }
  else {
    const char *b = basename(clang_getCString(source));
    clang_disposeString(source);
    return b;
  }
}

static CXString createCXString(const char *CS) {
  CXString Str;
  Str.data = (const void *) CS;
  Str.private_flags = 0;
  return Str;
}

/******************************************************************************/
/* Callbacks.                                                                 */
/******************************************************************************/

typedef void (*PostVisitTU)(CXTranslationUnit);

void PrintDiagnostic(CXDiagnostic Diagnostic) {
  FILE *out = stderr;
  CXFile file;
  CXString Msg;
  unsigned display_opts = CXDiagnostic_DisplaySourceLocation
    | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
    | CXDiagnostic_DisplayOption;
  unsigned i, num_fixits;

  if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
    return;

  Msg = clang_formatDiagnostic(Diagnostic, display_opts);
  fprintf(stderr, "%s\n", clang_getCString(Msg));
  clang_disposeString(Msg);

  clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
                            &file, 0, 0, 0);
  if (!file)
    return;

  num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
  fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
  for (i = 0; i != num_fixits; ++i) {
    CXSourceRange range;
    CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
    CXSourceLocation start = clang_getRangeStart(range);
    CXSourceLocation end = clang_getRangeEnd(range);
    unsigned start_line, start_column, end_line, end_column;
    CXFile start_file, end_file;
    clang_getSpellingLocation(start, &start_file, &start_line,
                              &start_column, 0);
    clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
    if (clang_equalLocations(start, end)) {
      /* Insertion. */
      if (start_file == file)
        fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
                clang_getCString(insertion_text), start_line, start_column);
    } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
      /* Removal. */
      if (start_file == file && end_file == file) {
        fprintf(out, "FIX-IT: Remove ");
        PrintExtent(out, start_line, start_column, end_line, end_column);
        fprintf(out, "\n");
      }
    } else {
      /* Replacement. */
      if (start_file == end_file) {
        fprintf(out, "FIX-IT: Replace ");
        PrintExtent(out, start_line, start_column, end_line, end_column);
        fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
      }
    }
    clang_disposeString(insertion_text);
  }
}

void PrintDiagnosticSet(CXDiagnosticSet Set) {
  int i = 0, n = clang_getNumDiagnosticsInSet(Set);
  for ( ; i != n ; ++i) {
    CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
    CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
    PrintDiagnostic(Diag);
    if (ChildDiags)
      PrintDiagnosticSet(ChildDiags);
  }  
}

void PrintDiagnostics(CXTranslationUnit TU) {
  CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
  PrintDiagnosticSet(TUSet);
  clang_disposeDiagnosticSet(TUSet);
}

void PrintMemoryUsage(CXTranslationUnit TU) {
  unsigned long total = 0;
  unsigned i = 0;
  CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
  fprintf(stderr, "Memory usage:\n");
  for (i = 0 ; i != usage.numEntries; ++i) {
    const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
    unsigned long amount = usage.entries[i].amount;
    total += amount;
    fprintf(stderr, "  %s : %ld bytes (%f MBytes)\n", name, amount,
            ((double) amount)/(1024*1024));
  }
  fprintf(stderr, "  TOTAL = %ld bytes (%f MBytes)\n", total,
          ((double) total)/(1024*1024));
  clang_disposeCXTUResourceUsage(usage);  
}

/******************************************************************************/
/* Logic for testing traversal.                                               */
/******************************************************************************/

static void PrintCursorExtent(CXCursor C) {
  CXSourceRange extent = clang_getCursorExtent(C);
  PrintRange(extent, "Extent");
}

/* Data used by the visitors. */
typedef struct {
  CXTranslationUnit TU;
  enum CXCursorKind *Filter;
  const char *CommentSchemaFile;
} VisitorData;


enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
                                                CXCursor Parent,
                                                CXClientData ClientData) {
  VisitorData *Data = (VisitorData *)ClientData;
  if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
    CXSourceLocation Loc = clang_getCursorLocation(Cursor);
    unsigned line, column;
    clang_getSpellingLocation(Loc, 0, &line, &column, 0);
    printf("// %s: %s:%d:%d: ", FileCheckPrefix,
           GetCursorSource(Cursor), line, column);
    PrintCursor(Cursor, Data->CommentSchemaFile);
    PrintCursorExtent(Cursor);
    if (clang_isDeclaration(Cursor.kind)) {
      enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
      const char *accessStr = 0;

      switch (access) {
        case CX_CXXInvalidAccessSpecifier: break;
        case CX_CXXPublic:
          accessStr = "public"; break;
        case CX_CXXProtected:
          accessStr = "protected"; break;
        case CX_CXXPrivate:
          accessStr = "private"; break;
      }

      if (accessStr)
        printf(" [access=%s]", accessStr);
    }
    printf("\n");
    return CXChildVisit_Recurse;
  }

  return CXChildVisit_Continue;
}

static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
                                                   CXCursor Parent,
                                                   CXClientData ClientData) {
  const char *startBuf, *endBuf;
  unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
  CXCursor Ref;
  VisitorData *Data = (VisitorData *)ClientData;

  if (Cursor.kind != CXCursor_FunctionDecl ||
      !clang_isCursorDefinition(Cursor))
    return CXChildVisit_Continue;

  clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
                                       &startLine, &startColumn,
                                       &endLine, &endColumn);
  /* Probe the entire body, looking for both decls and refs. */
  curLine = startLine;
  curColumn = startColumn;

  while (startBuf < endBuf) {
    CXSourceLocation Loc;
    CXFile file;
    CXString source;

    if (*startBuf == '\n') {
      startBuf++;
      curLine++;
      curColumn = 1;
    } else if (*startBuf != '\t')
      curColumn++;

    Loc = clang_getCursorLocation(Cursor);
    clang_getSpellingLocation(Loc, &file, 0, 0, 0);

    source = clang_getFileName(file);
    if (clang_getCString(source)) {
      CXSourceLocation RefLoc
        = clang_getLocation(Data->TU, file, curLine, curColumn);
      Ref = clang_getCursor(Data->TU, RefLoc);
      if (Ref.kind == CXCursor_NoDeclFound) {
        /* Nothing found here; that's fine. */
      } else if (Ref.kind != CXCursor_FunctionDecl) {
        printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
               curLine, curColumn);
        PrintCursor(Ref, Data->CommentSchemaFile);
        printf("\n");
      }
    }
    clang_disposeString(source);
    startBuf++;
  }

  return CXChildVisit_Continue;
}

/******************************************************************************/
/* USR testing.                                                               */
/******************************************************************************/

enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
                                   CXClientData ClientData) {
  VisitorData *Data = (VisitorData *)ClientData;
  if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
    CXString USR = clang_getCursorUSR(C);
    const char *cstr = clang_getCString(USR);
    if (!cstr || cstr[0] == '\0') {
      clang_disposeString(USR);
      return CXChildVisit_Recurse;
    }
    printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);

    PrintCursorExtent(C);
    printf("\n");
    clang_disposeString(USR);

    return CXChildVisit_Recurse;
  }

  return CXChildVisit_Continue;
}

/******************************************************************************/
/* Inclusion stack testing.                                                   */
/******************************************************************************/

void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
                      unsigned includeStackLen, CXClientData data) {

  unsigned i;
  CXString fname;

  fname = clang_getFileName(includedFile);
  printf("file: %s\nincluded by:\n", clang_getCString(fname));
  clang_disposeString(fname);

  for (i = 0; i < includeStackLen; ++i) {
    CXFile includingFile;
    unsigned line, column;
    clang_getSpellingLocation(includeStack[i], &includingFile, &line,
                              &column, 0);
    fname = clang_getFileName(includingFile);
    printf("  %s:%d:%d\n", clang_getCString(fname), line, column);
    clang_disposeString(fname);
  }
  printf("\n");
}

void PrintInclusionStack(CXTranslationUnit TU) {
  clang_getInclusions(TU, InclusionVisitor, NULL);
}

/******************************************************************************/
/* Linkage testing.                                                           */
/******************************************************************************/

static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
                                            CXClientData d) {
  const char *linkage = 0;

  if (clang_isInvalid(clang_getCursorKind(cursor)))
    return CXChildVisit_Recurse;

  switch (clang_getCursorLinkage(cursor)) {
    case CXLinkage_Invalid: break;
    case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
    case CXLinkage_Internal: linkage = "Internal"; break;
    case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
    case CXLinkage_External: linkage = "External"; break;
  }

  if (linkage) {
    PrintCursor(cursor, NULL);
    printf("linkage=%s\n", linkage);
  }

  return CXChildVisit_Recurse;
}

/******************************************************************************/
/* Visibility testing.                                                        */
/******************************************************************************/

static enum CXChildVisitResult PrintVisibility(CXCursor cursor, CXCursor p,
                                               CXClientData d) {
  const char *visibility = 0;

  if (clang_isInvalid(clang_getCursorKind(cursor)))
    return CXChildVisit_Recurse;

  switch (clang_getCursorVisibility(cursor)) {
    case CXVisibility_Invalid: break;
    case CXVisibility_Hidden: visibility = "Hidden"; break;
    case CXVisibility_Protected: visibility = "Protected"; break;
    case CXVisibility_Default: visibility = "Default"; break;
  }

  if (visibility) {
    PrintCursor(cursor, NULL);
    printf("visibility=%s\n", visibility);
  }

  return CXChildVisit_Recurse;
}

/******************************************************************************/
/* Typekind testing.                                                          */
/******************************************************************************/

static void PrintTypeAndTypeKind(CXType T, const char *Format) {
  CXString TypeSpelling, TypeKindSpelling;

  TypeSpelling = clang_getTypeSpelling(T);
  TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
  printf(Format,
         clang_getCString(TypeSpelling),
         clang_getCString(TypeKindSpelling));
  clang_disposeString(TypeSpelling);
  clang_disposeString(TypeKindSpelling);
}

static enum CXVisitorResult FieldVisitor(CXCursor C,
                                         CXClientData client_data) {
    (*(int *) client_data)+=1;
    return CXVisit_Continue;
}

static void PrintTypeTemplateArgs(CXType T, const char *Format) {
  int NumTArgs = clang_Type_getNumTemplateArguments(T);
  if (NumTArgs != -1 && NumTArgs != 0) {
    int i;
    CXType TArg;
    printf(Format, NumTArgs);
    for (i = 0; i < NumTArgs; ++i) {
      TArg = clang_Type_getTemplateArgumentAsType(T, i);
      if (TArg.kind != CXType_Invalid) {
        PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
      }
    }
    /* Ensure that the returned type is invalid when indexing off-by-one. */
    TArg = clang_Type_getTemplateArgumentAsType(T, i);
    assert(TArg.kind == CXType_Invalid);
    printf("]");
  }
}

static void PrintNullabilityKind(CXType T, const char *Format) {
  enum CXTypeNullabilityKind N = clang_Type_getNullability(T);

  const char *nullability = 0;
  switch (N) {
    case CXTypeNullability_NonNull: nullability = "nonnull"; break;
    case CXTypeNullability_Nullable: nullability = "nullable"; break;
    case CXTypeNullability_Unspecified: nullability = "unspecified"; break;
    case CXTypeNullability_Invalid: break;
  }

  if (nullability) {
    printf(Format, nullability);
  }
}

static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
                                         CXClientData d) {
  if (!clang_isInvalid(clang_getCursorKind(cursor))) {
    CXType T = clang_getCursorType(cursor);
    CXType PT = clang_getPointeeType(T);
    enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
    PrintCursor(cursor, NULL);
    PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
    PrintNullabilityKind(T, " [nullability=%s]");
    if (clang_isConstQualifiedType(T))
      printf(" const");
    if (clang_isVolatileQualifiedType(T))
      printf(" volatile");
    if (clang_isRestrictQualifiedType(T))
      printf(" restrict");
    if (RQ == CXRefQualifier_LValue)
      printf(" lvalue-ref-qualifier");
    if (RQ == CXRefQualifier_RValue)
      printf(" rvalue-ref-qualifier");
    /* Print the template argument types if they exist. */
    PrintTypeTemplateArgs(T, " [templateargs/%d=");
    /* Print the canonical type if it is different. */
    {
      CXType CT = clang_getCanonicalType(T);
      if (!clang_equalTypes(T, CT)) {
        PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
        PrintTypeTemplateArgs(CT, " [canonicaltemplateargs/%d=");
      }
    }
    /* Print the modified type if it exists. */
    {
      CXType MT = clang_Type_getModifiedType(T);
      if (MT.kind != CXType_Invalid) {
        PrintTypeAndTypeKind(MT, " [modifiedtype=%s] [modifiedtypekind=%s]");
      }
    }
    /* Print the return type if it exists. */
    {
      CXType RT = clang_getCursorResultType(cursor);
      if (RT.kind != CXType_Invalid) {
        PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
      }
      PrintNullabilityKind(RT, " [resultnullability=%s]");
    }
    /* Print the argument types if they exist. */
    {
      int NumArgs = clang_Cursor_getNumArguments(cursor);
      if (NumArgs != -1 && NumArgs != 0) {
        int i;
        printf(" [args=");
        for (i = 0; i < NumArgs; ++i) {
          CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
          if (T.kind != CXType_Invalid) {
            PrintTypeAndTypeKind(T, " [%s] [%s]");
            PrintNullabilityKind(T, " [%s]");
          }
        }
        printf("]");
      }
    }
    /* Print ObjC base types, type arguments, and protocol list if available. */
    {
      CXType BT = clang_Type_getObjCObjectBaseType(PT);
      if (BT.kind != CXType_Invalid) {
        PrintTypeAndTypeKind(BT, " [basetype=%s] [basekind=%s]");
      }
    }
    {
      unsigned NumTypeArgs = clang_Type_getNumObjCTypeArgs(PT);
      if (NumTypeArgs > 0) {
        unsigned i;
        printf(" [typeargs=");
        for (i = 0; i < NumTypeArgs; ++i) {
          CXType TA = clang_Type_getObjCTypeArg(PT, i);
          if (TA.kind != CXType_Invalid) {
            PrintTypeAndTypeKind(TA, " [%s] [%s]");
          }
        }
        printf("]");
      }
    }
    {
      unsigned NumProtocols = clang_Type_getNumObjCProtocolRefs(PT);
      if (NumProtocols > 0) {
        unsigned i;
        printf(" [protocols=");
        for (i = 0; i < NumProtocols; ++i) {
          CXCursor P = clang_Type_getObjCProtocolDecl(PT, i);
          if (!clang_isInvalid(clang_getCursorKind(P))) {
            PrintCursor(P, NULL);
          }
        }
        printf("]");
      }
    }
    /* Print if this is a non-POD type. */
    printf(" [isPOD=%d]", clang_isPODType(T));
    /* Print the pointee type. */
    {
      if (PT.kind != CXType_Invalid) {
        PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
      }
    }
    /* Print the number of fields if they exist. */
    {
      int numFields = 0;
      if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
        if (numFields != 0) {
          printf(" [nbFields=%d]", numFields);
        }
      }
    }

    /* Print if it is an anonymous record or namespace. */
    {
      unsigned isAnon = clang_Cursor_isAnonymous(cursor);
      if (isAnon != 0) {
        printf(" [isAnon=%d]", isAnon);
      }
    }

    /* Print if it is an anonymous record decl */
    {
      unsigned isAnonRecDecl = clang_Cursor_isAnonymousRecordDecl(cursor);
      printf(" [isAnonRecDecl=%d]", isAnonRecDecl);
    }

    /* Print if it is an inline namespace decl */
    {
      unsigned isInlineNamespace = clang_Cursor_isInlineNamespace(cursor);
      if (isInlineNamespace != 0)
        printf(" [isInlineNamespace=%d]", isInlineNamespace);
    }

    printf("\n");
  }
  return CXChildVisit_Recurse;
}

static void PrintSingleTypeSize(CXType T, const char *TypeKindFormat,
                                const char *SizeFormat,
                                const char *AlignFormat) {
  PrintTypeAndTypeKind(T, TypeKindFormat);
  /* Print the type sizeof if applicable. */
  {
    long long Size = clang_Type_getSizeOf(T);
    if (Size >= 0 || Size < -1 ) {
      printf(SizeFormat, Size);
    }
  }
  /* Print the type alignof if applicable. */
  {
    long long Align = clang_Type_getAlignOf(T);
    if (Align >= 0 || Align < -1) {
      printf(AlignFormat, Align);
    }
  }

  /* Print the return type if it exists. */
  {
    CXType RT = clang_getResultType(T);
    if (RT.kind != CXType_Invalid)
      PrintSingleTypeSize(RT, " [resulttype=%s] [resulttypekind=%s]",
                              " [resultsizeof=%lld]", " [resultalignof=%lld]");
  }
}

static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
                                             CXClientData d) {
  CXType T;
  enum CXCursorKind K = clang_getCursorKind(cursor);
  if (clang_isInvalid(K))
    return CXChildVisit_Recurse;
  T = clang_getCursorType(cursor);
  PrintCursor(cursor, NULL);
  PrintSingleTypeSize(T, " [type=%s] [typekind=%s]", " [sizeof=%lld]",
                      " [alignof=%lld]");
  /* Print the record field offset if applicable. */
  {
    CXString FieldSpelling = clang_getCursorSpelling(cursor);
    const char *FieldName = clang_getCString(FieldSpelling);
    /* recurse to get the first parent record that is not anonymous. */
    unsigned RecordIsAnonymous = 0;
    if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
      CXCursor Record;
      CXCursor Parent = p;
      do {
        Record = Parent;
        Parent = clang_getCursorSemanticParent(Record);
        RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
        /* Recurse as long as the parent is a CXType_Record and the Record
           is anonymous */
      } while ( clang_getCursorType(Parent).kind == CXType_Record &&
                RecordIsAnonymous > 0);
      {
        long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
                                                  FieldName);
        long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
        if (Offset == Offset2){
            printf(" [offsetof=%lld]", Offset);
        } else {
            /* Offsets will be different in anonymous records. */
            printf(" [offsetof=%lld/%lld]", Offset, Offset2);
        }
      }
    }
    clang_disposeString(FieldSpelling);
  }
  /* Print if its a bitfield */
  {
    int IsBitfield = clang_Cursor_isBitField(cursor);
    if (IsBitfield)
      printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
  }

  printf("\n");

  return CXChildVisit_Recurse;
}

/******************************************************************************/
/* Mangling testing.                                                          */
/******************************************************************************/

static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
                                                CXClientData d) {
  CXString MangledName;
  if (clang_isUnexposed(clang_getCursorKind(cursor)))
    return CXChildVisit_Recurse;
  PrintCursor(cursor, NULL);
  MangledName = clang_Cursor_getMangling(cursor);
  printf(" [mangled=%s]\n", clang_getCString(MangledName));
  clang_disposeString(MangledName);
  return CXChildVisit_Continue;
}

static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
                                              CXClientData d) {
  unsigned I, E;
  CXStringSet *Manglings = NULL;
  if (clang_isUnexposed(clang_getCursorKind(cursor)))
    return CXChildVisit_Recurse;
  if (!clang_isDeclaration(clang_getCursorKind(cursor)))
    return CXChildVisit_Recurse;
  if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
    return CXChildVisit_Continue;
  PrintCursor(cursor, NULL);
  Manglings = clang_Cursor_getCXXManglings(cursor);
  if (Manglings) {
    for (I = 0, E = Manglings->Count; I < E; ++I)
      printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
    clang_disposeStringSet(Manglings);
    printf("\n");
  }
  Manglings = clang_Cursor_getObjCManglings(cursor);
  if (Manglings) {
    for (I = 0, E = Manglings->Count; I < E; ++I)
      printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
    clang_disposeStringSet(Manglings);
    printf("\n");
  }
  return CXChildVisit_Recurse;
}

/******************************************************************************/
/* Bitwidth testing.                                                          */
/******************************************************************************/

static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
                                             CXClientData d) {
  int Bitwidth;
  if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
    return CXChildVisit_Recurse;

  Bitwidth = clang_getFieldDeclBitWidth(cursor);
  if (Bitwidth >= 0) {
    PrintCursor(cursor, NULL);
    printf(" bitwidth=%d\n", Bitwidth);
  }

  return CXChildVisit_Recurse;
}

/******************************************************************************/
/* Type declaration testing                                                   */
/******************************************************************************/

static enum CXChildVisitResult PrintTypeDeclaration(CXCursor cursor, CXCursor p,
                                             CXClientData d) {
  CXCursor typeDeclaration = clang_getTypeDeclaration(clang_getCursorType(cursor));

  if (clang_isDeclaration(typeDeclaration.kind)) {
    PrintCursor(cursor, NULL);
    PrintTypeAndTypeKind(clang_getCursorType(typeDeclaration), " [typedeclaration=%s] [typekind=%s]\n");
  }

  return CXChildVisit_Recurse;
}

/******************************************************************************/
/* Declaration attributes testing                                             */
/******************************************************************************/

static enum CXChildVisitResult PrintDeclAttributes(CXCursor cursor, CXCursor p,
                                                   CXClientData d) {
  if (clang_isDeclaration(cursor.kind)) {
    printf("\n");
    PrintCursor(cursor, NULL);
    return CXChildVisit_Recurse;
  } else if (clang_isAttribute(cursor.kind)) {
    printf(" ");
    PrintCursor(cursor, NULL);
  }
  return CXChildVisit_Continue;
}

/******************************************************************************/
/* Target information testing.                                                */
/******************************************************************************/

static int print_target_info(int argc, const char **argv) {
  CXIndex Idx;
  CXTranslationUnit TU;
  CXTargetInfo TargetInfo;
  CXString Triple;
  const char *FileName;
  enum CXErrorCode Err;
  int PointerWidth;

  if (argc == 0) {
    fprintf(stderr, "No filename specified\n");
    return 1;
  }

  FileName = argv[1];

  Idx = clang_createIndex(0, 1);
  Err = clang_parseTranslationUnit2(Idx, FileName, argv, argc, NULL, 0,
                                    getDefaultParsingOptions(), &TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "Couldn't parse translation unit!\n");
    describeLibclangFailure(Err);
    clang_disposeIndex(Idx);
    return 1;
  }

  TargetInfo = clang_getTranslationUnitTargetInfo(TU);

  Triple = clang_TargetInfo_getTriple(TargetInfo);
  printf("TargetTriple: %s\n", clang_getCString(Triple));
  clang_disposeString(Triple);

  PointerWidth = clang_TargetInfo_getPointerWidth(TargetInfo);
  printf("PointerWidth: %d\n", PointerWidth);

  clang_TargetInfo_dispose(TargetInfo);
  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(Idx);
  return 0;
}

/******************************************************************************/
/* Loading ASTs/source.                                                       */
/******************************************************************************/

static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
                             const char *filter, const char *prefix,
                             CXCursorVisitor Visitor,
                             PostVisitTU PV,
                             const char *CommentSchemaFile) {

  if (prefix)
    FileCheckPrefix = prefix;

  if (Visitor) {
    enum CXCursorKind K = CXCursor_NotImplemented;
    enum CXCursorKind *ck = &K;
    VisitorData Data;

    /* Perform some simple filtering. */
    if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
    else if (!strcmp(filter, "all-display") || 
             !strcmp(filter, "local-display")) {
      ck = NULL;
      wanted_display_type = DisplayType_DisplayName;
    }
    else if (!strcmp(filter, "all-pretty") ||
             !strcmp(filter, "local-pretty")) {
      ck = NULL;
      wanted_display_type = DisplayType_Pretty;
    }
    else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
    else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
    else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
    else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
    else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
    else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
    else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
    else {
      fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
      return 1;
    }

    Data.TU = TU;
    Data.Filter = ck;
    Data.CommentSchemaFile = CommentSchemaFile;
    clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
  }

  if (PV)
    PV(TU);

  PrintDiagnostics(TU);
  if (checkForErrors(TU) != 0) {
    clang_disposeTranslationUnit(TU);
    return -1;
  }

  clang_disposeTranslationUnit(TU);
  return 0;
}

int perform_test_load_tu(const char *file, const char *filter,
                         const char *prefix, CXCursorVisitor Visitor,
                         PostVisitTU PV) {
  CXIndex Idx;
  CXTranslationUnit TU;
  int result;
  Idx = clang_createIndex(/* excludeDeclsFromPCH */
                          !strcmp(filter, "local") ? 1 : 0,
                          /* displayDiagnostics=*/1);

  if (!CreateTranslationUnit(Idx, file, &TU)) {
    clang_disposeIndex(Idx);
    return 1;
  }

  result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
  clang_disposeIndex(Idx);
  return result;
}

int perform_test_load_source(int argc, const char **argv,
                             const char *filter, CXCursorVisitor Visitor,
                             PostVisitTU PV) {
  CXIndex Idx;
  CXTranslationUnit TU;
  const char *CommentSchemaFile;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  enum CXErrorCode Err;
  int result;
  unsigned Repeats = 0;
  unsigned I;
  const char *InvocationPath;

  Idx = clang_createIndex(/* excludeDeclsFromPCH */
                          (!strcmp(filter, "local") ||
                           !strcmp(filter, "local-display") ||
                           !strcmp(filter, "local-pretty"))
                              ? 1
                              : 0,
                          /* displayDiagnostics=*/1);
  InvocationPath = getenv("CINDEXTEST_INVOCATION_EMISSION_PATH");
  if (InvocationPath)
    clang_CXIndex_setInvocationEmissionPathOption(Idx, InvocationPath);

  if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
    argc--;
    argv++;
  }

  if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
    clang_disposeIndex(Idx);
    return -1;
  }

  if (getenv("CINDEXTEST_EDITING"))
    Repeats = 5;

  Err = clang_parseTranslationUnit2(Idx, 0,
                                    argv + num_unsaved_files,
                                    argc - num_unsaved_files,
                                    unsaved_files, num_unsaved_files,
                                    getDefaultParsingOptions(), &TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "Unable to load translation unit!\n");
    describeLibclangFailure(Err);
    free_remapped_files(unsaved_files, num_unsaved_files);
    clang_disposeIndex(Idx);
    return 1;
  }

  for (I = 0; I != Repeats; ++I) {
    if (checkForErrors(TU) != 0)
      return -1;

    if (Repeats > 1) {
      clang_suspendTranslationUnit(TU);

      Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
                                         clang_defaultReparseOptions(TU));
      if (Err != CXError_Success) {
        describeLibclangFailure(Err);
        free_remapped_files(unsaved_files, num_unsaved_files);
        clang_disposeIndex(Idx);
        return 1;
      }
    }
  }

  result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
                             CommentSchemaFile);
  free_remapped_files(unsaved_files, num_unsaved_files);
  clang_disposeIndex(Idx);
  return result;
}

int perform_test_reparse_source(int argc, const char **argv, int trials,
                                const char *filter, CXCursorVisitor Visitor,
                                PostVisitTU PV) {
  CXIndex Idx;
  CXTranslationUnit TU;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  int compiler_arg_idx = 0;
  enum CXErrorCode Err;
  int result, i;
  int trial;
  int remap_after_trial = 0;
  char *endptr = 0;
  
  Idx = clang_createIndex(/* excludeDeclsFromPCH */
                          !strcmp(filter, "local") ? 1 : 0,
                          /* displayDiagnostics=*/1);
  
  if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
    clang_disposeIndex(Idx);
    return -1;
  }

  for (i = 0; i < argc; ++i) {
    if (strcmp(argv[i], "--") == 0)
      break;
  }
  if (i < argc)
    compiler_arg_idx = i+1;
  if (num_unsaved_files > compiler_arg_idx)
    compiler_arg_idx = num_unsaved_files;
  
  /* Load the initial translation unit -- we do this without honoring remapped
   * files, so that we have a way to test results after changing the source. */
  Err = clang_parseTranslationUnit2(Idx, 0,
                                    argv + compiler_arg_idx,
                                    argc - compiler_arg_idx,
                                    0, 0, getDefaultParsingOptions(), &TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "Unable to load translation unit!\n");
    describeLibclangFailure(Err);
    free_remapped_files(unsaved_files, num_unsaved_files);
    clang_disposeIndex(Idx);
    return 1;
  }
  
  if (checkForErrors(TU) != 0)
    return -1;

  if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
    remap_after_trial =
        strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
  }

  for (trial = 0; trial < trials; ++trial) {
    free_remapped_files(unsaved_files, num_unsaved_files);
    if (parse_remapped_files_with_try(trial, argc, argv, 0,
                                      &unsaved_files, &num_unsaved_files)) {
      clang_disposeTranslationUnit(TU);
      clang_disposeIndex(Idx);
      return -1;
    }

    Err = clang_reparseTranslationUnit(
        TU,
        trial >= remap_after_trial ? num_unsaved_files : 0,
        trial >= remap_after_trial ? unsaved_files : 0,
        clang_defaultReparseOptions(TU));
    if (Err != CXError_Success) {
      fprintf(stderr, "Unable to reparse translation unit!\n");
      describeLibclangFailure(Err);
      clang_disposeTranslationUnit(TU);
      free_remapped_files(unsaved_files, num_unsaved_files);
      clang_disposeIndex(Idx);
      return -1;      
    }

    if (checkForErrors(TU) != 0)
      return -1;
  }
  
  result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);

  free_remapped_files(unsaved_files, num_unsaved_files);
  clang_disposeIndex(Idx);
  return result;
}

static int perform_single_file_parse(const char *filename) {
  CXIndex Idx;
  CXTranslationUnit TU;
  enum CXErrorCode Err;
  int result;

  Idx = clang_createIndex(/* excludeDeclsFromPCH */1,
                          /* displayDiagnostics=*/1);

  Err = clang_parseTranslationUnit2(Idx, filename,
                                    /*command_line_args=*/NULL,
                                    /*num_command_line_args=*/0,
                                    /*unsaved_files=*/NULL,
                                    /*num_unsaved_files=*/0,
                                    CXTranslationUnit_SingleFileParse, &TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "Unable to load translation unit!\n");
    describeLibclangFailure(Err);
    clang_disposeIndex(Idx);
    return 1;
  }

  result = perform_test_load(Idx, TU, /*filter=*/"all", /*prefix=*/NULL, FilteredPrintingVisitor, /*PostVisit=*/NULL,
                             /*CommentSchemaFile=*/NULL);
  clang_disposeIndex(Idx);
  return result;
}

static int perform_file_retain_excluded_cb(const char *filename) {
  CXIndex Idx;
  CXTranslationUnit TU;
  enum CXErrorCode Err;
  int result;

  Idx = clang_createIndex(/* excludeDeclsFromPCH */1,
                          /* displayDiagnostics=*/1);

  Err = clang_parseTranslationUnit2(Idx, filename,
                                    /*command_line_args=*/NULL,
                                    /*num_command_line_args=*/0,
                                    /*unsaved_files=*/NULL,
                                    /*num_unsaved_files=*/0,
                                    CXTranslationUnit_RetainExcludedConditionalBlocks, &TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "Unable to load translation unit!\n");
    describeLibclangFailure(Err);
    clang_disposeIndex(Idx);
    return 1;
  }

  result = perform_test_load(Idx, TU, /*filter=*/"all", /*prefix=*/NULL, FilteredPrintingVisitor, /*PostVisit=*/NULL,
                             /*CommentSchemaFile=*/NULL);
  clang_disposeIndex(Idx);
  return result;
}

/******************************************************************************/
/* Logic for testing clang_getCursor().                                       */
/******************************************************************************/

static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
                                   unsigned start_line, unsigned start_col,
                                   unsigned end_line, unsigned end_col,
                                   const char *prefix) {
  printf("// %s: ", FileCheckPrefix);
  if (prefix)
    printf("-%s", prefix);
  PrintExtent(stdout, start_line, start_col, end_line, end_col);
  printf(" ");
  PrintCursor(cursor, NULL);
  printf("\n");
}

static int perform_file_scan(const char *ast_file, const char *source_file,
                             const char *prefix) {
  CXIndex Idx;
  CXTranslationUnit TU;
  FILE *fp;
  CXCursor prevCursor = clang_getNullCursor();
  CXFile file;
  unsigned line = 1, col = 1;
  unsigned start_line = 1, start_col = 1;

  if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
                                /* displayDiagnostics=*/1))) {
    fprintf(stderr, "Could not create Index\n");
    return 1;
  }

  if (!CreateTranslationUnit(Idx, ast_file, &TU))
    return 1;

  if ((fp = fopen(source_file, "r")) == NULL) {
    fprintf(stderr, "Could not open '%s'\n", source_file);
    clang_disposeTranslationUnit(TU);
    return 1;
  }

  file = clang_getFile(TU, source_file);
  for (;;) {
    CXCursor cursor;
    int c = fgetc(fp);

    if (c == '\n') {
      ++line;
      col = 1;
    } else
      ++col;

    /* Check the cursor at this position, and dump the previous one if we have
     * found something new.
     */
    cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
    if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
        prevCursor.kind != CXCursor_InvalidFile) {
      print_cursor_file_scan(TU, prevCursor, start_line, start_col,
                             line, col, prefix);
      start_line = line;
      start_col = col;
    }
    if (c == EOF)
      break;

    prevCursor = cursor;
  }

  fclose(fp);
  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(Idx);
  return 0;
}

/******************************************************************************/
/* Logic for testing clang code completion.                                   */
/******************************************************************************/

/* Parse file:line:column from the input string. Returns 0 on success, non-zero
   on failure. If successful, the pointer *filename will contain newly-allocated
   memory (that will be owned by the caller) to store the file name. */
int parse_file_line_column(const char *input, char **filename, unsigned *line,
                           unsigned *column, unsigned *second_line,
                           unsigned *second_column) {
  /* Find the second colon. */
  const char *last_colon = strrchr(input, ':');
  unsigned values[4], i;
  unsigned num_values = (second_line && second_column)? 4 : 2;

  char *endptr = 0;
  if (!last_colon || last_colon == input) {
    if (num_values == 4)
      fprintf(stderr, "could not parse filename:line:column:line:column in "
              "'%s'\n", input);
    else
      fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
    return 1;
  }

  for (i = 0; i != num_values; ++i) {
    const char *prev_colon;

    /* Parse the next line or column. */
    values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
    if (*endptr != 0 && *endptr != ':') {
      fprintf(stderr, "could not parse %s in '%s'\n",
              (i % 2 ? "column" : "line"), input);
      return 1;
    }

    if (i + 1 == num_values)
      break;

    /* Find the previous colon. */
    prev_colon = last_colon - 1;
    while (prev_colon != input && *prev_colon != ':')
      --prev_colon;
    if (prev_colon == input) {
      fprintf(stderr, "could not parse %s in '%s'\n",
              (i % 2 == 0? "column" : "line"), input);
      return 1;
    }

    last_colon = prev_colon;
  }

  *line = values[0];
  *column = values[1];

  if (second_line && second_column) {
    *second_line = values[2];
    *second_column = values[3];
  }

  /* Copy the file name. */
  *filename = (char*)malloc(last_colon - input + 1);
  assert(*filename);
  memcpy(*filename, input, last_colon - input);
  (*filename)[last_colon - input] = 0;
  return 0;
}

const char *
clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
  switch (Kind) {
  case CXCompletionChunk_Optional: return "Optional";
  case CXCompletionChunk_TypedText: return "TypedText";
  case CXCompletionChunk_Text: return "Text";
  case CXCompletionChunk_Placeholder: return "Placeholder";
  case CXCompletionChunk_Informative: return "Informative";
  case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
  case CXCompletionChunk_LeftParen: return "LeftParen";
  case CXCompletionChunk_RightParen: return "RightParen";
  case CXCompletionChunk_LeftBracket: return "LeftBracket";
  case CXCompletionChunk_RightBracket: return "RightBracket";
  case CXCompletionChunk_LeftBrace: return "LeftBrace";
  case CXCompletionChunk_RightBrace: return "RightBrace";
  case CXCompletionChunk_LeftAngle: return "LeftAngle";
  case CXCompletionChunk_RightAngle: return "RightAngle";
  case CXCompletionChunk_Comma: return "Comma";
  case CXCompletionChunk_ResultType: return "ResultType";
  case CXCompletionChunk_Colon: return "Colon";
  case CXCompletionChunk_SemiColon: return "SemiColon";
  case CXCompletionChunk_Equal: return "Equal";
  case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
  case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
  }

  return "Unknown";
}

static int checkForErrors(CXTranslationUnit TU) {
  unsigned Num, i;
  CXDiagnostic Diag;
  CXString DiagStr;

  if (!getenv("CINDEXTEST_FAILONERROR"))
    return 0;

  Num = clang_getNumDiagnostics(TU);
  for (i = 0; i != Num; ++i) {
    Diag = clang_getDiagnostic(TU, i);
    if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
      DiagStr = clang_formatDiagnostic(Diag,
                                       clang_defaultDiagnosticDisplayOptions());
      fprintf(stderr, "%s\n", clang_getCString(DiagStr));
      clang_disposeString(DiagStr);
      clang_disposeDiagnostic(Diag);
      return -1;
    }
    clang_disposeDiagnostic(Diag);
  }

  return 0;
}

static void print_completion_string(CXCompletionString completion_string,
                                    FILE *file) {
  int I, N;

  N = clang_getNumCompletionChunks(completion_string);
  for (I = 0; I != N; ++I) {
    CXString text;
    const char *cstr;
    enum CXCompletionChunkKind Kind
      = clang_getCompletionChunkKind(completion_string, I);

    if (Kind == CXCompletionChunk_Optional) {
      fprintf(file, "{Optional ");
      print_completion_string(
                clang_getCompletionChunkCompletionString(completion_string, I),
                              file);
      fprintf(file, "}");
      continue;
    } 

    if (Kind == CXCompletionChunk_VerticalSpace) {
      fprintf(file, "{VerticalSpace  }");
      continue;
    }

    text = clang_getCompletionChunkText(completion_string, I);
    cstr = clang_getCString(text);
    fprintf(file, "{%s %s}",
            clang_getCompletionChunkKindSpelling(Kind),
            cstr ? cstr : "");
    clang_disposeString(text);
  }

}

static void print_line_column(CXSourceLocation location, FILE *file) {
    unsigned line, column;
    clang_getExpansionLocation(location, NULL, &line, &column, NULL);
    fprintf(file, "%d:%d", line, column);
}

static void print_token_range(CXTranslationUnit translation_unit,
                              CXSourceLocation start, FILE *file) {
  CXToken *token = clang_getToken(translation_unit, start);

  fprintf(file, "{");
  if (token != NULL) {
    CXSourceRange token_range = clang_getTokenExtent(translation_unit, *token);
    print_line_column(clang_getRangeStart(token_range), file);
    fprintf(file, "-");
    print_line_column(clang_getRangeEnd(token_range), file);
    clang_disposeTokens(translation_unit, token, 1);
  }

  fprintf(file, "}");
}

static void print_completion_result(CXTranslationUnit translation_unit,
                                    CXCodeCompleteResults *completion_results,
                                    unsigned index,
                                    FILE *file) {
  CXCompletionResult *completion_result = completion_results->Results + index;
  CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
  unsigned annotationCount;
  enum CXCursorKind ParentKind;
  CXString ParentName;
  CXString BriefComment;
  CXString Annotation;
  const char *BriefCommentCString;
  unsigned i;
  
  fprintf(file, "%s:", clang_getCString(ks));
  clang_disposeString(ks);

  print_completion_string(completion_result->CompletionString, file);
  fprintf(file, " (%u)", 
          clang_getCompletionPriority(completion_result->CompletionString));
  switch (clang_getCompletionAvailability(completion_result->CompletionString)){
  case CXAvailability_Available:
    break;
    
  case CXAvailability_Deprecated:
    fprintf(file, " (deprecated)");
    break;
    
  case CXAvailability_NotAvailable:
    fprintf(file, " (unavailable)");
    break;

  case CXAvailability_NotAccessible:
    fprintf(file, " (inaccessible)");
    break;
  }

  annotationCount = clang_getCompletionNumAnnotations(
        completion_result->CompletionString);
  if (annotationCount) {
    unsigned i;
    fprintf(file, " (");
    for (i = 0; i < annotationCount; ++i) {
      if (i != 0)
        fprintf(file, ", ");
      Annotation =
          clang_getCompletionAnnotation(completion_result->CompletionString, i);
      fprintf(file, "\"%s\"", clang_getCString(Annotation));
      clang_disposeString(Annotation);
    }
    fprintf(file, ")");
  }

  if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
    ParentName = clang_getCompletionParent(completion_result->CompletionString,
                                           &ParentKind);
    if (ParentKind != CXCursor_NotImplemented) {
      CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
      fprintf(file, " (parent: %s '%s')",
              clang_getCString(KindSpelling),
              clang_getCString(ParentName));
      clang_disposeString(KindSpelling);
    }
    clang_disposeString(ParentName);
  }

  BriefComment = clang_getCompletionBriefComment(
                                        completion_result->CompletionString);
  BriefCommentCString = clang_getCString(BriefComment);
  if (BriefCommentCString && *BriefCommentCString != '\0') {
    fprintf(file, "(brief comment: %s)", BriefCommentCString);
  }
  clang_disposeString(BriefComment);

  for (i = 0; i < clang_getCompletionNumFixIts(completion_results, index);
       ++i) {
    CXSourceRange correction_range;
    CXString FixIt = clang_getCompletionFixIt(completion_results, index, i,
                                              &correction_range);
    fprintf(file, " (requires fix-it: ");
    print_token_range(translation_unit, clang_getRangeStart(correction_range),
                      file);
    fprintf(file, " to \"%s\")", clang_getCString(FixIt));
    clang_disposeString(FixIt);
  }

  fprintf(file, "\n");
}

void print_completion_contexts(unsigned long long contexts, FILE *file) {
  fprintf(file, "Completion contexts:\n");
  if (contexts == CXCompletionContext_Unknown) {
    fprintf(file, "Unknown\n");
  }
  if (contexts & CXCompletionContext_AnyType) {
    fprintf(file, "Any type\n");
  }
  if (contexts & CXCompletionContext_AnyValue) {
    fprintf(file, "Any value\n");
  }
  if (contexts & CXCompletionContext_ObjCObjectValue) {
    fprintf(file, "Objective-C object value\n");
  }
  if (contexts & CXCompletionContext_ObjCSelectorValue) {
    fprintf(file, "Objective-C selector value\n");
  }
  if (contexts & CXCompletionContext_CXXClassTypeValue) {
    fprintf(file, "C++ class type value\n");
  }
  if (contexts & CXCompletionContext_DotMemberAccess) {
    fprintf(file, "Dot member access\n");
  }
  if (contexts & CXCompletionContext_ArrowMemberAccess) {
    fprintf(file, "Arrow member access\n");
  }
  if (contexts & CXCompletionContext_ObjCPropertyAccess) {
    fprintf(file, "Objective-C property access\n");
  }
  if (contexts & CXCompletionContext_EnumTag) {
    fprintf(file, "Enum tag\n");
  }
  if (contexts & CXCompletionContext_UnionTag) {
    fprintf(file, "Union tag\n");
  }
  if (contexts & CXCompletionContext_StructTag) {
    fprintf(file, "Struct tag\n");
  }
  if (contexts & CXCompletionContext_ClassTag) {
    fprintf(file, "Class name\n");
  }
  if (contexts & CXCompletionContext_Namespace) {
    fprintf(file, "Namespace or namespace alias\n");
  }
  if (contexts & CXCompletionContext_NestedNameSpecifier) {
    fprintf(file, "Nested name specifier\n");
  }
  if (contexts & CXCompletionContext_ObjCInterface) {
    fprintf(file, "Objective-C interface\n");
  }
  if (contexts & CXCompletionContext_ObjCProtocol) {
    fprintf(file, "Objective-C protocol\n");
  }
  if (contexts & CXCompletionContext_ObjCCategory) {
    fprintf(file, "Objective-C category\n");
  }
  if (contexts & CXCompletionContext_ObjCInstanceMessage) {
    fprintf(file, "Objective-C instance method\n");
  }
  if (contexts & CXCompletionContext_ObjCClassMessage) {
    fprintf(file, "Objective-C class method\n");
  }
  if (contexts & CXCompletionContext_ObjCSelectorName) {
    fprintf(file, "Objective-C selector name\n");
  }
  if (contexts & CXCompletionContext_MacroName) {
    fprintf(file, "Macro name\n");
  }
  if (contexts & CXCompletionContext_NaturalLanguage) {
    fprintf(file, "Natural language\n");
  }
}

int perform_code_completion(int argc, const char **argv, int timing_only) {
  const char *input = argv[1];
  char *filename = 0;
  unsigned line;
  unsigned column;
  CXIndex CIdx;
  int errorCode;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  CXCodeCompleteResults *results = 0;
  enum CXErrorCode Err;
  CXTranslationUnit TU;
  unsigned I, Repeats = 1;
  unsigned completionOptions = clang_defaultCodeCompleteOptions();
  const char *InvocationPath;

  if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
    completionOptions |= CXCodeComplete_IncludeCodePatterns;
  if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
    completionOptions |= CXCodeComplete_IncludeBriefComments;
  if (getenv("CINDEXTEST_COMPLETION_SKIP_PREAMBLE"))
    completionOptions |= CXCodeComplete_SkipPreamble;
  if (getenv("CINDEXTEST_COMPLETION_INCLUDE_FIXITS"))
    completionOptions |= CXCodeComplete_IncludeCompletionsWithFixIts;
  
  if (timing_only)
    input += strlen("-code-completion-timing=");
  else
    input += strlen("-code-completion-at=");

  if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
                                          0, 0)))
    return errorCode;

  if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
    return -1;

  CIdx = clang_createIndex(0, 0);
  InvocationPath = getenv("CINDEXTEST_INVOCATION_EMISSION_PATH");
  if (InvocationPath)
    clang_CXIndex_setInvocationEmissionPathOption(CIdx, InvocationPath);

  if (getenv("CINDEXTEST_EDITING"))
    Repeats = 5;

  Err = clang_parseTranslationUnit2(CIdx, 0,
                                    argv + num_unsaved_files + 2,
                                    argc - num_unsaved_files - 2,
                                    0, 0, getDefaultParsingOptions(), &TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "Unable to load translation unit!\n");
    describeLibclangFailure(Err);
    return 1;
  }

  Err = clang_reparseTranslationUnit(TU, 0, 0,
                                     clang_defaultReparseOptions(TU));

  if (Err != CXError_Success) {
    fprintf(stderr, "Unable to reparse translation unit!\n");
    describeLibclangFailure(Err);
    clang_disposeTranslationUnit(TU);
    return 1;
  }

  for (I = 0; I != Repeats; ++I) {
    results = clang_codeCompleteAt(TU, filename, line, column,
                                   unsaved_files, num_unsaved_files,
                                   completionOptions);
    if (!results) {
      fprintf(stderr, "Unable to perform code completion!\n");
      return 1;
    }
    if (I != Repeats-1)
      clang_disposeCodeCompleteResults(results);
  }

  if (results) {
    unsigned i, n = results->NumResults, containerIsIncomplete = 0;
    unsigned long long contexts;
    enum CXCursorKind containerKind;
    CXString objCSelector;
    const char *selectorString;
    if (!timing_only) {      
      /* Sort the code-completion results based on the typed text. */
      clang_sortCodeCompletionResults(results->Results, results->NumResults);

      for (i = 0; i != n; ++i)
        print_completion_result(TU, results, i, stdout);
    }
    n = clang_codeCompleteGetNumDiagnostics(results);
    for (i = 0; i != n; ++i) {
      CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
      PrintDiagnostic(diag);
      clang_disposeDiagnostic(diag);
    }
    
    contexts = clang_codeCompleteGetContexts(results);
    print_completion_contexts(contexts, stdout);
    
    containerKind = clang_codeCompleteGetContainerKind(results,
                                                       &containerIsIncomplete);
    
    if (containerKind != CXCursor_InvalidCode) {
      /* We have found a container */
      CXString containerUSR, containerKindSpelling;
      containerKindSpelling = clang_getCursorKindSpelling(containerKind);
      printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
      clang_disposeString(containerKindSpelling);
      
      if (containerIsIncomplete) {
        printf("Container is incomplete\n");
      }
      else {
        printf("Container is complete\n");
      }
      
      containerUSR = clang_codeCompleteGetContainerUSR(results);
      printf("Container USR: %s\n", clang_getCString(containerUSR));
      clang_disposeString(containerUSR);
    }
    
    objCSelector = clang_codeCompleteGetObjCSelector(results);
    selectorString = clang_getCString(objCSelector);
    if (selectorString && strlen(selectorString) > 0) {
      printf("Objective-C selector: %s\n", selectorString);
    }
    clang_disposeString(objCSelector);
    
    clang_disposeCodeCompleteResults(results);
  }
  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(CIdx);
  free(filename);

  free_remapped_files(unsaved_files, num_unsaved_files);

  return 0;
}

typedef struct {
  char *filename;
  unsigned line;
  unsigned column;
} CursorSourceLocation;

typedef void (*cursor_handler_t)(CXCursor cursor);

static int inspect_cursor_at(int argc, const char **argv,
                             const char *locations_flag,
                             cursor_handler_t handler) {
  CXIndex CIdx;
  int errorCode;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  enum CXErrorCode Err;
  CXTranslationUnit TU;
  CXCursor Cursor;
  CursorSourceLocation *Locations = 0;
  unsigned NumLocations = 0, Loc;
  unsigned Repeats = 1;
  unsigned I;
  
  /* Count the number of locations. */
  while (strstr(argv[NumLocations+1], locations_flag) == argv[NumLocations+1])
    ++NumLocations;

  /* Parse the locations. */
  assert(NumLocations > 0 && "Unable to count locations?");
  Locations = (CursorSourceLocation *)malloc(
                                  NumLocations * sizeof(CursorSourceLocation));
  assert(Locations);
  for (Loc = 0; Loc < NumLocations; ++Loc) {
    const char *input = argv[Loc + 1] + strlen(locations_flag);
    if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
                                            &Locations[Loc].line,
                                            &Locations[Loc].column, 0, 0)))
      return errorCode;
  }

  if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
                           &num_unsaved_files))
    return -1;

  if (getenv("CINDEXTEST_EDITING"))
    Repeats = 5;

  /* Parse the translation unit. When we're testing clang_getCursor() after
     reparsing, don't remap unsaved files until the second parse. */
  CIdx = clang_createIndex(1, 1);
  Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
                                   argv + num_unsaved_files + 1 + NumLocations,
                                   argc - num_unsaved_files - 2 - NumLocations,
                                   unsaved_files,
                                   Repeats > 1? 0 : num_unsaved_files,
                                   getDefaultParsingOptions(), &TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "unable to parse input\n");
    describeLibclangFailure(Err);
    return -1;
  }

  if (checkForErrors(TU) != 0)
    return -1;

  for (I = 0; I != Repeats; ++I) {
    if (Repeats > 1) {
      Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
                                         clang_defaultReparseOptions(TU));
      if (Err != CXError_Success) {
        describeLibclangFailure(Err);
        clang_disposeTranslationUnit(TU);
        return 1;
      }
    }

    if (checkForErrors(TU) != 0)
      return -1;
    
    for (Loc = 0; Loc < NumLocations; ++Loc) {
      CXFile file = clang_getFile(TU, Locations[Loc].filename);
      if (!file)
        continue;

      Cursor = clang_getCursor(TU,
                               clang_getLocation(TU, file, Locations[Loc].line,
                                                 Locations[Loc].column));

      if (checkForErrors(TU) != 0)
        return -1;

      if (I + 1 == Repeats) {
        handler(Cursor);
        free(Locations[Loc].filename);
      }
    }
  }
  
  PrintDiagnostics(TU);
  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(CIdx);
  free(Locations);
  free_remapped_files(unsaved_files, num_unsaved_files);
  return 0;
}

static void inspect_print_cursor(CXCursor Cursor) {
  CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
  CXCompletionString completionString = clang_getCursorCompletionString(
                                                                  Cursor);
  CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
  CXString Spelling;
  const char *cspell;
  unsigned line, column;
  clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
  printf("%d:%d ", line, column);
  PrintCursor(Cursor, NULL);
  PrintCursorExtent(Cursor);
  Spelling = clang_getCursorSpelling(Cursor);
  cspell = clang_getCString(Spelling);
  if (cspell && strlen(cspell) != 0) {
    unsigned pieceIndex;
    printf(" Spelling=%s (", cspell);
    for (pieceIndex = 0; ; ++pieceIndex) {
      CXSourceRange range =
        clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
      if (clang_Range_isNull(range))
        break;
      PrintRange(range, 0);
    }
    printf(")");
  }
  clang_disposeString(Spelling);
  if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
    printf(" Selector index=%d",
           clang_Cursor_getObjCSelectorIndex(Cursor));
  if (clang_Cursor_isDynamicCall(Cursor))
    printf(" Dynamic-call");
  if (Cursor.kind == CXCursor_ObjCMessageExpr ||
      Cursor.kind == CXCursor_MemberRefExpr) {
    CXType T = clang_Cursor_getReceiverType(Cursor);
    if (T.kind != CXType_Invalid) {
      CXString S = clang_getTypeKindSpelling(T.kind);
      printf(" Receiver-type=%s", clang_getCString(S));
      clang_disposeString(S);
    }
  }

  {
    CXModule mod = clang_Cursor_getModule(Cursor);
    CXFile astFile;
    CXString name, astFilename;
    unsigned i, numHeaders;
    if (mod) {
      astFile = clang_Module_getASTFile(mod);
      astFilename = clang_getFileName(astFile);
      name = clang_Module_getFullName(mod);
      numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
      printf(" ModuleName=%s (%s) system=%d Headers(%d):",
             clang_getCString(name), clang_getCString(astFilename),
             clang_Module_isSystem(mod), numHeaders);
      clang_disposeString(name);
      clang_disposeString(astFilename);
      for (i = 0; i < numHeaders; ++i) {
        CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
        CXString filename = clang_getFileName(file);
        printf("\n%s", clang_getCString(filename));
        clang_disposeString(filename);
      }
    }
  }

  if (completionString != NULL) {
    printf("\nCompletion string: ");
    print_completion_string(completionString, stdout);
  }
  printf("\n");
}

static void display_evaluate_results(CXEvalResult result) {
  switch (clang_EvalResult_getKind(result)) {
    case CXEval_Int:
    {
      printf("Kind: Int, ");
      if (clang_EvalResult_isUnsignedInt(result)) {
        unsigned long long val = clang_EvalResult_getAsUnsigned(result);
        printf("unsigned, Value: %llu", val);
      } else {
        long long val = clang_EvalResult_getAsLongLong(result);
        printf("Value: %lld", val);
      }
      break;
    }
    case CXEval_Float:
    {
      double val = clang_EvalResult_getAsDouble(result);
      printf("Kind: Float , Value: %f", val);
      break;
    }
    case CXEval_ObjCStrLiteral:
    {
      const char* str = clang_EvalResult_getAsStr(result);
      printf("Kind: ObjCString , Value: %s", str);
      break;
    }
    case CXEval_StrLiteral:
    {
      const char* str = clang_EvalResult_getAsStr(result);
      printf("Kind: CString , Value: %s", str);
      break;
    }
    case CXEval_CFStr:
    {
      const char* str = clang_EvalResult_getAsStr(result);
      printf("Kind: CFString , Value: %s", str);
      break;
    }
    default:
      printf("Unexposed");
      break;
    }
}

static void inspect_evaluate_cursor(CXCursor Cursor) {
  CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
  CXString Spelling;
  const char *cspell;
  unsigned line, column;
  CXEvalResult ER;

  clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
  printf("%d:%d ", line, column);
  PrintCursor(Cursor, NULL);
  PrintCursorExtent(Cursor);
  Spelling = clang_getCursorSpelling(Cursor);
  cspell = clang_getCString(Spelling);
  if (cspell && strlen(cspell) != 0) {
    unsigned pieceIndex;
    printf(" Spelling=%s (", cspell);
    for (pieceIndex = 0; ; ++pieceIndex) {
      CXSourceRange range =
         clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
      if (clang_Range_isNull(range))
        break;
      PrintRange(range, 0);
    }
    printf(")");
  }
  clang_disposeString(Spelling);

  ER = clang_Cursor_Evaluate(Cursor);
  if (!ER) {
    printf("Not Evaluatable");
  } else {
    display_evaluate_results(ER);
    clang_EvalResult_dispose(ER);
  }
  printf("\n");
}

static void inspect_macroinfo_cursor(CXCursor Cursor) {
  CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
  CXString Spelling;
  const char *cspell;
  unsigned line, column;
  clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
  printf("%d:%d ", line, column);
  PrintCursor(Cursor, NULL);
  PrintCursorExtent(Cursor);
  Spelling = clang_getCursorSpelling(Cursor);
  cspell = clang_getCString(Spelling);
  if (cspell && strlen(cspell) != 0) {
    unsigned pieceIndex;
    printf(" Spelling=%s (", cspell);
    for (pieceIndex = 0; ; ++pieceIndex) {
      CXSourceRange range =
         clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
      if (clang_Range_isNull(range))
        break;
      PrintRange(range, 0);
    }
    printf(")");
  }
  clang_disposeString(Spelling);

  if (clang_Cursor_isMacroBuiltin(Cursor)) {
    printf("[builtin macro]");
  } else if (clang_Cursor_isMacroFunctionLike(Cursor)) {
    printf("[function macro]");
  }
  printf("\n");
}

static enum CXVisitorResult findFileRefsVisit(void *context,
                                         CXCursor cursor, CXSourceRange range) {
  if (clang_Range_isNull(range))
    return CXVisit_Continue;

  PrintCursor(cursor, NULL);
  PrintRange(range, "");
  printf("\n");
  return CXVisit_Continue;
}

static int find_file_refs_at(int argc, const char **argv) {
  CXIndex CIdx;
  int errorCode;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  enum CXErrorCode Err;
  CXTranslationUnit TU;
  CXCursor Cursor;
  CursorSourceLocation *Locations = 0;
  unsigned NumLocations = 0, Loc;
  unsigned Repeats = 1;
  unsigned I;
  
  /* Count the number of locations. */
  while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
    ++NumLocations;

  /* Parse the locations. */
  assert(NumLocations > 0 && "Unable to count locations?");
  Locations = (CursorSourceLocation *)malloc(
                                  NumLocations * sizeof(CursorSourceLocation));
  assert(Locations);
  for (Loc = 0; Loc < NumLocations; ++Loc) {
    const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
    if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
                                            &Locations[Loc].line,
                                            &Locations[Loc].column, 0, 0)))
      return errorCode;
  }

  if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
                           &num_unsaved_files))
    return -1;

  if (getenv("CINDEXTEST_EDITING"))
    Repeats = 5;

  /* Parse the translation unit. When we're testing clang_getCursor() after
     reparsing, don't remap unsaved files until the second parse. */
  CIdx = clang_createIndex(1, 1);
  Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
                                    argv + num_unsaved_files + 1 + NumLocations,
                                    argc - num_unsaved_files - 2 - NumLocations,
                                    unsaved_files,
                                    Repeats > 1? 0 : num_unsaved_files,
                                    getDefaultParsingOptions(), &TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "unable to parse input\n");
    describeLibclangFailure(Err);
    clang_disposeTranslationUnit(TU);
    return -1;
  }

  if (checkForErrors(TU) != 0)
    return -1;

  for (I = 0; I != Repeats; ++I) {
    if (Repeats > 1) {
      Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
                                         clang_defaultReparseOptions(TU));
      if (Err != CXError_Success) {
        describeLibclangFailure(Err);
        clang_disposeTranslationUnit(TU);
        return 1;
      }
    }

    if (checkForErrors(TU) != 0)
      return -1;
    
    for (Loc = 0; Loc < NumLocations; ++Loc) {
      CXFile file = clang_getFile(TU, Locations[Loc].filename);
      if (!file)
        continue;

      Cursor = clang_getCursor(TU,
                               clang_getLocation(TU, file, Locations[Loc].line,
                                                 Locations[Loc].column));

      if (checkForErrors(TU) != 0)
        return -1;

      if (I + 1 == Repeats) {
        CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
        PrintCursor(Cursor, NULL);
        printf("\n");
        clang_findReferencesInFile(Cursor, file, visitor);
        free(Locations[Loc].filename);

        if (checkForErrors(TU) != 0)
          return -1;
      }
    }
  }
  
  PrintDiagnostics(TU);
  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(CIdx);
  free(Locations);
  free_remapped_files(unsaved_files, num_unsaved_files);
  return 0;
}

static enum CXVisitorResult findFileIncludesVisit(void *context,
                                         CXCursor cursor, CXSourceRange range) {
  PrintCursor(cursor, NULL);
  PrintRange(range, "");
  printf("\n");
  return CXVisit_Continue;
}

static int find_file_includes_in(int argc, const char **argv) {
  CXIndex CIdx;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  enum CXErrorCode Err;
  CXTranslationUnit TU;
  const char **Filenames = 0;
  unsigned NumFilenames = 0;
  unsigned Repeats = 1;
  unsigned I, FI;

  /* Count the number of locations. */
  while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
    ++NumFilenames;

  /* Parse the locations. */
  assert(NumFilenames > 0 && "Unable to count filenames?");
  Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
  assert(Filenames);
  for (I = 0; I < NumFilenames; ++I) {
    const char *input = argv[I + 1] + strlen("-file-includes-in=");
    /* Copy the file name. */
    Filenames[I] = input;
  }

  if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
                           &num_unsaved_files))
    return -1;

  if (getenv("CINDEXTEST_EDITING"))
    Repeats = 2;

  /* Parse the translation unit. When we're testing clang_getCursor() after
     reparsing, don't remap unsaved files until the second parse. */
  CIdx = clang_createIndex(1, 1);
  Err = clang_parseTranslationUnit2(
      CIdx, argv[argc - 1],
      argv + num_unsaved_files + 1 + NumFilenames,
      argc - num_unsaved_files - 2 - NumFilenames,
      unsaved_files,
      Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);

  if (Err != CXError_Success) {
    fprintf(stderr, "unable to parse input\n");
    describeLibclangFailure(Err);
    clang_disposeTranslationUnit(TU);
    return -1;
  }

  if (checkForErrors(TU) != 0)
    return -1;

  for (I = 0; I != Repeats; ++I) {
    if (Repeats > 1) {
      Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
                                         clang_defaultReparseOptions(TU));
      if (Err != CXError_Success) {
        describeLibclangFailure(Err);
        clang_disposeTranslationUnit(TU);
        return 1;
      }
    }

    if (checkForErrors(TU) != 0)
      return -1;

    for (FI = 0; FI < NumFilenames; ++FI) {
      CXFile file = clang_getFile(TU, Filenames[FI]);
      if (!file)
        continue;

      if (checkForErrors(TU) != 0)
        return -1;

      if (I + 1 == Repeats) {
        CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
        clang_findIncludesInFile(TU, file, visitor);

        if (checkForErrors(TU) != 0)
          return -1;
      }
    }
  }

  PrintDiagnostics(TU);
  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(CIdx);
  free((void *)Filenames);
  free_remapped_files(unsaved_files, num_unsaved_files);
  return 0;
}

#define MAX_IMPORTED_ASTFILES 200

typedef struct {
  char **filenames;
  unsigned num_files;
} ImportedASTFilesData;

static ImportedASTFilesData *importedASTs_create() {
  ImportedASTFilesData *p;
  p = malloc(sizeof(ImportedASTFilesData));
  assert(p);
  p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
  assert(p->filenames);
  p->num_files = 0;
  return p;
}

static void importedASTs_dispose(ImportedASTFilesData *p) {
  unsigned i;
  if (!p)
    return;

  for (i = 0; i < p->num_files; ++i)
    free(p->filenames[i]);
  free(p->filenames);
  free(p);
}

static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
  unsigned i;
  assert(p && file);
  for (i = 0; i < p->num_files; ++i)
    if (strcmp(file, p->filenames[i]) == 0)
      return;
  assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
  p->filenames[p->num_files++] = strdup(file);
}

typedef struct IndexDataStringList_ {
  struct IndexDataStringList_ *next;
  char data[1]; /* Dynamically sized. */
} IndexDataStringList;

typedef struct {
  const char *check_prefix;
  int first_check_printed;
  int fail_for_error;
  int abort;
  CXString main_filename;
  ImportedASTFilesData *importedASTs;
  IndexDataStringList *strings;
  CXTranslationUnit TU;
} IndexData;

static void free_client_data(IndexData *index_data) {
  IndexDataStringList *node = index_data->strings;
  while (node) {
    IndexDataStringList *next = node->next;
    free(node);
    node = next;
  }
  index_data->strings = NULL;
}

static void printCheck(IndexData *data) {
  if (data->check_prefix) {
    if (data->first_check_printed) {
      printf("// %s-NEXT: ", data->check_prefix);
    } else {
      printf("// %s     : ", data->check_prefix);
      data->first_check_printed = 1;
    }
  }
}

static void printCXIndexFile(CXIdxClientFile file) {
  CXString filename = clang_getFileName((CXFile)file);
  printf("%s", clang_getCString(filename));
  clang_disposeString(filename);
}

static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
  IndexData *index_data;
  CXString filename;
  const char *cname;
  CXIdxClientFile file;
  unsigned line, column;
  const char *main_filename;
  int isMainFile;
  
  index_data = (IndexData *)client_data;
  clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
  if (line == 0) {
    printf("<invalid>");
    return;
  }
  if (!file) {
    printf("<no idxfile>");
    return;
  }
  filename = clang_getFileName((CXFile)file);
  cname = clang_getCString(filename);
  main_filename = clang_getCString(index_data->main_filename);
  if (strcmp(cname, main_filename) == 0)
    isMainFile = 1;
  else
    isMainFile = 0;
  clang_disposeString(filename);

  if (!isMainFile) {
    printCXIndexFile(file);
    printf(":");
  }
  printf("%d:%d", line, column);
}

static unsigned digitCount(unsigned val) {
  unsigned c = 1;
  while (1) {
    if (val < 10)
      return c;
    ++c;
    val /= 10;
  }
}

static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
                                                const CXIdxEntityInfo *info,
                                                CXIdxLoc loc) {
  IndexData *index_data;
  IndexDataStringList *node;
  const char *name;
  char *newStr;
  CXIdxClientFile file;
  unsigned line, column;
  
  name = info->name;
  if (!name)
    name = "<anon-tag>";

  clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);

  node =
      (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
                                    digitCount(line) + digitCount(column) + 2);
  assert(node);
  newStr = node->data;
  sprintf(newStr, "%s:%d:%d", name, line, column);

  /* Remember string so it can be freed later. */
  index_data = (IndexData *)client_data;
  node->next = index_data->strings;
  index_data->strings = node;

  return (CXIdxClientContainer)newStr;
}

static void printCXIndexContainer(const CXIdxContainerInfo *info) {
  CXIdxClientContainer container;
  container = clang_index_getClientContainer(info);
  if (!container)
    printf("[<<NULL>>]");
  else
    printf("[%s]", (const char *)container);
}

static const char *getEntityKindString(CXIdxEntityKind kind) {
  switch (kind) {
  case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
  case CXIdxEntity_Typedef: return "typedef";
  case CXIdxEntity_Function: return "function";
  case CXIdxEntity_Variable: return "variable";
  case CXIdxEntity_Field: return "field";
  case CXIdxEntity_EnumConstant: return "enumerator";
  case CXIdxEntity_ObjCClass: return "objc-class";
  case CXIdxEntity_ObjCProtocol: return "objc-protocol";
  case CXIdxEntity_ObjCCategory: return "objc-category";
  case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
  case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
  case CXIdxEntity_ObjCProperty: return "objc-property";
  case CXIdxEntity_ObjCIvar: return "objc-ivar";
  case CXIdxEntity_Enum: return "enum";
  case CXIdxEntity_Struct: return "struct";
  case CXIdxEntity_Union: return "union";
  case CXIdxEntity_CXXClass: return "c++-class";
  case CXIdxEntity_CXXNamespace: return "namespace";
  case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
  case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
  case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
  case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
  case CXIdxEntity_CXXConstructor: return "constructor";
  case CXIdxEntity_CXXDestructor: return "destructor";
  case CXIdxEntity_CXXConversionFunction: return "conversion-func";
  case CXIdxEntity_CXXTypeAlias: return "type-alias";
  case CXIdxEntity_CXXInterface: return "c++-__interface";
  }
  assert(0 && "Garbage entity kind");
  return 0;
}

static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
  switch (kind) {
  case CXIdxEntity_NonTemplate: return "";
  case CXIdxEntity_Template: return "-template";
  case CXIdxEntity_TemplatePartialSpecialization:
    return "-template-partial-spec";
  case CXIdxEntity_TemplateSpecialization: return "-template-spec";
  }
  assert(0 && "Garbage entity kind");
  return 0;
}

static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
  switch (kind) {
  case CXIdxEntityLang_None: return "<none>";
  case CXIdxEntityLang_C: return "C";
  case CXIdxEntityLang_ObjC: return "ObjC";
  case CXIdxEntityLang_CXX: return "C++";
  case CXIdxEntityLang_Swift: return "Swift";
  }
  assert(0 && "Garbage language kind");
  return 0;
}

static void printEntityInfo(const char *cb,
                            CXClientData client_data,
                            const CXIdxEntityInfo *info) {
  const char *name;
  IndexData *index_data;
  unsigned i;
  index_data = (IndexData *)client_data;
  printCheck(index_data);

  if (!info) {
    printf("%s: <<NULL>>", cb);
    return;
  }

  name = info->name;
  if (!name)
    name = "<anon-tag>";

  printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
         getEntityTemplateKindString(info->templateKind));
  printf(" | name: %s", name);
  printf(" | USR: %s", info->USR);
  printf(" | lang: %s", getEntityLanguageString(info->lang));

  for (i = 0; i != info->numAttributes; ++i) {
    const CXIdxAttrInfo *Attr = info->attributes[i];
    printf("     <attribute>: ");
    PrintCursor(Attr->cursor, NULL);
  }
}

static void printBaseClassInfo(CXClientData client_data,
                               const CXIdxBaseClassInfo *info) {
  printEntityInfo("     <base>", client_data, info->base);
  printf(" | cursor: ");
  PrintCursor(info->cursor, NULL);
  printf(" | loc: ");
  printCXIndexLoc(info->loc, client_data);
}

static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
                              CXClientData client_data) {
  unsigned i;
  for (i = 0; i < ProtoInfo->numProtocols; ++i) {
    printEntityInfo("     <protocol>", client_data,
                    ProtoInfo->protocols[i]->protocol);
    printf(" | cursor: ");
    PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
    printf(" | loc: ");
    printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
    printf("\n");
  }
}

static void printSymbolRole(CXSymbolRole role) {
  if (role & CXSymbolRole_Declaration)
    printf(" decl");
  if (role & CXSymbolRole_Definition)
    printf(" def");
  if (role & CXSymbolRole_Reference)
    printf(" ref");
  if (role & CXSymbolRole_Read)
    printf(" read");
  if (role & CXSymbolRole_Write)
    printf(" write");
  if (role & CXSymbolRole_Call)
    printf(" call");
  if (role & CXSymbolRole_Dynamic)
    printf(" dyn");
  if (role & CXSymbolRole_AddressOf)
    printf(" addr");
  if (role & CXSymbolRole_Implicit)
    printf(" implicit");
}

static void index_diagnostic(CXClientData client_data,
                             CXDiagnosticSet diagSet, void *reserved) {
  CXString str;
  const char *cstr;
  unsigned numDiags, i;
  CXDiagnostic diag;
  IndexData *index_data;
  index_data = (IndexData *)client_data;
  printCheck(index_data);

  numDiags = clang_getNumDiagnosticsInSet(diagSet);
  for (i = 0; i != numDiags; ++i) {
    diag = clang_getDiagnosticInSet(diagSet, i);
    str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
    cstr = clang_getCString(str);
    printf("[diagnostic]: %s\n", cstr);
    clang_disposeString(str);  
  
    if (getenv("CINDEXTEST_FAILONERROR") &&
        clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
      index_data->fail_for_error = 1;
    }
  }
}

static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
                                       CXFile file, void *reserved) {
  IndexData *index_data;

  index_data = (IndexData *)client_data;
  printCheck(index_data);

  index_data->main_filename = clang_getFileName(file);

  printf("[enteredMainFile]: ");
  printCXIndexFile((CXIdxClientFile)file);
  printf("\n");

  return (CXIdxClientFile)file;
}

static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
                                            const CXIdxIncludedFileInfo *info) {
  IndexData *index_data;
  CXModule Mod;
  index_data = (IndexData *)client_data;
  printCheck(index_data);

  printf("[ppIncludedFile]: ");
  printCXIndexFile((CXIdxClientFile)info->file);
  printf(" | name: \"%s\"", info->filename);
  printf(" | hash loc: ");
  printCXIndexLoc(info->hashLoc, client_data);
  printf(" | isImport: %d | isAngled: %d | isModule: %d",
         info->isImport, info->isAngled, info->isModuleImport);
  
  Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
  if (Mod) {
    CXString str = clang_Module_getFullName(Mod);
    const char *cstr = clang_getCString(str);
    printf(" | module: %s", cstr);
    clang_disposeString(str);
  }

  printf("\n");

  return (CXIdxClientFile)info->file;
}

static CXIdxClientFile index_importedASTFile(CXClientData client_data,
                                         const CXIdxImportedASTFileInfo *info) {
  IndexData *index_data;
  index_data = (IndexData *)client_data;
  printCheck(index_data);

  if (index_data->importedASTs) {
    CXString filename = clang_getFileName(info->file);
    importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
    clang_disposeString(filename);
  }
  
  printf("[importedASTFile]: ");
  printCXIndexFile((CXIdxClientFile)info->file);
  if (info->module) {
    CXString name = clang_Module_getFullName(info->module);
    printf(" | loc: ");
    printCXIndexLoc(info->loc, client_data);
    printf(" | name: \"%s\"", clang_getCString(name));
    printf(" | isImplicit: %d\n", info->isImplicit);
    clang_disposeString(name);
  } else {
    /* PCH file, the rest are not relevant. */
    printf("\n");
  }

  return (CXIdxClientFile)info->file;
}

static CXIdxClientContainer
index_startedTranslationUnit(CXClientData client_data, void *reserved) {
  IndexData *index_data;
  index_data = (IndexData *)client_data;
  printCheck(index_data);

  printf("[startedTranslationUnit]\n");
  return (CXIdxClientContainer)"TU";
}

static void index_indexDeclaration(CXClientData client_data,
                                   const CXIdxDeclInfo *info) {
  IndexData *index_data;
  const CXIdxObjCCategoryDeclInfo *CatInfo;
  const CXIdxObjCInterfaceDeclInfo *InterInfo;
  const CXIdxObjCProtocolRefListInfo *ProtoInfo;
  const CXIdxObjCPropertyDeclInfo *PropInfo;
  const CXIdxCXXClassDeclInfo *CXXClassInfo;
  unsigned i;
  index_data = (IndexData *)client_data;

  printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
  printf(" | cursor: ");
  PrintCursor(info->cursor, NULL);
  printf(" | loc: ");
  printCXIndexLoc(info->loc, client_data);
  printf(" | semantic-container: ");
  printCXIndexContainer(info->semanticContainer);
  printf(" | lexical-container: ");
  printCXIndexContainer(info->lexicalContainer);
  printf(" | isRedecl: %d", info->isRedeclaration);
  printf(" | isDef: %d", info->isDefinition);
  if (info->flags & CXIdxDeclFlag_Skipped) {
    assert(!info->isContainer);
    printf(" | isContainer: skipped");
  } else {
    printf(" | isContainer: %d", info->isContainer);
  }
  printf(" | isImplicit: %d\n", info->isImplicit);

  for (i = 0; i != info->numAttributes; ++i) {
    const CXIdxAttrInfo *Attr = info->attributes[i];
    printf("     <attribute>: ");
    PrintCursor(Attr->cursor, NULL);
    printf("\n");
  }

  if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
    const char *kindName = 0;
    CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
    switch (K) {
    case CXIdxObjCContainer_ForwardRef:
      kindName = "forward-ref"; break;
    case CXIdxObjCContainer_Interface:
      kindName = "interface"; break;
    case CXIdxObjCContainer_Implementation:
      kindName = "implementation"; break;
    }
    printCheck(index_data);
    printf("     <ObjCContainerInfo>: kind: %s\n", kindName);
  }

  if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
    printEntityInfo("     <ObjCCategoryInfo>: class", client_data,
                    CatInfo->objcClass);
    printf(" | cursor: ");
    PrintCursor(CatInfo->classCursor, NULL);
    printf(" | loc: ");
    printCXIndexLoc(CatInfo->classLoc, client_data);
    printf("\n");
  }

  if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
    if (InterInfo->superInfo) {
      printBaseClassInfo(client_data, InterInfo->superInfo);
      printf("\n");
    }
  }

  if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
    printProtocolList(ProtoInfo, client_data);
  }

  if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
    if (PropInfo->getter) {
      printEntityInfo("     <getter>", client_data, PropInfo->getter);
      printf("\n");
    }
    if (PropInfo->setter) {
      printEntityInfo("     <setter>", client_data, PropInfo->setter);
      printf("\n");
    }
  }

  if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
    for (i = 0; i != CXXClassInfo->numBases; ++i) {
      printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
      printf("\n");
    }
  }

  if (info->declAsContainer)
    clang_index_setClientContainer(
        info->declAsContainer,
        makeClientContainer(client_data, info->entityInfo, info->loc));
}

static void index_indexEntityReference(CXClientData client_data,
                                       const CXIdxEntityRefInfo *info) {
  printEntityInfo("[indexEntityReference]", client_data,
                  info->referencedEntity);
  printf(" | cursor: ");
  PrintCursor(info->cursor, NULL);
  printf(" | loc: ");
  printCXIndexLoc(info->loc, client_data);
  printEntityInfo(" | <parent>:", client_data, info->parentEntity);
  printf(" | container: ");
  printCXIndexContainer(info->container);
  printf(" | refkind: ");
  switch (info->kind) {
    case CXIdxEntityRef_Direct: printf("direct"); break;
    case CXIdxEntityRef_Implicit: printf("implicit"); break;
  }
  printf(" | role:");
  printSymbolRole(info->role);
  printf("\n");
}

static int index_abortQuery(CXClientData client_data, void *reserved) {
  IndexData *index_data;
  index_data = (IndexData *)client_data;
  return index_data->abort;
}

static IndexerCallbacks IndexCB = {
  index_abortQuery,
  index_diagnostic,
  index_enteredMainFile,
  index_ppIncludedFile,
  index_importedASTFile,
  index_startedTranslationUnit,
  index_indexDeclaration,
  index_indexEntityReference
};

static unsigned getIndexOptions(void) {
  unsigned index_opts;
  index_opts = 0;
  if (getenv("CINDEXTEST_SUPPRESSREFS"))
    index_opts |= CXIndexOpt_SuppressRedundantRefs;
  if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
    index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
  if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
    index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
  if (getenv("CINDEXTEST_INDEXIMPLICITTEMPLATEINSTANTIATIONS"))
    index_opts |= CXIndexOpt_IndexImplicitTemplateInstantiations;

  return index_opts;
}

static int index_compile_args(int num_args, const char **args,
                              CXIndexAction idxAction,
                              ImportedASTFilesData *importedASTs,
                              const char *check_prefix) {
  IndexData index_data;
  unsigned index_opts;
  int result;

  if (num_args == 0) {
    fprintf(stderr, "no compiler arguments\n");
    return -1;
  }

  index_data.check_prefix = check_prefix;
  index_data.first_check_printed = 0;
  index_data.fail_for_error = 0;
  index_data.abort = 0;
  index_data.main_filename = createCXString("");
  index_data.importedASTs = importedASTs;
  index_data.strings = NULL;
  index_data.TU = NULL;

  index_opts = getIndexOptions();
  result = clang_indexSourceFile(idxAction, &index_data,
                                 &IndexCB,sizeof(IndexCB), index_opts,
                                 0, args, num_args, 0, 0, 0,
                                 getDefaultParsingOptions());
  if (result != CXError_Success)
    describeLibclangFailure(result);

  if (index_data.fail_for_error)
    result = -1;

  clang_disposeString(index_data.main_filename);
  free_client_data(&index_data);
  return result;
}

static int index_ast_file(const char *ast_file,
                          CXIndex Idx,
                          CXIndexAction idxAction,
                          ImportedASTFilesData *importedASTs,
                          const char *check_prefix) {
  CXTranslationUnit TU;
  IndexData index_data;
  unsigned index_opts;
  int result;

  if (!CreateTranslationUnit(Idx, ast_file, &TU))
    return -1;

  index_data.check_prefix = check_prefix;
  index_data.first_check_printed = 0;
  index_data.fail_for_error = 0;
  index_data.abort = 0;
  index_data.main_filename = createCXString("");
  index_data.importedASTs = importedASTs;
  index_data.strings = NULL;
  index_data.TU = TU;

  index_opts = getIndexOptions();
  result = clang_indexTranslationUnit(idxAction, &index_data,
                                      &IndexCB,sizeof(IndexCB),
                                      index_opts, TU);
  if (index_data.fail_for_error)
    result = -1;

  clang_disposeTranslationUnit(TU);
  clang_disposeString(index_data.main_filename);
  free_client_data(&index_data);
  return result;
}

static int index_file(int argc, const char **argv, int full) {
  const char *check_prefix;
  CXIndex Idx;
  CXIndexAction idxAction;
  ImportedASTFilesData *importedASTs;
  int result;

  check_prefix = 0;
  if (argc > 0) {
    if (strstr(argv[0], "-check-prefix=") == argv[0]) {
      check_prefix = argv[0] + strlen("-check-prefix=");
      ++argv;
      --argc;
    }
  }

  if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
                                /* displayDiagnostics=*/1))) {
    fprintf(stderr, "Could not create Index\n");
    return 1;
  }
  idxAction = clang_IndexAction_create(Idx);
  importedASTs = 0;
  if (full)
    importedASTs = importedASTs_create();

  result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
  if (result != 0)
    goto finished;

  if (full) {
    unsigned i;
    for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
      result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
                              importedASTs, check_prefix);
    }
  }

finished:
  importedASTs_dispose(importedASTs);
  clang_IndexAction_dispose(idxAction);
  clang_disposeIndex(Idx);
  return result;
}

static int index_tu(int argc, const char **argv) {
  const char *check_prefix;
  CXIndex Idx;
  CXIndexAction idxAction;
  int result;

  check_prefix = 0;
  if (argc > 0) {
    if (strstr(argv[0], "-check-prefix=") == argv[0]) {
      check_prefix = argv[0] + strlen("-check-prefix=");
      ++argv;
      --argc;
    }
  }

  if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
                                /* displayDiagnostics=*/1))) {
    fprintf(stderr, "Could not create Index\n");
    return 1;
  }
  idxAction = clang_IndexAction_create(Idx);

  result = index_ast_file(argv[0], Idx, idxAction,
                          /*importedASTs=*/0, check_prefix);

  clang_IndexAction_dispose(idxAction);
  clang_disposeIndex(Idx);
  return result;
}

static int index_compile_db(int argc, const char **argv) {
  const char *check_prefix;
  CXIndex Idx;
  CXIndexAction idxAction;
  int errorCode = 0;

  check_prefix = 0;
  if (argc > 0) {
    if (strstr(argv[0], "-check-prefix=") == argv[0]) {
      check_prefix = argv[0] + strlen("-check-prefix=");
      ++argv;
      --argc;
    }
  }

  if (argc == 0) {
    fprintf(stderr, "no compilation database\n");
    return -1;
  }

  if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
                                /* displayDiagnostics=*/1))) {
    fprintf(stderr, "Could not create Index\n");
    return 1;
  }
  idxAction = clang_IndexAction_create(Idx);

  {
    const char *database = argv[0];
    CXCompilationDatabase db = 0;
    CXCompileCommands CCmds = 0;
    CXCompileCommand CCmd;
    CXCompilationDatabase_Error ec;
    CXString wd;
#define MAX_COMPILE_ARGS 512
    CXString cxargs[MAX_COMPILE_ARGS];
    const char *args[MAX_COMPILE_ARGS];
    char *tmp;
    unsigned len;
    char *buildDir;
    int i, a, numCmds, numArgs;

    len = strlen(database);
    tmp = (char *) malloc(len+1);
    assert(tmp);
    memcpy(tmp, database, len+1);
    buildDir = dirname(tmp);

    db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);

    if (db) {

      if (ec!=CXCompilationDatabase_NoError) {
        printf("unexpected error %d code while loading compilation database\n", ec);
        errorCode = -1;
        goto cdb_end;
      }

      if (chdir(buildDir) != 0) {
        printf("Could not chdir to %s\n", buildDir);
        errorCode = -1;
        goto cdb_end;
      }

      CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
      if (!CCmds) {
        printf("compilation db is empty\n");
        errorCode = -1;
        goto cdb_end;
      }

      numCmds = clang_CompileCommands_getSize(CCmds);

      if (numCmds==0) {
        fprintf(stderr, "should not get an empty compileCommand set\n");
        errorCode = -1;
        goto cdb_end;
      }

      for (i=0; i<numCmds && errorCode == 0; ++i) {
        CCmd = clang_CompileCommands_getCommand(CCmds, i);

        wd = clang_CompileCommand_getDirectory(CCmd);
        if (chdir(clang_getCString(wd)) != 0) {
          printf("Could not chdir to %s\n", clang_getCString(wd));
          errorCode = -1;
          goto cdb_end;
        }
        clang_disposeString(wd);

        numArgs = clang_CompileCommand_getNumArgs(CCmd);
        if (numArgs > MAX_COMPILE_ARGS){
          fprintf(stderr, "got more compile arguments than maximum\n");
          errorCode = -1;
          goto cdb_end;
        }
        for (a=0; a<numArgs; ++a) {
          cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
          args[a] = clang_getCString(cxargs[a]);
        }

        errorCode = index_compile_args(numArgs, args, idxAction,
                                       /*importedASTs=*/0, check_prefix);

        for (a=0; a<numArgs; ++a)
          clang_disposeString(cxargs[a]);
      }
    } else {
      printf("database loading failed with error code %d.\n", ec);
      errorCode = -1;
    }

  cdb_end:
    clang_CompileCommands_dispose(CCmds);
    clang_CompilationDatabase_dispose(db);
    free(tmp);

  }

  clang_IndexAction_dispose(idxAction);
  clang_disposeIndex(Idx);
  return errorCode;
}

int perform_token_annotation(int argc, const char **argv) {
  const char *input = argv[1];
  char *filename = 0;
  unsigned line, second_line;
  unsigned column, second_column;
  CXIndex CIdx;
  CXTranslationUnit TU = 0;
  int errorCode;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  CXToken *tokens;
  unsigned num_tokens;
  CXSourceRange range;
  CXSourceLocation startLoc, endLoc;
  CXFile file = 0;
  CXCursor *cursors = 0;
  CXSourceRangeList *skipped_ranges = 0;
  enum CXErrorCode Err;
  unsigned i;

  input += strlen("-test-annotate-tokens=");
  if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
                                          &second_line, &second_column)))
    return errorCode;

  if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
    free(filename);
    return -1;
  }

  CIdx = clang_createIndex(0, 1);
  Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
                                    argv + num_unsaved_files + 2,
                                    argc - num_unsaved_files - 3,
                                    unsaved_files,
                                    num_unsaved_files,
                                    getDefaultParsingOptions(), &TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "unable to parse input\n");
    describeLibclangFailure(Err);
    clang_disposeIndex(CIdx);
    free(filename);
    free_remapped_files(unsaved_files, num_unsaved_files);
    return -1;
  }
  errorCode = 0;

  if (checkForErrors(TU) != 0) {
    errorCode = -1;
    goto teardown;
  }

  if (getenv("CINDEXTEST_EDITING")) {
    for (i = 0; i < 5; ++i) {
      Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
                                         clang_defaultReparseOptions(TU));
      if (Err != CXError_Success) {
        fprintf(stderr, "Unable to reparse translation unit!\n");
        describeLibclangFailure(Err);
        errorCode = -1;
        goto teardown;
      }
    }
  }

  if (checkForErrors(TU) != 0) {
    errorCode = -1;
    goto teardown;
  }

  file = clang_getFile(TU, filename);
  if (!file) {
    fprintf(stderr, "file %s is not in this translation unit\n", filename);
    errorCode = -1;
    goto teardown;
  }

  startLoc = clang_getLocation(TU, file, line, column);
  if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
    fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
            column);
    errorCode = -1;
    goto teardown;
  }

  endLoc = clang_getLocation(TU, file, second_line, second_column);
  if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
    fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
            second_line, second_column);
    errorCode = -1;
    goto teardown;
  }

  range = clang_getRange(startLoc, endLoc);
  clang_tokenize(TU, range, &tokens, &num_tokens);

  if (checkForErrors(TU) != 0) {
    errorCode = -1;
    goto teardown;
  }

  cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
  assert(cursors);
  clang_annotateTokens(TU, tokens, num_tokens, cursors);

  if (checkForErrors(TU) != 0) {
    errorCode = -1;
    goto teardown;
  }

  skipped_ranges = clang_getSkippedRanges(TU, file);
  for (i = 0; i != skipped_ranges->count; ++i) {
    unsigned start_line, start_column, end_line, end_column;
    clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
                              0, &start_line, &start_column, 0);
    clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
                              0, &end_line, &end_column, 0);
    printf("Skipping: ");
    PrintExtent(stdout, start_line, start_column, end_line, end_column);
    printf("\n");
  }
  clang_disposeSourceRangeList(skipped_ranges);

  for (i = 0; i != num_tokens; ++i) {
    const char *kind = "<unknown>";
    CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
    CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
    unsigned start_line, start_column, end_line, end_column;

    switch (clang_getTokenKind(tokens[i])) {
    case CXToken_Punctuation: kind = "Punctuation"; break;
    case CXToken_Keyword: kind = "Keyword"; break;
    case CXToken_Identifier: kind = "Identifier"; break;
    case CXToken_Literal: kind = "Literal"; break;
    case CXToken_Comment: kind = "Comment"; break;
    }
    clang_getSpellingLocation(clang_getRangeStart(extent),
                              0, &start_line, &start_column, 0);
    clang_getSpellingLocation(clang_getRangeEnd(extent),
                              0, &end_line, &end_column, 0);
    printf("%s: \"%s\" ", kind, clang_getCString(spelling));
    clang_disposeString(spelling);
    PrintExtent(stdout, start_line, start_column, end_line, end_column);
    if (!clang_isInvalid(cursors[i].kind)) {
      printf(" ");
      PrintCursor(cursors[i], NULL);
    }
    printf("\n");
  }
  free(cursors);
  clang_disposeTokens(TU, tokens, num_tokens);

 teardown:
  PrintDiagnostics(TU);
  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(CIdx);
  free(filename);
  free_remapped_files(unsaved_files, num_unsaved_files);
  return errorCode;
}

static int
perform_test_compilation_db(const char *database, int argc, const char **argv) {
  CXCompilationDatabase db;
  CXCompileCommands CCmds;
  CXCompileCommand CCmd;
  CXCompilationDatabase_Error ec;
  CXString wd;
  CXString arg;
  int errorCode = 0;
  char *tmp;
  unsigned len;
  char *buildDir;
  int i, j, a, numCmds, numArgs;

  len = strlen(database);
  tmp = (char *) malloc(len+1);
  assert(tmp);
  memcpy(tmp, database, len+1);
  buildDir = dirname(tmp);

  db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);

  if (db) {

    if (ec!=CXCompilationDatabase_NoError) {
      printf("unexpected error %d code while loading compilation database\n", ec);
      errorCode = -1;
      goto cdb_end;
    }

    for (i=0; i<argc && errorCode==0; ) {
      if (strcmp(argv[i],"lookup")==0){
        CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);

        if (!CCmds) {
          printf("file %s not found in compilation db\n", argv[i+1]);
          errorCode = -1;
          break;
        }

        numCmds = clang_CompileCommands_getSize(CCmds);

        if (numCmds==0) {
          fprintf(stderr, "should not get an empty compileCommand set for file"
                          " '%s'\n", argv[i+1]);
          errorCode = -1;
          break;
        }

        for (j=0; j<numCmds; ++j) {
          CCmd = clang_CompileCommands_getCommand(CCmds, j);

          wd = clang_CompileCommand_getDirectory(CCmd);
          printf("workdir:'%s'", clang_getCString(wd));
          clang_disposeString(wd);

          printf(" cmdline:'");
          numArgs = clang_CompileCommand_getNumArgs(CCmd);
          for (a=0; a<numArgs; ++a) {
            if (a) printf(" ");
            arg = clang_CompileCommand_getArg(CCmd, a);
            printf("%s", clang_getCString(arg));
            clang_disposeString(arg);
          }
          printf("'\n");
        }

        clang_CompileCommands_dispose(CCmds);

        i += 2;
      }
    }
    clang_CompilationDatabase_dispose(db);
  } else {
    printf("database loading failed with error code %d.\n", ec);
    errorCode = -1;
  }

cdb_end:
  free(tmp);

  return errorCode;
}

/******************************************************************************/
/* USR printing.                                                              */
/******************************************************************************/

static int insufficient_usr(const char *kind, const char *usage) {
  fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
  return 1;
}

static unsigned isUSR(const char *s) {
  return s[0] == 'c' && s[1] == ':';
}

static int not_usr(const char *s, const char *arg) {
  fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
  return 1;
}

static void print_usr(CXString usr) {
  const char *s = clang_getCString(usr);
  printf("%s\n", s);
  clang_disposeString(usr);
}

static void display_usrs() {
  fprintf(stderr, "-print-usrs options:\n"
        " ObjCCategory <class name> <category name>\n"
        " ObjCClass <class name>\n"
        " ObjCIvar <ivar name> <class USR>\n"
        " ObjCMethod <selector> [0=class method|1=instance method] "
            "<class USR>\n"
          " ObjCProperty <property name> <class USR>\n"
          " ObjCProtocol <protocol name>\n");
}

int print_usrs(const char **I, const char **E) {
  while (I != E) {
    const char *kind = *I;
    unsigned len = strlen(kind);
    switch (len) {
      case 8:
        if (memcmp(kind, "ObjCIvar", 8) == 0) {
          if (I + 2 >= E)
            return insufficient_usr(kind, "<ivar name> <class USR>");
          if (!isUSR(I[2]))
            return not_usr("<class USR>", I[2]);
          else {
            CXString x = createCXString(I[2]);
            print_usr(clang_constructUSR_ObjCIvar(I[1], x));
          }

          I += 3;
          continue;
        }
        break;
      case 9:
        if (memcmp(kind, "ObjCClass", 9) == 0) {
          if (I + 1 >= E)
            return insufficient_usr(kind, "<class name>");
          print_usr(clang_constructUSR_ObjCClass(I[1]));
          I += 2;
          continue;
        }
        break;
      case 10:
        if (memcmp(kind, "ObjCMethod", 10) == 0) {
          if (I + 3 >= E)
            return insufficient_usr(kind, "<method selector> "
                "[0=class method|1=instance method] <class USR>");
          if (!isUSR(I[3]))
            return not_usr("<class USR>", I[3]);
          else {
            CXString x = createCXString(I[3]);
            print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
          }
          I += 4;
          continue;
        }
        break;
      case 12:
        if (memcmp(kind, "ObjCCategory", 12) == 0) {
          if (I + 2 >= E)
            return insufficient_usr(kind, "<class name> <category name>");
          print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
          I += 3;
          continue;
        }
        if (memcmp(kind, "ObjCProtocol", 12) == 0) {
          if (I + 1 >= E)
            return insufficient_usr(kind, "<protocol name>");
          print_usr(clang_constructUSR_ObjCProtocol(I[1]));
          I += 2;
          continue;
        }
        if (memcmp(kind, "ObjCProperty", 12) == 0) {
          if (I + 2 >= E)
            return insufficient_usr(kind, "<property name> <class USR>");
          if (!isUSR(I[2]))
            return not_usr("<class USR>", I[2]);
          else {
            CXString x = createCXString(I[2]);
            print_usr(clang_constructUSR_ObjCProperty(I[1], x));
          }
          I += 3;
          continue;
        }
        break;
      default:
        break;
    }
    break;
  }

  if (I != E) {
    fprintf(stderr, "Invalid USR kind: %s\n", *I);
    display_usrs();
    return 1;
  }
  return 0;
}

int print_usrs_file(const char *file_name) {
  char line[2048];
  const char *args[128];
  unsigned numChars = 0;

  FILE *fp = fopen(file_name, "r");
  if (!fp) {
    fprintf(stderr, "error: cannot open '%s'\n", file_name);
    return 1;
  }

  /* This code is not really all that safe, but it works fine for testing. */
  while (!feof(fp)) {
    char c = fgetc(fp);
    if (c == '\n') {
      unsigned i = 0;
      const char *s = 0;

      if (numChars == 0)
        continue;

      line[numChars] = '\0';
      numChars = 0;

      if (line[0] == '/' && line[1] == '/')
        continue;

      s = strtok(line, " ");
      while (s) {
        args[i] = s;
        ++i;
        s = strtok(0, " ");
      }
      if (print_usrs(&args[0], &args[i]))
        return 1;
    }
    else
      line[numChars++] = c;
  }

  fclose(fp);
  return 0;
}

/******************************************************************************/
/* Command line processing.                                                   */
/******************************************************************************/
int write_pch_file(const char *filename, int argc, const char *argv[]) {
  CXIndex Idx;
  CXTranslationUnit TU;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  enum CXErrorCode Err;
  int result = 0;
  
  Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
  
  if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
    clang_disposeIndex(Idx);
    return -1;
  }

  Err = clang_parseTranslationUnit2(
      Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
      unsaved_files, num_unsaved_files,
      CXTranslationUnit_Incomplete |
          CXTranslationUnit_DetailedPreprocessingRecord |
          CXTranslationUnit_ForSerialization,
      &TU);
  if (Err != CXError_Success) {
    fprintf(stderr, "Unable to load translation unit!\n");
    describeLibclangFailure(Err);
    free_remapped_files(unsaved_files, num_unsaved_files);
    clang_disposeTranslationUnit(TU);
    clang_disposeIndex(Idx);
    return 1;
  }

  switch (clang_saveTranslationUnit(TU, filename, 
                                    clang_defaultSaveOptions(TU))) {
  case CXSaveError_None:
    break;

  case CXSaveError_TranslationErrors:
    fprintf(stderr, "Unable to write PCH file %s: translation errors\n", 
            filename);
    result = 2;    
    break;

  case CXSaveError_InvalidTU:
    fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n", 
            filename);
    result = 3;    
    break;

  case CXSaveError_Unknown:
  default:
    fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
    result = 1;
    break;
  }
  
  clang_disposeTranslationUnit(TU);
  free_remapped_files(unsaved_files, num_unsaved_files);
  clang_disposeIndex(Idx);
  return result;
}

/******************************************************************************/
/* Serialized diagnostics.                                                    */
/******************************************************************************/

static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
  switch (error) {
    case CXLoadDiag_CannotLoad: return "Cannot Load File";
    case CXLoadDiag_None: break;
    case CXLoadDiag_Unknown: return "Unknown";
    case CXLoadDiag_InvalidFile: return "Invalid File";
  }
  return "None";
}

static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
  switch (severity) {
    case CXDiagnostic_Note: return "note";
    case CXDiagnostic_Error: return "error";
    case CXDiagnostic_Fatal: return "fatal";
    case CXDiagnostic_Ignored: return "ignored";
    case CXDiagnostic_Warning: return "warning";
  }
  return "unknown";
}

static void printIndent(unsigned indent) {
  if (indent == 0)
    return;
  fprintf(stderr, "+");
  --indent;
  while (indent > 0) {
    fprintf(stderr, "-");
    --indent;
  }
}

static void printLocation(CXSourceLocation L) {
  CXFile File;
  CXString FileName;
  unsigned line, column, offset;

  clang_getExpansionLocation(L, &File, &line, &column, &offset);
  FileName = clang_getFileName(File);

  fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
  clang_disposeString(FileName);
}

static void printRanges(CXDiagnostic D, unsigned indent) {
  unsigned i, n = clang_getDiagnosticNumRanges(D);
  
  for (i = 0; i < n; ++i) {
    CXSourceLocation Start, End;
    CXSourceRange SR = clang_getDiagnosticRange(D, i);
    Start = clang_getRangeStart(SR);
    End = clang_getRangeEnd(SR);
    
    printIndent(indent);
    fprintf(stderr, "Range: ");
    printLocation(Start);
    fprintf(stderr, " ");
    printLocation(End);
    fprintf(stderr, "\n");
  }
}

static void printFixIts(CXDiagnostic D, unsigned indent) {
  unsigned i, n = clang_getDiagnosticNumFixIts(D);
  fprintf(stderr, "Number FIXITs = %d\n", n);
  for (i = 0 ; i < n; ++i) {
    CXSourceRange ReplacementRange;
    CXString text;
    text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
    
    printIndent(indent);
    fprintf(stderr, "FIXIT: (");
    printLocation(clang_getRangeStart(ReplacementRange));
    fprintf(stderr, " - ");
    printLocation(clang_getRangeEnd(ReplacementRange));
    fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
    clang_disposeString(text);
  }  
}

static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
  unsigned i, n;

  if (!Diags)
    return;
  
  n = clang_getNumDiagnosticsInSet(Diags);
  for (i = 0; i < n; ++i) {
    CXSourceLocation DiagLoc;
    CXDiagnostic D;
    CXFile File;
    CXString FileName, DiagSpelling, DiagOption, DiagCat;
    unsigned line, column, offset;
    const char *FileNameStr = 0, *DiagOptionStr = 0, *DiagCatStr = 0;
    
    D = clang_getDiagnosticInSet(Diags, i);
    DiagLoc = clang_getDiagnosticLocation(D);
    clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
    FileName = clang_getFileName(File);
    FileNameStr = clang_getCString(FileName);
    DiagSpelling = clang_getDiagnosticSpelling(D);

    printIndent(indent);
    
    fprintf(stderr, "%s:%d:%d: %s: %s",
            FileNameStr ? FileNameStr : "(null)",
            line,
            column,
            getSeverityString(clang_getDiagnosticSeverity(D)),
            clang_getCString(DiagSpelling));

    DiagOption = clang_getDiagnosticOption(D, 0);
    DiagOptionStr = clang_getCString(DiagOption);
    if (DiagOptionStr) {
      fprintf(stderr, " [%s]", DiagOptionStr);
    }
    
    DiagCat = clang_getDiagnosticCategoryText(D);
    DiagCatStr = clang_getCString(DiagCat);
    if (DiagCatStr) {
      fprintf(stderr, " [%s]", DiagCatStr);
    }
    
    fprintf(stderr, "\n");
    
    printRanges(D, indent);
    printFixIts(D, indent);
    
    /* Print subdiagnostics. */
    printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);

    clang_disposeString(FileName);
    clang_disposeString(DiagSpelling);
    clang_disposeString(DiagOption);
    clang_disposeString(DiagCat);
  }  
}

static int read_diagnostics(const char *filename) {
  enum CXLoadDiag_Error error;
  CXString errorString;
  CXDiagnosticSet Diags = 0;
  
  Diags = clang_loadDiagnostics(filename, &error, &errorString);
  if (!Diags) {
    fprintf(stderr, "Trouble deserializing file (%s): %s\n",
            getDiagnosticCodeStr(error),
            clang_getCString(errorString));
    clang_disposeString(errorString);
    return 1;
  }
  
  printDiagnosticSet(Diags, 0);
  fprintf(stderr, "Number of diagnostics: %d\n",
          clang_getNumDiagnosticsInSet(Diags));
  clang_disposeDiagnosticSet(Diags);
  return 0;
}

static int perform_print_build_session_timestamp(void) {
  printf("%lld\n", clang_getBuildSessionTimestamp());
  return 0;
}

/******************************************************************************/
/* Command line processing.                                                   */
/******************************************************************************/

static CXCursorVisitor GetVisitor(const char *s) {
  if (s[0] == '\0')
    return FilteredPrintingVisitor;
  if (strcmp(s, "-usrs") == 0)
    return USRVisitor;
  if (strncmp(s, "-memory-usage", 13) == 0)
    return GetVisitor(s + 13);
  return NULL;
}

static void print_usage(void) {
  fprintf(stderr,
    "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
    "       c-index-test -code-completion-timing=<site> <compiler arguments>\n"
    "       c-index-test -cursor-at=<site> <compiler arguments>\n"
    "       c-index-test -evaluate-cursor-at=<site> <compiler arguments>\n"
    "       c-index-test -get-macro-info-cursor-at=<site> <compiler arguments>\n"
    "       c-index-test -file-refs-at=<site> <compiler arguments>\n"
    "       c-index-test -file-includes-in=<filename> <compiler arguments>\n");
  fprintf(stderr,
    "       c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
    "       c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
    "       c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
    "       c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
    "       c-index-test -test-file-scan <AST file> <source file> "
          "[FileCheck prefix]\n");
  fprintf(stderr,
    "       c-index-test -test-load-tu <AST file> <symbol filter> "
          "[FileCheck prefix]\n"
    "       c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
           "[FileCheck prefix]\n"
    "       c-index-test -test-load-source <symbol filter> {<args>}*\n");
  fprintf(stderr,
    "       c-index-test -test-load-source-memory-usage "
    "<symbol filter> {<args>}*\n"
    "       c-index-test -test-load-source-reparse <trials> <symbol filter> "
    "          {<args>}*\n"
    "       c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
    "       c-index-test -test-load-source-usrs-memory-usage "
          "<symbol filter> {<args>}*\n"
    "       c-index-test -test-annotate-tokens=<range> {<args>}*\n"
    "       c-index-test -test-inclusion-stack-source {<args>}*\n"
    "       c-index-test -test-inclusion-stack-tu <AST file>\n");
  fprintf(stderr,
    "       c-index-test -test-print-linkage-source {<args>}*\n"
    "       c-index-test -test-print-visibility {<args>}*\n"
    "       c-index-test -test-print-type {<args>}*\n"
    "       c-index-test -test-print-type-size {<args>}*\n"
    "       c-index-test -test-print-bitwidth {<args>}*\n"
    "       c-index-test -test-print-target-info {<args>}*\n"
    "       c-index-test -test-print-type-declaration {<args>}*\n"
    "       c-index-test -print-usr [<CursorKind> {<args>}]*\n"
    "       c-index-test -print-usr-file <file>\n");
  fprintf(stderr,
    "       c-index-test -write-pch <file> <compiler arguments>\n"
    "       c-index-test -compilation-db [lookup <filename>] database\n");
  fprintf(stderr,
    "       c-index-test -print-build-session-timestamp\n");
  fprintf(stderr,
    "       c-index-test -read-diagnostics <file>\n\n");
  fprintf(stderr,
    " <symbol filter> values:\n%s",
    "   all - load all symbols, including those from PCH\n"
    "   local - load all symbols except those in PCH\n"
    "   category - only load ObjC categories (non-PCH)\n"
    "   interface - only load ObjC interfaces (non-PCH)\n"
    "   protocol - only load ObjC protocols (non-PCH)\n"
    "   function - only load functions (non-PCH)\n"
    "   typedef - only load typdefs (non-PCH)\n"
    "   scan-function - scan function bodies (non-PCH)\n\n");
}

/***/

int cindextest_main(int argc, const char **argv) {
  clang_enableStackTraces();
  if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
      return read_diagnostics(argv[2]);
  if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
    return perform_code_completion(argc, argv, 0);
  if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
    return perform_code_completion(argc, argv, 1);
  if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
    return inspect_cursor_at(argc, argv, "-cursor-at=", inspect_print_cursor);
  if (argc > 2 && strstr(argv[1], "-evaluate-cursor-at=") == argv[1])
    return inspect_cursor_at(argc, argv, "-evaluate-cursor-at=",
                             inspect_evaluate_cursor);
  if (argc > 2 && strstr(argv[1], "-get-macro-info-cursor-at=") == argv[1])
    return inspect_cursor_at(argc, argv, "-get-macro-info-cursor-at=",
                             inspect_macroinfo_cursor);
  if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
    return find_file_refs_at(argc, argv);
  if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
    return find_file_includes_in(argc, argv);
  if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
    return index_file(argc - 2, argv + 2, /*full=*/0);
  if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
    return index_file(argc - 2, argv + 2, /*full=*/1);
  if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
    return index_tu(argc - 2, argv + 2);
  if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
    return index_compile_db(argc - 2, argv + 2);
  else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
    CXCursorVisitor I = GetVisitor(argv[1] + 13);
    if (I)
      return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
                                  NULL);
  }
  else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
    CXCursorVisitor I = GetVisitor(argv[1] + 25);
    if (I) {
      int trials = atoi(argv[2]);
      return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I, 
                                         NULL);
    }
  }
  else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
    CXCursorVisitor I = GetVisitor(argv[1] + 17);
    
    PostVisitTU postVisit = 0;
    if (strstr(argv[1], "-memory-usage"))
      postVisit = PrintMemoryUsage;
    
    if (I)
      return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
                                      postVisit);
  }
  else if (argc >= 3 && strcmp(argv[1], "-single-file-parse") == 0)
    return perform_single_file_parse(argv[2]);
  else if (argc >= 3 && strcmp(argv[1], "-retain-excluded-conditional-blocks") == 0)
    return perform_file_retain_excluded_cb(argv[2]);
  else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
    return perform_file_scan(argv[2], argv[3],
                             argc >= 5 ? argv[4] : 0);
  else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
    return perform_token_annotation(argc, argv);
  else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
    return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
                                    PrintInclusionStack);
  else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
    return perform_test_load_tu(argv[2], "all", NULL, NULL,
                                PrintInclusionStack);
  else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
    return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
                                    NULL);
  else if (argc > 2 && strcmp(argv[1], "-test-print-visibility") == 0)
    return perform_test_load_source(argc - 2, argv + 2, "all", PrintVisibility,
                                    NULL);
  else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
    return perform_test_load_source(argc - 2, argv + 2, "all",
                                    PrintType, 0);
  else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
    return perform_test_load_source(argc - 2, argv + 2, "all",
                                    PrintTypeSize, 0);
  else if (argc > 2 && strcmp(argv[1], "-test-print-type-declaration") == 0)
    return perform_test_load_source(argc - 2, argv + 2, "all",
                                    PrintTypeDeclaration, 0);
  else if (argc > 2 && strcmp(argv[1], "-test-print-decl-attributes") == 0)
    return perform_test_load_source(argc - 2, argv + 2, "all",
                                    PrintDeclAttributes, 0);
  else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
    return perform_test_load_source(argc - 2, argv + 2, "all",
                                    PrintBitWidth, 0);
  else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
    return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
  else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
    return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
  else if (argc > 2 && strcmp(argv[1], "-test-print-target-info") == 0)
    return print_target_info(argc - 2, argv + 2);
  else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
    if (argc > 2)
      return print_usrs(argv + 2, argv + argc);
    else {
      display_usrs();
      return 1;
    }
  }
  else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
    return print_usrs_file(argv[2]);
  else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
    return write_pch_file(argv[2], argc - 3, argv + 3);
  else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
    return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
  else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
    return perform_print_build_session_timestamp();

  print_usage();
  return 1;
}

/***/

/* We intentionally run in a separate thread to ensure we at least minimal
 * testing of a multithreaded environment (for example, having a reduced stack
 * size). */

typedef struct thread_info {
  int (*main_func)(int argc, const char **argv);
  int argc;
  const char **argv;
  int result;
} thread_info;
void thread_runner(void *client_data_v) {
  thread_info *client_data = client_data_v;
  client_data->result = client_data->main_func(client_data->argc,
                                               client_data->argv);
}

static void flush_atexit(void) {
  /* stdout, and surprisingly even stderr, are not always flushed on process
   * and thread exit, particularly when the system is under heavy load. */
  fflush(stdout);
  fflush(stderr);
}

int main(int argc, const char **argv) {
  thread_info client_data;

  atexit(flush_atexit);

#ifdef CLANG_HAVE_LIBXML
  LIBXML_TEST_VERSION
#endif

  if (argc > 1 && strcmp(argv[1], "core") == 0)
    return indextest_core_main(argc, argv);

  client_data.main_func = cindextest_main;
  client_data.argc = argc;
  client_data.argv = argv;

  if (getenv("CINDEXTEST_NOTHREADS"))
    return client_data.main_func(client_data.argc, client_data.argv);

  clang_executeOnThread(thread_runner, &client_data, 0);
  return client_data.result;
}